google_cse.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008
  1. <?php
  2. class google_cse{
  3. public const req_html = 0;
  4. public const req_js = 1;
  5. public function __construct(){
  6. include "lib/backend.php";
  7. $this->backend = new backend("google_cse");
  8. include "lib/fuckhtml.php";
  9. $this->fuckhtml = new fuckhtml();
  10. }
  11. public function getfilters($page){
  12. $base = [
  13. "country" => [ // gl=<country> (image: cr=countryAF)
  14. "display" => "Country",
  15. "option" => [
  16. "any" => "Any country",
  17. "af" => "Afghanistan",
  18. "al" => "Albania",
  19. "dz" => "Algeria",
  20. "as" => "American Samoa",
  21. "ad" => "Andorra",
  22. "ao" => "Angola",
  23. "ai" => "Anguilla",
  24. "aq" => "Antarctica",
  25. "ag" => "Antigua and Barbuda",
  26. "ar" => "Argentina",
  27. "am" => "Armenia",
  28. "aw" => "Aruba",
  29. "au" => "Australia",
  30. "at" => "Austria",
  31. "az" => "Azerbaijan",
  32. "bs" => "Bahamas",
  33. "bh" => "Bahrain",
  34. "bd" => "Bangladesh",
  35. "bb" => "Barbados",
  36. "by" => "Belarus",
  37. "be" => "Belgium",
  38. "bz" => "Belize",
  39. "bj" => "Benin",
  40. "bm" => "Bermuda",
  41. "bt" => "Bhutan",
  42. "bo" => "Bolivia",
  43. "ba" => "Bosnia and Herzegovina",
  44. "bw" => "Botswana",
  45. "bv" => "Bouvet Island",
  46. "br" => "Brazil",
  47. "io" => "British Indian Ocean Territory",
  48. "bn" => "Brunei Darussalam",
  49. "bg" => "Bulgaria",
  50. "bf" => "Burkina Faso",
  51. "bi" => "Burundi",
  52. "kh" => "Cambodia",
  53. "cm" => "Cameroon",
  54. "ca" => "Canada",
  55. "cv" => "Cape Verde",
  56. "ky" => "Cayman Islands",
  57. "cf" => "Central African Republic",
  58. "td" => "Chad",
  59. "cl" => "Chile",
  60. "cn" => "China",
  61. "cx" => "Christmas Island",
  62. "cc" => "Cocos (Keeling) Islands",
  63. "co" => "Colombia",
  64. "km" => "Comoros",
  65. "cg" => "Congo",
  66. "cd" => "Congo, the Democratic Republic",
  67. "ck" => "Cook Islands",
  68. "cr" => "Costa Rica",
  69. "ci" => "Cote D'ivoire",
  70. "hr" => "Croatia",
  71. "cu" => "Cuba",
  72. "cy" => "Cyprus",
  73. "cz" => "Czech Republic",
  74. "dk" => "Denmark",
  75. "dj" => "Djibouti",
  76. "dm" => "Dominica",
  77. "do" => "Dominican Republic",
  78. "ec" => "Ecuador",
  79. "eg" => "Egypt",
  80. "sv" => "El Salvador",
  81. "gq" => "Equatorial Guinea",
  82. "er" => "Eritrea",
  83. "ee" => "Estonia",
  84. "et" => "Ethiopia",
  85. "fk" => "Falkland Islands (Malvinas)",
  86. "fo" => "Faroe Islands",
  87. "fj" => "Fiji",
  88. "fi" => "Finland",
  89. "fr" => "France",
  90. "gf" => "French Guiana",
  91. "pf" => "French Polynesia",
  92. "tf" => "French Southern Territories",
  93. "ga" => "Gabon",
  94. "gm" => "Gambia",
  95. "ge" => "Georgia",
  96. "de" => "Germany",
  97. "gh" => "Ghana",
  98. "gi" => "Gibraltar",
  99. "gr" => "Greece",
  100. "gl" => "Greenland",
  101. "gd" => "Grenada",
  102. "gp" => "Guadeloupe",
  103. "gu" => "Guam",
  104. "gt" => "Guatemala",
  105. "gn" => "Guinea",
  106. "gw" => "Guinea-Bissau",
  107. "gy" => "Guyana",
  108. "ht" => "Haiti",
  109. "hm" => "Heard Island and Mcdonald Islands",
  110. "va" => "Holy See (Vatican City State)",
  111. "hn" => "Honduras",
  112. "hk" => "Hong Kong",
  113. "hu" => "Hungary",
  114. "is" => "Iceland",
  115. "in" => "India",
  116. "id" => "Indonesia",
  117. "ir" => "Iran, Islamic Republic",
  118. "iq" => "Iraq",
  119. "ie" => "Ireland",
  120. "il" => "Israel",
  121. "it" => "Italy",
  122. "jm" => "Jamaica",
  123. "jp" => "Japan",
  124. "jo" => "Jordan",
  125. "kz" => "Kazakhstan",
  126. "ke" => "Kenya",
  127. "ki" => "Kiribati",
  128. "kp" => "Korea, Democratic People's Republic",
  129. "kr" => "Korea, Republic",
  130. "kw" => "Kuwait",
  131. "kg" => "Kyrgyzstan",
  132. "la" => "Lao People's Democratic Republic",
  133. "lv" => "Latvia",
  134. "lb" => "Lebanon",
  135. "ls" => "Lesotho",
  136. "lr" => "Liberia",
  137. "ly" => "Libyan Arab Jamahiriya",
  138. "li" => "Liechtenstein",
  139. "lt" => "Lithuania",
  140. "lu" => "Luxembourg",
  141. "mo" => "Macao",
  142. "mk" => "Macedonia, the Former Yugosalv Republic",
  143. "mg" => "Madagascar",
  144. "mw" => "Malawi",
  145. "my" => "Malaysia",
  146. "mv" => "Maldives",
  147. "ml" => "Mali",
  148. "mt" => "Malta",
  149. "mh" => "Marshall Islands",
  150. "mq" => "Martinique",
  151. "mr" => "Mauritania",
  152. "mu" => "Mauritius",
  153. "yt" => "Mayotte",
  154. "mx" => "Mexico",
  155. "fm" => "Micronesia, Federated States",
  156. "md" => "Moldova, Republic",
  157. "mc" => "Monaco",
  158. "mn" => "Mongolia",
  159. "ms" => "Montserrat",
  160. "ma" => "Morocco",
  161. "mz" => "Mozambique",
  162. "mm" => "Myanmar",
  163. "na" => "Namibia",
  164. "nr" => "Nauru",
  165. "np" => "Nepal",
  166. "nl" => "Netherlands",
  167. "an" => "Netherlands Antilles",
  168. "nc" => "New Caledonia",
  169. "nz" => "New Zealand",
  170. "ni" => "Nicaragua",
  171. "ne" => "Niger",
  172. "ng" => "Nigeria",
  173. "nu" => "Niue",
  174. "nf" => "Norfolk Island",
  175. "mp" => "Northern Mariana Islands",
  176. "no" => "Norway",
  177. "om" => "Oman",
  178. "pk" => "Pakistan",
  179. "pw" => "Palau",
  180. "ps" => "Palestinian Territory, Occupied",
  181. "pa" => "Panama",
  182. "pg" => "Papua New Guinea",
  183. "py" => "Paraguay",
  184. "pe" => "Peru",
  185. "ph" => "Philippines",
  186. "pn" => "Pitcairn",
  187. "pl" => "Poland",
  188. "pt" => "Portugal",
  189. "pr" => "Puerto Rico",
  190. "qa" => "Qatar",
  191. "re" => "Reunion",
  192. "ro" => "Romania",
  193. "ru" => "Russian Federation",
  194. "rw" => "Rwanda",
  195. "sh" => "Saint Helena",
  196. "kn" => "Saint Kitts and Nevis",
  197. "lc" => "Saint Lucia",
  198. "pm" => "Saint Pierre and Miquelon",
  199. "vc" => "Saint Vincent and the Grenadines",
  200. "ws" => "Samoa",
  201. "sm" => "San Marino",
  202. "st" => "Sao Tome and Principe",
  203. "sa" => "Saudi Arabia",
  204. "sn" => "Senegal",
  205. "cs" => "Serbia and Montenegro",
  206. "sc" => "Seychelles",
  207. "sl" => "Sierra Leone",
  208. "sg" => "Singapore",
  209. "sk" => "Slovakia",
  210. "si" => "Slovenia",
  211. "sb" => "Solomon Islands",
  212. "so" => "Somalia",
  213. "za" => "South Africa",
  214. "gs" => "South Georgia and the South Sandwich Islands",
  215. "es" => "Spain",
  216. "lk" => "Sri Lanka",
  217. "sd" => "Sudan",
  218. "sr" => "Suriname",
  219. "sj" => "Svalbard and Jan Mayen",
  220. "sz" => "Swaziland",
  221. "se" => "Sweden",
  222. "ch" => "Switzerland",
  223. "sy" => "Syrian Arab Republic",
  224. "tw" => "Taiwan, Province of China",
  225. "tj" => "Tajikistan",
  226. "tz" => "Tanzania, United Republic",
  227. "th" => "Thailand",
  228. "tl" => "Timor-Leste",
  229. "tg" => "Togo",
  230. "tk" => "Tokelau",
  231. "to" => "Tonga",
  232. "tt" => "Trinidad and Tobago",
  233. "tn" => "Tunisia",
  234. "tr" => "Turkey",
  235. "tm" => "Turkmenistan",
  236. "tc" => "Turks and Caicos Islands",
  237. "tv" => "Tuvalu",
  238. "ug" => "Uganda",
  239. "ua" => "Ukraine",
  240. "ae" => "United Arab Emirates",
  241. "uk" => "United Kingdom",
  242. "us" => "United States",
  243. "um" => "United States Minor Outlying Islands",
  244. "uy" => "Uruguay",
  245. "uz" => "Uzbekistan",
  246. "vu" => "Vanuatu",
  247. "ve" => "Venezuela",
  248. "vn" => "Viet Nam",
  249. "vg" => "Virgin Islands, British",
  250. "vi" => "Virgin Islands, U.S.",
  251. "wf" => "Wallis and Futuna",
  252. "eh" => "Western Sahara",
  253. "ye" => "Yemen",
  254. "zm" => "Zambia",
  255. "zw" => "Zimbabwe"
  256. ]
  257. ],
  258. "nsfw" => [
  259. "display" => "NSFW",
  260. "option" => [
  261. "yes" => "Yes", // safe=active
  262. "no" => "No" // safe=off
  263. ]
  264. ]
  265. ];
  266. switch($page){
  267. case "web":
  268. return array_merge(
  269. $base,
  270. [
  271. "lang" => [ // lr=<lang> (prefix lang with "lang_")
  272. "display" => "Language",
  273. "option" => [
  274. "any" => "Any language",
  275. "ar" => "Arabic",
  276. "bg" => "Bulgarian",
  277. "ca" => "Catalan",
  278. "cs" => "Czech",
  279. "da" => "Danish",
  280. "de" => "German",
  281. "el" => "Greek",
  282. "en" => "English",
  283. "es" => "Spanish",
  284. "et" => "Estonian",
  285. "fi" => "Finnish",
  286. "fr" => "French",
  287. "hr" => "Croatian",
  288. "hu" => "Hungarian",
  289. "id" => "Indonesian",
  290. "is" => "Icelandic",
  291. "it" => "Italian",
  292. "iw" => "Hebrew",
  293. "ja" => "Japanese",
  294. "ko" => "Korean",
  295. "lt" => "Lithuanian",
  296. "lv" => "Latvian",
  297. "nl" => "Dutch",
  298. "no" => "Norwegian",
  299. "pl" => "Polish",
  300. "pt" => "Portuguese",
  301. "ro" => "Romanian",
  302. "ru" => "Russian",
  303. "sk" => "Slovak",
  304. "sl" => "Slovenian",
  305. "sr" => "Serbian",
  306. "sv" => "Swedish",
  307. "tr" => "Turkish",
  308. "zh-CN" => "Chinese (Simplified)",
  309. "zh-TW" => "Chinese (Traditional)"
  310. ]
  311. ],
  312. "sort" => [
  313. "display" => "Sort by",
  314. "option" => [
  315. "relevance" => "Relevance",
  316. "date" => "Date"
  317. ]
  318. ],
  319. "redundant" => [
  320. "display" => "Remove redundant",
  321. "option" => [
  322. "yes" => "Yes",
  323. "no" => "No",
  324. ]
  325. ]
  326. ]
  327. );
  328. break;
  329. case "images":
  330. return array_merge(
  331. $base,
  332. [
  333. "size" => [ // imgsz
  334. "display" => "Size",
  335. "option" => [
  336. "any" => "Any size",
  337. "l" => "Large",
  338. "m" => "Medium",
  339. "i" => "Icon",
  340. "qsvga" => "Larger than 400x300",
  341. "vga" => "Larger than 640x480",
  342. "svga" => "Larger than 800x600",
  343. "xga" => "Larger than 1024x768",
  344. "2mp" => "Larger than 2MP",
  345. "4mp" => "Larger than 4MP",
  346. "6mp" => "Larger than 6MP",
  347. "8mp" => "Larger than 8MP",
  348. "10mp" => "Larger than 10MP",
  349. "12mp" => "Larger than 12MP",
  350. "15mp" => "Larger than 15MP",
  351. "20mp" => "Larger than 20MP",
  352. "40mp" => "Larger than 40MP",
  353. "70mp" => "Larger than 70MP"
  354. ]
  355. ],
  356. "color" => [ // imgc
  357. "display" => "Color",
  358. "option" => [
  359. "any" => "Any color",
  360. "color" => "Full color",
  361. "bnw" => "Black & white",
  362. "trans" => "Transparent",
  363. // from here, imgcolor
  364. "red" => "Red",
  365. "orange" => "Orange",
  366. "yellow" => "Yellow",
  367. "green" => "Green",
  368. "teal" => "Teal",
  369. "blue" => "Blue",
  370. "purple" => "Purple",
  371. "pink" => "Pink",
  372. "white" => "White",
  373. "gray" => "Gray",
  374. "black" => "Black",
  375. "brown" => "Brown"
  376. ]
  377. ],
  378. "format" => [ // as_filetype
  379. "display" => "Format",
  380. "option" => [
  381. "any" => "Any format",
  382. "jpg" => "JPG",
  383. "gif" => "GIF",
  384. "png" => "PNG",
  385. "bmp" => "BMP",
  386. "svg" => "SVG",
  387. "webp" => "WEBP",
  388. "ico" => "ICO",
  389. "craw" => "RAW"
  390. ]
  391. ]
  392. ]
  393. );
  394. break;
  395. }
  396. }
  397. private function get($proxy, $url, $get = [], $reqtype = self::req_js){
  398. $curlproc = curl_init();
  399. if($get !== []){
  400. $get = http_build_query($get);
  401. $url .= "?" . $get;
  402. }
  403. curl_setopt($curlproc, CURLOPT_URL, $url);
  404. // http2 bypass
  405. curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
  406. curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding
  407. if($reqtype === self::req_js){
  408. curl_setopt($curlproc, CURLOPT_HTTPHEADER,
  409. ["User-Agent: " . config::USER_AGENT,
  410. "Accept: */*",
  411. "Accept-Language: en-US,en;q=0.5",
  412. "Accept-Encoding: gzip",
  413. "DNT: 1",
  414. "Sec-GPC: 1",
  415. "Alt-Used: cse.google.com",
  416. "Connection: keep-alive",
  417. "Referer: https://cse.google.com/cse?cx=" . config::GOOGLE_CX_ENDPOINT,
  418. "Sec-Fetch-Dest: script",
  419. "Sec-Fetch-Mode: no-cors",
  420. "Sec-Fetch-Site: same-origin",
  421. "TE: trailers"]
  422. );
  423. }else{
  424. curl_setopt($curlproc, CURLOPT_HTTPHEADER,
  425. ["User-Agent: " . config::USER_AGENT,
  426. "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8",
  427. "Accept-Language: en-US,en;q=0.5",
  428. "Accept-Encoding: gzip",
  429. "DNT: 1",
  430. "Sec-GPC: 1",
  431. "Connection: keep-alive",
  432. "Upgrade-Insecure-Requests: 1",
  433. "Sec-Fetch-Dest: document",
  434. "Sec-Fetch-Mode: navigate",
  435. "Sec-Fetch-Site: none",
  436. "Sec-Fetch-User: ?1",
  437. "Priority: u=0, i"]
  438. );
  439. }
  440. curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true);
  441. curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2);
  442. curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true);
  443. curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30);
  444. curl_setopt($curlproc, CURLOPT_TIMEOUT, 30);
  445. $this->backend->assign_proxy($curlproc, $proxy);
  446. $data = curl_exec($curlproc);
  447. if(curl_errno($curlproc)){
  448. throw new Exception(curl_error($curlproc));
  449. }
  450. curl_close($curlproc);
  451. return $data;
  452. }
  453. public function web($get){
  454. // page 1
  455. // https://cse.google.com/cse/element/v1?rsz=filtered_cse&num=10&hl=en&source=gcsc&cselibv=8fa85d58e016b414&cx=d4e68b99b876541f0&q=asmr&safe=active&cse_tok=AB-tC_6RPUTmB4XK0lE9e1AFFC5r%3A1729563832926&lr=&cr=&gl=&filter=0&sort=&as_oq=&as_sitesearch=&exp=cc%2Capo&oq=asmr&gs_l=partner-web.3..0i512i433j0i512i433i131l2j0i512i433j0i512i433i131j0i512i433j0i512i433i131l2j0i512l2.10902.266627.5.267157.11.10.0.0.0.0.188.1108.2j7.9.0.csems%2Cnrl%3D10...0....1.34.partner-web..42.14.1500.WJQvMvfXkx4&cseclient=hosted-page-client&callback=google.search.cse.api8223&rurl=https%3A%2F%2Fcse.google.com%2Fcse%3Fcx%3Dd4e68b99b876541f0%23gsc.tab%3D0%26gsc.q%3Dtest%26gsc.sort%3D
  456. // page 2
  457. // https://cse.google.com/cse/element/v1?rsz=filtered_cse&num=10&hl=en&source=gcsc&start=10&cselibv=8fa85d58e016b414&cx=d4e68b99b876541f0&q=asmr&safe=active&cse_tok=AB-tC_6RPUTmB4XK0lE9e1AFFC5r%3A1729563832926&lr=&cr=&gl=&filter=0&sort=&as_oq=&as_sitesearch=&exp=cc%2Capo&callback=google.search.cse.api3595&rurl=https%3A%2F%2Fcse.google.com%2Fcse%3Fcx%3Dd4e68b99b876541f0%23gsc.tab%3D0%26gsc.q%3Dtest%26gsc.sort%3D
  458. if($get["npt"]){
  459. [$req_params, $proxy] =
  460. $this->backend->get(
  461. $get["npt"],
  462. "web"
  463. );
  464. $req_params =
  465. json_decode(
  466. $req_params,
  467. true
  468. );
  469. $json =
  470. $this->get(
  471. $proxy,
  472. "https://cse.google.com/cse/element/v1",
  473. $req_params,
  474. self::req_js
  475. );
  476. }else{
  477. $proxy = $this->backend->get_ip();
  478. $params = $this->generate_token($proxy);
  479. //$json = file_get_contents("scraper/google_cse.txt");
  480. $req_params = [
  481. "rsz" => "filtered_cse",
  482. "num" => 20,
  483. "hl" => "en",
  484. "source" => "gcsc",
  485. "cselibv" => $params["lib"],
  486. "cx" => config::GOOGLE_CX_ENDPOINT,
  487. "q" => $get["s"],
  488. "safe" => $get["nsfw"] == "yes" ? "off" : "active",
  489. "cse_tok" => $params["token"],
  490. "lr" => $get["lang"] == "any" ? "" : "lang_" . $get["lang"],
  491. "cr" => $get["country"] == "any" ? "" : "country" . strtoupper($get["country"]),
  492. "gl" => "",
  493. "filter" => $get["redundant"] == "yes" ? "1" : "0",
  494. "sort" => $get["sort"] == "relevance" ? "" : "date",
  495. "as_oq" => "",
  496. "as_sitesearch" => "",
  497. "exp" => "cc,apo",
  498. "oq" => $get["s"],
  499. "gs_l" => "partner-web.3...33294.34225.3.34597.26.11.0.0.0.0.201.1132.6j4j1.11.0.csems,nrl=10...0....1.34.partner-web..34.19.1897.FKEeG5yh2iw",
  500. "cseclient" => "hosted-page-client",
  501. "callback" => "google.search.cse.api" . random_int(4000, 99999),
  502. "rurl" => "https://cse.google.com/cse?cx=" . config::GOOGLE_CX_ENDPOINT . "#gsc.tab=0&gsc.q=" . $get["s"] . "&gsc.sort="
  503. ];
  504. $json =
  505. $this->get(
  506. $proxy,
  507. "https://cse.google.com/cse/element/v1",
  508. $req_params,
  509. self::req_js
  510. );
  511. unset($req_params["gs_l"]);
  512. $req_params["start"] = 0;
  513. }
  514. $req_params["start"] += 20;
  515. if(
  516. !preg_match(
  517. '/google\.search\.cse\.[A-Za-z0-9]+\(([\S\s]*)\);/i',
  518. $json,
  519. $json
  520. )
  521. ){
  522. throw new Exception("Failed to grep JSON");
  523. }
  524. $json = json_decode($json[1], true);
  525. if(isset($json["error"])){
  526. if(isset($json["error"]["errors"][0]["message"])){
  527. throw new Exception("Google returned an error: " . $json["error"]["errors"][0]["message"]);
  528. }
  529. if(isset($json["error"]["message"])){
  530. throw new Exception("Google returned an error: " . $json["error"]["message"]);
  531. }
  532. throw new Exception("Google returned an error object");
  533. }
  534. $out = [
  535. "status" => "ok",
  536. "spelling" => [
  537. "type" => "no_correction",
  538. "using" => null,
  539. "correction" => null
  540. ],
  541. "npt" => null,
  542. "answer" => [],
  543. "web" => [],
  544. "image" => [],
  545. "video" => [],
  546. "news" => [],
  547. "related" => []
  548. ];
  549. if(!isset($json["results"])){
  550. return $out;
  551. }
  552. foreach($json["results"] as $result){
  553. // get date from description
  554. $description =
  555. explode(
  556. "...",
  557. trim($result["contentNoFormatting"], " ."),
  558. 2
  559. );
  560. if(count($description) === 2){
  561. if($date = strtotime($description[0])){
  562. $description = ltrim($description[1]);
  563. }else{
  564. $date = null;
  565. $description = implode("...", $description);
  566. }
  567. }else{
  568. $description = implode("...", $description);
  569. $date = null;
  570. }
  571. $description = trim($description, " .");
  572. // get thumbnails
  573. if(isset($result["richSnippet"]["cseThumbnail"]["src"])){
  574. $thumb = [
  575. "url" => $this->unshit_thumb($result["richSnippet"]["cseThumbnail"]["src"]),
  576. "ratio" => "1:1"
  577. ];
  578. }
  579. elseif(isset($result["richSnippet"]["cseImage"]["src"])){
  580. $thumb = [
  581. "url" => $result["richSnippet"]["cseImage"]["src"],
  582. "ratio" => "1:1"
  583. ];
  584. }else{
  585. $thumb = [
  586. "url" => null,
  587. "ratio" => null
  588. ];
  589. }
  590. if($thumb["url"] !== null){
  591. $found_size = false;
  592. // find correct ratio
  593. if(
  594. isset($result["richSnippet"]["cseThumbnail"]["width"]) &&
  595. isset($result["richSnippet"]["cseThumbnail"]["height"])
  596. ){
  597. $found_size = true;
  598. $width = (int)$result["richSnippet"]["cseThumbnail"]["width"];
  599. $height = (int)$result["richSnippet"]["cseThumbnail"]["height"];
  600. }
  601. elseif(
  602. isset($result["richSnippet"]["metatags"]["ogImageWidth"]) &&
  603. isset($result["richSnippet"]["metatags"]["ogImageHeight"])
  604. ){
  605. $found_size = true;
  606. $width = (int)$result["richSnippet"]["metatags"]["ogImageWidth"];
  607. $height = (int)$result["richSnippet"]["metatags"]["ogImageHeight"];
  608. }
  609. // calculate rounded ratio
  610. if($found_size){
  611. $aspect_ratio = $width / $height;
  612. if($aspect_ratio >= 1.5){
  613. $thumb["ratio"] = "16:9";
  614. }
  615. elseif($aspect_ratio >= 0.8){
  616. $thumb["ratio"] = "1:1";
  617. }else{
  618. $thumb["ratio"] = "9:16";
  619. }
  620. }
  621. }
  622. $out["web"][] = [
  623. "title" => rtrim($result["titleNoFormatting"], " ."),
  624. "description" => $description,
  625. "url" => $result["unescapedUrl"],
  626. "date" => $date,
  627. "type" => "web",
  628. "thumb" => $thumb,
  629. "sublink" => [],
  630. "table" => []
  631. ];
  632. }
  633. // detect next page
  634. if(
  635. isset($json["cursor"]["isExactTotalResults"]) || // detects last page
  636. !isset($json["cursor"]["pages"]) // detects no results on page
  637. ){
  638. return $out;
  639. }
  640. // get next page
  641. $out["npt"] =
  642. $this->backend->store(
  643. json_encode(
  644. $req_params
  645. ),
  646. "web",
  647. $proxy
  648. );
  649. return $out;
  650. }
  651. public function image($get){
  652. if($get["npt"]){
  653. [$req_params, $proxy] =
  654. $this->backend->get(
  655. $get["npt"],
  656. "images"
  657. );
  658. $req_params =
  659. json_decode(
  660. $req_params,
  661. true
  662. );
  663. $json =
  664. $this->get(
  665. $proxy,
  666. "https://cse.google.com/cse/element/v1",
  667. $req_params,
  668. self::req_js
  669. );
  670. }else{
  671. $proxy = $this->backend->get_ip();
  672. $params = $this->generate_token($proxy);
  673. //$json = file_get_contents("scraper/google_cse.txt");
  674. $req_params = [
  675. "rsz" => "filtered_cse",
  676. "num" => 20,
  677. "hl" => "en",
  678. "source" => "gcsc",
  679. "cselibv" => $params["lib"],
  680. "searchtype" => "image",
  681. "cx" => config::GOOGLE_CX_ENDPOINT,
  682. "q" => $get["s"],
  683. "safe" => $get["nsfw"] == "yes" ? "off" : "active",
  684. "cse_tok" => $params["token"],
  685. "exp" => "cc,apo",
  686. "cseclient" => "hosted-page-client",
  687. "callback" => "google.search.cse.api" . random_int(4000, 99999),
  688. "rurl" => "https://cse.google.com/cse?cx=" . config::GOOGLE_CX_ENDPOINT . "#gsc.tab=1&gsc.q=" . $get["s"] . "&gsc.sort="
  689. ];
  690. // add additional hidden filters
  691. // country (image search uses cr instead of gl)
  692. if($get["country"] != "any"){
  693. $req_params["cr"] = "country" . strtoupper($get["country"]);
  694. }
  695. // nsfw
  696. $req_params["safe"] = $get["nsfw"] == "yes" ? "off" : "active";
  697. // size
  698. if($get["size"] != "any"){
  699. $req_params["imgsz"] = $get["size"];
  700. }
  701. // format
  702. if($get["format"] != "any"){
  703. $req_params["as_filetype"] = $get["format"];
  704. }
  705. // color
  706. if($get["color"] != "any"){
  707. if(
  708. $get["color"] == "color" ||
  709. $get["color"] == "trans"
  710. ){
  711. $req_params["imgc"] = $get["color"];
  712. }elseif($get["color"] == "bnw"){
  713. $req_params["imgc"] = "gray";
  714. }else{
  715. $req_params["imgcolor"] = $get["color"];
  716. }
  717. }
  718. $json =
  719. $this->get(
  720. $proxy,
  721. "https://cse.google.com/cse/element/v1",
  722. $req_params,
  723. self::req_js
  724. );
  725. $req_params["start"] = 0;
  726. }
  727. $req_params["start"] += 20;
  728. if(
  729. !preg_match(
  730. '/google\.search\.cse\.[A-Za-z0-9]+\(([\S\s]*)\);/i',
  731. $json,
  732. $json
  733. )
  734. ){
  735. throw new Exception("Failed to grep JSON");
  736. }
  737. $json = json_decode($json[1], true);
  738. if(isset($json["error"])){
  739. if(isset($json["error"]["errors"][0]["message"])){
  740. throw new Exception("Google returned an error: " . $json["error"]["errors"][0]["message"]);
  741. }
  742. if(isset($json["error"]["message"])){
  743. throw new Exception("Google returned an error: " . $json["error"]["message"]);
  744. }
  745. throw new Exception("Google returned an error object");
  746. }
  747. // detect next page
  748. if(
  749. isset($json["cursor"]["isExactTotalResults"]) || // detects last page
  750. !isset($json["cursor"]["pages"]) // detects no results on page
  751. ){
  752. return $out;
  753. }
  754. $out = [
  755. "status" => "ok",
  756. "npt" => null,
  757. "image" => []
  758. ];
  759. foreach($json["results"] as $result){
  760. $out["image"][] = [
  761. "title" => rtrim($result["titleNoFormatting"], " ."),
  762. "source" => [
  763. [
  764. "url" => $result["unescapedUrl"],
  765. "width" => (int)$result["width"],
  766. "height" => (int)$result["height"]
  767. ],
  768. [
  769. "url" => $result["tbLargeUrl"],
  770. "width" => (int)$result["tbLargeWidth"],
  771. "height" => (int)$result["tbLargeHeight"]
  772. ]
  773. ],
  774. "url" => $result["originalContextUrl"]
  775. ];
  776. }
  777. // get next page
  778. $out["npt"] =
  779. $this->backend->store(
  780. json_encode(
  781. $req_params
  782. ),
  783. "images",
  784. $proxy
  785. );
  786. return $out;
  787. }
  788. private function generate_token($proxy){
  789. $html =
  790. $this->get(
  791. $proxy,
  792. "https://cse.google.com/cse",
  793. [
  794. "cx" => config::GOOGLE_CX_ENDPOINT
  795. ],
  796. self::req_html
  797. );
  798. // detect captcha
  799. $this->fuckhtml->load($html);
  800. $title =
  801. $this->fuckhtml
  802. ->getElementsByTagName(
  803. "title"
  804. );
  805. if(
  806. count($title) !== 0 &&
  807. $title[0]["innerHTML"] == "302 Moved"
  808. ){
  809. throw new Exception("Google returned a captcha");
  810. }
  811. // get token
  812. preg_match(
  813. '/relativeUrl=\'([^\']+)\';/i',
  814. $html,
  815. $js_uri
  816. );
  817. if(!isset($js_uri[1])){
  818. throw new Exception("Failed to grep search token");
  819. }
  820. $js_uri =
  821. $this->fuckhtml
  822. ->parseJsString(
  823. $js_uri[1]
  824. );
  825. // get parameters
  826. $js =
  827. $this->get(
  828. $proxy,
  829. "https://cse.google.com" . $js_uri,
  830. [],
  831. self::req_js
  832. );
  833. preg_match(
  834. '/}\)\(({[\S\s]+})\);/',
  835. $js,
  836. $json
  837. );
  838. if(!isset($json[1])){
  839. throw new Exception("Failed to grep JSON parameters");
  840. }
  841. $json = json_decode($json[1], true);
  842. return [
  843. "token" => $json["cse_token"],
  844. "lib" => $json["cselibVersion"]
  845. ];
  846. }
  847. private function unshit_thumb($url){
  848. // https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQINE2vbnNLHXqoZr3RVsaEJFyOsj1_BiBnJch-e1nyz3oia7Aj5xVj
  849. // https://i.ytimg.com/vi/PZVIyA5ER3Y/mqdefault.jpg?sqp=-oaymwEFCJQBEFM&rs=AMzJL3nXeaCpdIar-ltNwl82Y82cIJfphA
  850. $parts = parse_url($url);
  851. if(
  852. isset($parts["host"]) &&
  853. preg_match(
  854. '/tbn.*\.gstatic\.com/',
  855. $parts["host"]
  856. )
  857. ){
  858. parse_str($parts["query"], $params);
  859. if(isset($params["q"])){
  860. return "https://" . $parts["host"] . "/images?q=" . $params["q"];
  861. }
  862. }
  863. return $url;
  864. }
  865. }