summaryrefslogtreecommitdiff
path: root/bridges/UnsplashBridge.php
blob: dad0efc2eaf53f7993843c2d16f8197d225591aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
class UnsplashBridge extends BridgeAbstract {

	const MAINTAINER = 'nel50n';
	const NAME = 'Unsplash Bridge';
	const URI = 'https://unsplash.com/';
	const CACHE_TIMEOUT = 43200; // 12h
	const DESCRIPTION = 'Returns the latests photos from Unsplash';

	const PARAMETERS = array( array(
		'm' => array(
			'name' => 'Max number of photos',
			'type' => 'number',
			'defaultValue' => 20
		),
		'w' => array(
			'name' => 'Width',
			'exampleValue' => '1920, 1680, …',
			'defaultValue' => '1920'
		),
		'q' => array(
			'name' => 'JPEG quality',
			'type' => 'number',
			'defaultValue' => 75
		)
	));

	public function collectData(){
		$width = $this->getInput('w');
		$max = $this->getInput('m');
		$quality = $this->getInput('q');

		$api_response = getContents('https://unsplash.com/napi/photos?page=1&per_page=' . $max)
			or returnServerError('Could not request Unsplash API.');
		$json = json_decode($api_response, true);

		foreach ($json as $json_item) {
			$item = array();

			// Get image URI
			$uri = $json_item['urls']['regular'] . '.jpg'; // '.jpg' only for format hint
			$uri = str_replace('q=80', 'q=' . $quality, $uri);
			$uri = str_replace('w=1080', 'w=' . $width, $uri);
			$item['uri'] = $uri;

			// Get title from description
			if (is_null($json_item['alt_description'])) {
				if (is_null($json_item['description'])) {
					$item['title'] = 'Unsplash picture from ' . $json_item['user']['name'];
				} else {
					$item['title'] = $json_item['description'];
				}
			} else {
				$item['title'] = $json_item['alt_description'];
			}

			$item['timestamp'] = time();
			$item['content'] = $item['title']
				. '<br><a href="'
				. $item['uri']
				. '"><img src="'
				. $json_item['urls']['thumb']
				. '" /></a>';

			$this->items[] = $item;
		}
	}
}