api.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. <?php
  2. // Prepare cURL object with options for the search query
  3. function prepareSearchCurlObj($query, $bookmark = null, $url, $csrftoken = null, $header_function) {
  4. $data_param_obj = [
  5. "options" => [
  6. "query" => $query,
  7. "bookmarks" => $bookmark ? [$bookmark] : null
  8. ]
  9. ];
  10. $data_param = urlencode(json_encode(array_filter($data_param_obj['options'])));
  11. $headers = [];
  12. if ($csrftoken) {
  13. $headers[] = "x-csrftoken: $csrftoken";
  14. $headers[] = "cookie: csrftoken=$csrftoken";
  15. }
  16. $finalurl = $bookmark ? $url : "$url?data=$data_param";
  17. $ch = curl_init($finalurl);
  18. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  19. curl_setopt($ch, CURLOPT_HEADERFUNCTION, $header_function);
  20. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  21. if ($bookmark) {
  22. curl_setopt($ch, CURLOPT_POST, true);
  23. curl_setopt($ch, CURLOPT_POSTFIELDS, "data=$data_param");
  24. }
  25. return $ch;
  26. }
  27. // Search function to execute the cURL request and process the response
  28. function search($query, $bookmark, $url, $csrftoken, $header_function) {
  29. $ch = prepareSearchCurlObj($query, $bookmark, $url, $csrftoken, $header_function);
  30. $response = curl_exec($ch);
  31. if ($response === false) {
  32. // Handle cURL error
  33. $error = curl_error($ch);
  34. curl_close($ch);
  35. return json_encode(['error' => 'CURL Error: ' . $error]);
  36. }
  37. curl_close($ch); // Close cURL handle
  38. $data = json_decode($response);
  39. $images = [];
  40. if (isset($data->resource_response->data->results)) {
  41. foreach ($data->resource_response->data->results as $result) {
  42. $url = $result->images->orig->url ?? null; // Use null coalescing for safety
  43. if ($url) {
  44. $images[] = $url;
  45. }
  46. }
  47. }
  48. $result = new SearchResult();
  49. $result->images = $images;
  50. $result->bookmark = $data->resource_response->bookmark ?? null;
  51. return $result;
  52. }
  53. // Main execution
  54. header("Content-Type: application/json");
  55. $result = search($query, $bookmark, $url, $csrftoken, $header_function);
  56. // Handle bookmark for pagination
  57. if ($result->bookmark) {
  58. $query_encoded = urlencode($query);
  59. $bookmark_encoded = urlencode($result->bookmark);
  60. $csrftoken_encoded = urlencode($csrftoken);
  61. // Uncomment below line to display the link for next page
  62. // echo "<h2 style=\"text-align: center;\"><a href=\"/search.php?q=$query_encoded&bookmark=$bookmark_encoded&csrftoken=$csrftoken_encoded\">Next page</a></h2><br><br><br>";
  63. }
  64. echo json_encode($result);
  65. ?>