google.php 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. class GoogleRequest extends EngineRequest {
  3. public function get_request_url() {
  4. $query_encoded = str_replace("%22", "\"", urlencode($this->query));
  5. $results = array();
  6. $domain = $this->opts->google_domain;
  7. $results_language = $this->opts->language;
  8. $number_of_results = $this->opts->number_of_results;
  9. $url = "https://www.google.$domain/search?q=$query_encoded&nfpr=1&start=$this->page";
  10. if (3 > strlen($results_language) && 0 < strlen($results_language)) {
  11. $url .= "&lr=lang_$results_language";
  12. $url .= "&hl=$results_language";
  13. }
  14. if (3 > strlen($number_of_results) && 0 < strlen($number_of_results))
  15. $url .= "&num=$number_of_results";
  16. if (isset($_COOKIE["safe_search"]))
  17. $url .= "&safe=medium";
  18. return $url;
  19. }
  20. public function parse_results($response) {
  21. $results = array();
  22. $xpath = get_xpath($response);
  23. if (!$xpath)
  24. return $results;
  25. $didyoumean = $xpath->query(".//a[@class='gL9Hy']")[0];
  26. if (!is_null($didyoumean))
  27. array_push($results, array(
  28. "did_you_mean" => $didyoumean->textContent
  29. ));
  30. foreach($xpath->query("//div[@id='search']//div[contains(@class, 'g')]") as $result) {
  31. $url = $xpath->evaluate(".//div[@class='yuRUbf']//a/@href", $result)[0];
  32. if ($url == null)
  33. continue;
  34. if (!empty($results) && array_key_exists("url", end($results)) && end($results)["url"] == $url->textContent)
  35. continue;
  36. $url = $url->textContent;
  37. $title = $xpath->evaluate(".//h3", $result)[0];
  38. $description = $xpath->evaluate(".//div[contains(@class, 'VwiC3b')]", $result)[0];
  39. array_push($results,
  40. array (
  41. "title" => htmlspecialchars($title->textContent),
  42. "url" => htmlspecialchars($url),
  43. // base_url is to be removed in the future, see #47
  44. "base_url" => htmlspecialchars(get_base_url($url)),
  45. "description" => $description == null ?
  46. TEXTS["result_no_description"] :
  47. htmlspecialchars($description->textContent)
  48. )
  49. );
  50. }
  51. if (empty($results) && !str_contains($response, "Our systems have detected unusual traffic from your computer network.")) {
  52. $results["error"] = array(
  53. "message" => TEXTS["failure_empty"]
  54. );
  55. }
  56. return $results;
  57. }
  58. }
  59. ?>