You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

66 lines
2.2 KiB

  1. <?php
  2. // AJAX call to fetch a new background image
  3. // http://stackoverflow.com/a/24707821 => use instead of file_get_contents for external URL's
  4. function curl_get_contents($url, $headers = null) {
  5. $ch = curl_init();
  6. curl_setopt($ch, CURLOPT_HEADER, 0);
  7. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  8. curl_setopt($ch, CURLOPT_URL, $url);
  9. // Include potential headers with request
  10. if (!empty($headers)) {
  11. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  12. }
  13. $data = curl_exec($ch);
  14. curl_close($ch);
  15. return $data;
  16. }
  17. // Traverse a JSON object given a string selector
  18. function traverse_json($json, $selector) {
  19. $regex = "\[\'?([{}a-z0-9_]+)\'?\]";
  20. preg_match_all('/' . $regex . '/i', $selector, $matches);
  21. // Go through each regex match and traverse the JSON object given the keys
  22. $obj = $json;
  23. foreach ($matches[1] as $i => $match) {
  24. if ($match == '{random}' && is_array($obj)) {
  25. // Let's fetch a random index of the array
  26. $rand = rand(0, count($obj));
  27. $obj = $obj[$rand];
  28. } else {
  29. // Keep traversing the object
  30. $obj = $obj[$match];
  31. }
  32. }
  33. return $obj;
  34. }
  35. $config = json_decode(file_get_contents(dirname(__FILE__) . "/../../config.json"), true);
  36. if (!empty($config['custom_url'])) {
  37. // We're fetching from a custom URL
  38. $json = json_decode(curl_get_contents($config['custom_url'], $config['custom_url_headers']), true);
  39. $image_url = traverse_json($json, $config['custom_url_selector']);
  40. echo json_encode(array('success' => 1, 'url' => $image_url));
  41. } else if (!empty($config['unsplash_client_id'])) {
  42. // We're fetching from Unsplash's API
  43. $url = "https://api.unsplash.com/photos/random?per_page=1&client_id=" . $config['unsplash_client_id'];
  44. $json = json_decode(curl_get_contents($url), true);
  45. $image_url = $json['urls']['regular'];
  46. $image_user_name = $json['user']['name'];
  47. $image_user_url = $json['user']['links']['html'];
  48. echo json_encode(array('success' => 1, 'url' => $image_url, 'image_user_name' => $image_user_name, 'image_user_url' => $image_user_url));
  49. }
  50. die();
  51. ?>