ddg.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384
  1. <?php
  2. class ddg{
  3. public function __construct(){
  4. include "lib/backend.php";
  5. $this->backend = new backend("ddg");
  6. include "lib/fuckhtml.php";
  7. $this->fuckhtml = new fuckhtml();
  8. }
  9. /*
  10. curl functions
  11. */
  12. private const req_web = 0;
  13. private const req_xhr = 1;
  14. private function get($proxy, $url, $get = [], $reqtype = self::req_web){
  15. $curlproc = curl_init();
  16. if($get !== []){
  17. $get = http_build_query($get);
  18. $url .= "?" . $get;
  19. }
  20. curl_setopt($curlproc, CURLOPT_URL, $url);
  21. // http2 bypass
  22. curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0);
  23. switch($reqtype){
  24. case self::req_web:
  25. $headers =
  26. [//"User-Agent: " . config::USER_AGENT,
  27. "User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
  28. "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
  29. "Accept-Language: en-US,en;q=0.5",
  30. "Accept-Encoding: gzip",
  31. "DNT: 1",
  32. "Sec-GPC: 1",
  33. "Connection: keep-alive",
  34. "Upgrade-Insecure-Requests: 1",
  35. "Sec-Fetch-Dest: document",
  36. "Sec-Fetch-Mode: navigate",
  37. "Sec-Fetch-Site: same-origin",
  38. "Sec-Fetch-User: ?1",
  39. "Priority: u=0, i",
  40. "TE: trailers"];
  41. break;
  42. case self::req_xhr:
  43. $headers =
  44. ["User-Agent: " . config::USER_AGENT,
  45. "Accept: */*",
  46. "Accept-Language: en-US,en;q=0.5",
  47. "Accept-Encoding: gzip",
  48. "Referer: https://duckduckgo.com/",
  49. "DNT: 1",
  50. "Sec-GPC: 1",
  51. "Connection: keep-alive",
  52. "Sec-Fetch-Dest: script",
  53. "Sec-Fetch-Mode: no-cors",
  54. "Sec-Fetch-Site: same-site",
  55. "Priority: u=1"];
  56. break;
  57. }
  58. $this->backend->assign_proxy($curlproc, $proxy);
  59. curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding
  60. curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers);
  61. curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true);
  62. curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2);
  63. curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true);
  64. curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30);
  65. curl_setopt($curlproc, CURLOPT_TIMEOUT, 30);
  66. $data = curl_exec($curlproc);
  67. if(curl_errno($curlproc)){
  68. throw new Exception(curl_error($curlproc));
  69. }
  70. curl_close($curlproc);
  71. return $data;
  72. }
  73. public function getfilters($pagetype){
  74. $base = [
  75. "country" => [
  76. "display" => "Country",
  77. "option" => [
  78. "us-en" => "US (English)",
  79. "ar-es" => "Argentina",
  80. "au-en" => "Australia",
  81. "at-de" => "Austria",
  82. "be-fr" => "Belgium (fr)",
  83. "be-nl" => "Belgium (nl)",
  84. "br-pt" => "Brazil",
  85. "bg-bg" => "Bulgaria",
  86. "ca-en" => "Canada (en)",
  87. "ca-fr" => "Canada (fr)",
  88. "ct-ca" => "Catalonia",
  89. "cl-es" => "Chile",
  90. "cn-zh" => "China",
  91. "co-es" => "Colombia",
  92. "hr-hr" => "Croatia",
  93. "cz-cs" => "Czech Republic",
  94. "dk-da" => "Denmark",
  95. "ee-et" => "Estonia",
  96. "fi-fi" => "Finland",
  97. "fr-fr" => "France",
  98. "de-de" => "Germany",
  99. "gr-el" => "Greece",
  100. "hk-tzh" => "Hong Kong",
  101. "hu-hu" => "Hungary",
  102. "in-en" => "India (en)",
  103. "id-en" => "Indonesia (en)",
  104. "ie-en" => "Ireland",
  105. "il-en" => "Israel (en)",
  106. "it-it" => "Italy",
  107. "jp-jp" => "Japan",
  108. "kr-kr" => "Korea",
  109. "lv-lv" => "Latvia",
  110. "lt-lt" => "Lithuania",
  111. "my-en" => "Malaysia (en)",
  112. "mx-es" => "Mexico",
  113. "nl-nl" => "Netherlands",
  114. "nz-en" => "New Zealand",
  115. "no-no" => "Norway",
  116. "pk-en" => "Pakistan (en)",
  117. "pe-es" => "Peru",
  118. "ph-en" => "Philippines (en)",
  119. "pl-pl" => "Poland",
  120. "pt-pt" => "Portugal",
  121. "ro-ro" => "Romania",
  122. "ru-ru" => "Russia",
  123. "xa-ar" => "Saudi Arabia",
  124. "sg-en" => "Singapore",
  125. "sk-sk" => "Slovakia",
  126. "sl-sl" => "Slovenia",
  127. "za-en" => "South Africa",
  128. "es-ca" => "Spain (ca)",
  129. "es-es" => "Spain (es)",
  130. "se-sv" => "Sweden",
  131. "ch-de" => "Switzerland (de)",
  132. "ch-fr" => "Switzerland (fr)",
  133. "tw-tzh" => "Taiwan",
  134. "th-en" => "Thailand (en)",
  135. "tr-tr" => "Turkey",
  136. "us-es" => "US (Spanish)",
  137. "ua-uk" => "Ukraine",
  138. "uk-en" => "United Kingdom",
  139. "vn-en" => "Vietnam (en)"
  140. ]
  141. ]
  142. ];
  143. switch($pagetype){
  144. case "web":
  145. $base["country"]["option"] =
  146. array_merge(["any" => "All Regions"], $base["country"]["option"]);
  147. return array_merge($base,
  148. [
  149. "nsfw" => [
  150. "display" => "NSFW",
  151. "option" => [
  152. "yes" => "Yes",
  153. "maybe" => "Maybe",
  154. "no" => "No"
  155. ]
  156. ],
  157. "newer" => [
  158. "display" => "Newer than",
  159. "option" => "_DATE"
  160. ],
  161. "older" => [
  162. "display" => "Older than",
  163. "option" => "_DATE"
  164. ],
  165. "extendedsearch" => [
  166. // undefined display
  167. "option" => [
  168. "yes" => "Yes",
  169. "no" => "No",
  170. ]
  171. ]
  172. ]
  173. );
  174. break;
  175. case "images":
  176. return array_merge($base,
  177. [
  178. "nsfw" => [
  179. "display" => "NSFW",
  180. "option" => [
  181. "yes" => "Yes",
  182. "no" => "No"
  183. ]
  184. ],
  185. "date" => [
  186. "display" => "Time posted",
  187. "option" => [
  188. "any" => "Any time",
  189. "Day" => "Past day",
  190. "Week" => "Past week",
  191. "Month" => "Past month"
  192. ]
  193. ],
  194. "size" => [
  195. "display" => "Size",
  196. "option" => [
  197. "any" => "Any size",
  198. "Small" => "Small",
  199. "Medium" => "Medium",
  200. "Large" => "Large",
  201. "Wallpaper" => "Wallpaper"
  202. ]
  203. ],
  204. "color" => [
  205. "display" => "Colors",
  206. "option" => [
  207. "any" => "All colors",
  208. "Monochrome" => "Black and white",
  209. "Red" => "Red",
  210. "Orange" => "Orange",
  211. "Yellow" => "Yellow",
  212. "Green" => "Green",
  213. "Blue" => "Blue",
  214. "Purple" => "Purple",
  215. "Pink" => "Pink",
  216. "Brown" => "Brown",
  217. "Black" => "Black",
  218. "Gray" => "Gray",
  219. "Teal" => "Teal",
  220. "White" => "White"
  221. ]
  222. ],
  223. "type" => [
  224. "display" => "Type",
  225. "option" => [
  226. "any" => "All types",
  227. "photo" => "Photograph",
  228. "clipart" => "Clipart",
  229. "gif" => "Animated GIF",
  230. "transparent" => "Transparent"
  231. ]
  232. ],
  233. "layout" => [
  234. "display" => "Layout",
  235. "option" => [
  236. "any" => "All layouts",
  237. "Square" => "Square",
  238. "Tall" => "Tall",
  239. "Wide" => "Wide"
  240. ]
  241. ],
  242. "license" => [
  243. "display" => "License",
  244. "option" => [
  245. "any" => "All licenses",
  246. "Any" => "All Creative Commons",
  247. "Public" => "Public domain",
  248. "Share" => "Free to Share and Use",
  249. "ShareCommercially" => "Free to Share and Use Commercially",
  250. "Modify" => "Free to Modify, Share, and Use",
  251. "ModifyCommercially" => "Free to Modify, Share, and Use Commercially"
  252. ]
  253. ]
  254. ]
  255. );
  256. break;
  257. case "videos":
  258. return array_merge($base,
  259. [
  260. "nsfw" => [
  261. "display" => "NSFW",
  262. "option" => [
  263. "yes" => "Yes",
  264. "maybe" => "Maybe",
  265. "no" => "No"
  266. ]
  267. ],
  268. "date" => [
  269. "display" => "Time fetched",
  270. "option" => [
  271. "any" => "Any time",
  272. "d" => "Past day",
  273. "w" => "Past week",
  274. "m" => "Past month"
  275. ]
  276. ],
  277. "resolution" => [ //videoDefinition
  278. "display" => "Resolution",
  279. "option" => [
  280. "any" => "Any resolution",
  281. "high" => "High definition",
  282. "standard" => "Standard definition"
  283. ]
  284. ],
  285. "duration" => [ // videoDuration
  286. "display" => "Duration",
  287. "option" => [
  288. "any" => "Any duration",
  289. "short" => "Short (>5min)",
  290. "medium" => "Medium (5-20min)",
  291. "long" => "Long (<20min)"
  292. ]
  293. ],
  294. "license" => [
  295. "display" => "License",
  296. "option" => [
  297. "any" => "Any license",
  298. "creativeCommon" => "Creative Commons",
  299. "youtube" => "YouTube Standard"
  300. ]
  301. ]
  302. ]
  303. );
  304. break;
  305. case "news":
  306. return array_merge($base,
  307. [
  308. "nsfw" => [
  309. "display" => "NSFW",
  310. "option" => [
  311. "yes" => "Yes",
  312. "maybe" => "Maybe",
  313. "no" => "No"
  314. ]
  315. ],
  316. "date" => [
  317. "display" => "Time posted",
  318. "option" => [
  319. "any" => "Any time",
  320. "d" => "Past day",
  321. "w" => "Past week",
  322. "m" => "Past month"
  323. ]
  324. ]
  325. ]
  326. );
  327. break;
  328. }
  329. }
  330. public function web($get){
  331. $out = [
  332. "status" => "ok",
  333. "spelling" => [
  334. "type" => "no_correction",
  335. "using" => null,
  336. "correction" => null
  337. ],
  338. "npt" => null,
  339. "answer" => [],
  340. "web" => [],
  341. "image" => [],
  342. "video" => [],
  343. "news" => [],
  344. "related" => []
  345. ];
  346. if($get["npt"]){
  347. [$js_link, $proxy] = $this->backend->get($get["npt"], "web");
  348. $js_link = "https://links.duckduckgo.com" . $js_link;
  349. $html = "";
  350. $get["extendedsearch"] = "no";
  351. }else{
  352. if(strlen($get["s"]) === 0){
  353. throw new Exception("Search term is empty!");
  354. }
  355. $proxy = $this->backend->get_ip();
  356. // generate filters
  357. $get_filters = [
  358. "q" => $get["s"]
  359. ];
  360. if($get["country"] == "any"){
  361. $get_filters["kl"] = "wt-wt";
  362. }else{
  363. $get_filters["kl"] = $get["country"];
  364. }
  365. switch($get["nsfw"]){
  366. case "yes": $get_filters["kp"] = "-2"; break;
  367. case "maybe": $get_filters["kp"] = "-1"; break;
  368. case "no": $get_filters["kp"] = "1"; break;
  369. }
  370. $df = true;
  371. if($get["newer"] === false){
  372. if($get["older"] !== false){
  373. $start = 36000;
  374. $end = $get["older"];
  375. }else{
  376. $df = false;
  377. }
  378. }else{
  379. $start = $get["newer"];
  380. if($get["older"] !== false){
  381. $end = $get["older"];
  382. }else{
  383. $end = time();
  384. }
  385. }
  386. if($df === true){
  387. $get_filters["df"] = date("Y-m-d", $start) . ".." . date("Y-m-d", $end);
  388. }
  389. //
  390. // Get HTML
  391. //
  392. try{
  393. $html = $this->get(
  394. $proxy,
  395. "https://duckduckgo.com/",
  396. $get_filters
  397. );
  398. }catch(Exception $e){
  399. throw new Exception("Failed to fetch search page");
  400. }
  401. $this->fuckhtml->load($html);
  402. $script =
  403. $this->fuckhtml
  404. ->getElementById(
  405. "deep_preload_link",
  406. "link"
  407. );
  408. if(
  409. $script === null ||
  410. !isset($script["attributes"]["href"])
  411. ){
  412. throw new Exception("Failed to grep d.js");
  413. }
  414. $js_link =
  415. $this->fuckhtml
  416. ->getTextContent(
  417. $script["attributes"]["href"]
  418. );
  419. }
  420. //
  421. // Get d.js
  422. //
  423. try{
  424. $js = $this->get(
  425. $proxy,
  426. $js_link,
  427. [],
  428. ddg::req_xhr
  429. );
  430. }catch(Exception $e){
  431. throw new Exception("Failed to fetch d.js");
  432. }
  433. //$js = file_get_contents("scraper/fuck.js");
  434. //echo htmlspecialchars($js);
  435. $js_tmp =
  436. preg_split(
  437. '/DDG\.pageLayout\.load\(\s*\'d\'\s*,\s*/',
  438. $js,
  439. 2
  440. );
  441. if(count($js_tmp) <= 1){
  442. //
  443. // Detect javascript challenge
  444. //
  445. if(
  446. preg_match(
  447. '/DDG\.deep\.initialize\(\'([^\']+)\'\ *\+ *jsa/i',
  448. $js,
  449. $challenge_url
  450. )
  451. ){
  452. throw new Exception("DuckDuckGo returned a JSA challenge");
  453. // get JSA initial token
  454. if(
  455. !preg_match(
  456. '/let jsa *= *([0-9]+)/',
  457. $js,
  458. $jsa
  459. )
  460. ){
  461. $jsa = 0;
  462. }else{
  463. $jsa = (int)$jsa[1];
  464. }
  465. // get function bodies
  466. preg_match_all(
  467. '/let *([A-Za-z0-9]+) *= *function\(.*\) *{(.*)};/sU',
  468. $js,
  469. $functions
  470. );
  471. $parsed_functions = [];
  472. for($i=0; $i<count($functions[0]); $i++){
  473. $functions[2][$i] = trim($functions[2][$i]);
  474. if(
  475. preg_match(
  476. '/return num *\* *([0-9]+)/i',
  477. $functions[2][$i],
  478. $num
  479. )
  480. ){
  481. $parsed_functions[$functions[1][$i]] = [
  482. "type" => "multiplication",
  483. "num" => (int)$num[1]
  484. ];
  485. continue;
  486. }
  487. if(
  488. preg_match(
  489. '/innerHTML *= *`([^`]+)`/i',
  490. $functions[2][$i],
  491. $challenge
  492. )
  493. ){
  494. $challenge[1] =
  495. preg_replace(
  496. '/<\/(br)>/',
  497. '<$1>',
  498. $challenge[1]
  499. );
  500. $parsed_functions[$functions[1][$i]] = [
  501. "type" => "challenge",
  502. "text" => $challenge[1]
  503. ];
  504. }
  505. }
  506. // get function call order
  507. preg_match_all(
  508. '/jsa *= *([A-Za-z0-9]+)\(jsa\)/i',
  509. $js,
  510. $call_order
  511. );
  512. foreach($call_order[1] as $order){
  513. if(!isset($parsed_functions[$order])){
  514. throw new Exception("JS challenge solve failure: DuckDuckGo called an unknown function");
  515. }
  516. if($parsed_functions[$order]["type"] == "multiplication"){
  517. $jsa = $jsa * $parsed_functions[$order]["num"];
  518. continue;
  519. }
  520. if($parsed_functions[$order]["type"] == "challenge"){
  521. // @TODO get parsed length
  522. //$parsed_functions[$order]["text"]
  523. $jsa = $jsa + strlen($parsed_functions[$order]["text"]);
  524. }
  525. }
  526. try{
  527. $js = $this->get(
  528. $proxy,
  529. "https://links.duckduckgo.com" . $challenge_url[1] . $jsa,
  530. [],
  531. ddg::req_xhr
  532. );
  533. }catch(Exception $error){
  534. throw new Exception("Failed to get challenged d.js");
  535. }
  536. }
  537. //
  538. // Detect JavaScript anomaly failure thingy
  539. //
  540. if(
  541. preg_match(
  542. '/DDG.deep.anomalyDetectionBlock\({/',
  543. $js
  544. )
  545. ){
  546. throw new Exception("DuckDuckGo detected an anomaly in the Javascript challenge response");
  547. }
  548. throw new Exception("Failed to grep pageLayout(d)");
  549. }
  550. $json =
  551. json_decode(
  552. $this->fuckhtml
  553. ->extract_json(
  554. $js_tmp[1]
  555. ),
  556. true
  557. );
  558. if($json === null){
  559. throw new Exception("Failed to decode JSON");
  560. }
  561. //
  562. // Get search results + NPT token
  563. //
  564. foreach($json as $item){
  565. if(isset($item["c"])){
  566. if(
  567. !isset($item["s"]) &&
  568. isset($item["t"]) &&
  569. (
  570. $item["t"] == "DEEP_ERROR_NO_RESULTS" ||
  571. $item["t"] == "DEEP_SIMPLE_NO_RESULTS"
  572. )
  573. ){
  574. return $out;
  575. }
  576. $table = [];
  577. // get youtube video information
  578. if(isset($item["video"]["thumbnail_url_template"])){
  579. $thumb =
  580. [
  581. "ratio" => "16:9",
  582. "url" => $this->bingimg($item["video"]["thumbnail_url_template"])
  583. ];
  584. }else{
  585. $thumb =
  586. [
  587. "ratio" => null,
  588. "url" => null
  589. ];
  590. }
  591. // get table items
  592. if(isset($item["rf"])){
  593. foreach($item["rf"] as $hint){
  594. if(
  595. !isset($hint["label"]["text"]) ||
  596. !isset($hint["items"][0]["text"])
  597. ){
  598. continue;
  599. }
  600. $text = [];
  601. foreach($hint["items"] as $text_part){
  602. $text[] = $text_part["text"];
  603. }
  604. $text = implode(", ", $text);
  605. if(is_numeric($text)){
  606. $text = number_format((string)$text);
  607. }
  608. $table[$hint["label"]["text"]] = $text;
  609. }
  610. }
  611. // get ratings
  612. if(isset($item["ar"])){
  613. foreach($item["ar"] as $rating){
  614. if(
  615. isset($rating["aggregateRating"]["bestRating"]) &&
  616. isset($rating["aggregateRating"]["ratingValue"])
  617. ){
  618. $text = $rating["aggregateRating"]["ratingValue"] . "/" . $rating["aggregateRating"]["bestRating"];
  619. if(isset($rating["aggregateRating"]["reviewCount"])){
  620. $text .= " (" . number_format($rating["aggregateRating"]["reviewCount"]) . " votes)";
  621. }
  622. $table["Rating"] = $text;
  623. }
  624. }
  625. }
  626. // get sublinks
  627. $sublinks = [];
  628. if(isset($item["l"])){
  629. foreach($item["l"] as $sublink){
  630. $sublinks[] = [
  631. "title" => $this->titledots($sublink["text"]),
  632. "description" => $this->titledots($sublink["snippet"]),
  633. "url" => $sublink["targetUrl"],
  634. "date" => null
  635. ];
  636. }
  637. }
  638. $title =
  639. $this->titledots(
  640. $this->fuckhtml
  641. ->getTextContent(
  642. $item["t"]
  643. )
  644. );
  645. if(
  646. $title == "EOF" &&
  647. strpos(
  648. $item["c"],
  649. "google"
  650. )
  651. ){
  652. continue;
  653. }
  654. // parse search result
  655. $out["web"][] = [
  656. "title" =>
  657. $this->titledots(
  658. $this->fuckhtml
  659. ->getTextContent(
  660. $item["t"]
  661. )
  662. ),
  663. "description" =>
  664. isset($item["a"]) ?
  665. $this->titledots(
  666. $this->fuckhtml
  667. ->getTextContent(
  668. $item["a"]
  669. )
  670. ) : null,
  671. "url" => $this->unshiturl($item["c"]),
  672. "date" =>
  673. isset($item["e"]) ?
  674. strtotime($item["e"]) : null,
  675. "type" => "web",
  676. "thumb" => $thumb,
  677. "sublink" => $sublinks,
  678. "table" => $table
  679. ];
  680. continue;
  681. }
  682. if(isset($item["n"])){
  683. // get NPT
  684. $out["npt"] =
  685. $this->backend->store(
  686. $item["n"],
  687. "web",
  688. $proxy
  689. );
  690. continue;
  691. }
  692. }
  693. //
  694. // Get spelling
  695. //
  696. $js_tmp =
  697. preg_split(
  698. '/DDG\.page\.showMessage\(\s*\'spelling\'\s*,\s*/',
  699. $js,
  700. 2
  701. );
  702. if(count($js_tmp) > 1){
  703. $json =
  704. json_decode(
  705. $this->fuckhtml
  706. ->extract_json(
  707. $js_tmp[1]
  708. ),
  709. true
  710. );
  711. if($json !== null){
  712. // parse spelling
  713. // qc=2: including
  714. switch((int)$json["qc"]){
  715. case 2:
  716. $type = "including";
  717. break;
  718. default:
  719. $type = "not_many";
  720. break;
  721. }
  722. $out["spelling"] = [
  723. "type" => $type,
  724. "using" =>
  725. $this->fuckhtml
  726. ->getTextContent(
  727. $json["suggestion"]
  728. ),
  729. "correction" => html_entity_decode($json["recourseText"])
  730. ];
  731. }
  732. }
  733. //
  734. // Get images
  735. //
  736. $js_tmp =
  737. preg_split(
  738. '/DDG\.duckbar\.load\(\s*\'images\'\s*,\s*/',
  739. $js,
  740. 2
  741. );
  742. if(count($js_tmp) > 1){
  743. $json =
  744. json_decode(
  745. $this->fuckhtml
  746. ->extract_json(
  747. $js_tmp[1]
  748. ),
  749. true
  750. );
  751. if($json !== null){
  752. foreach($json["results"] as $image){
  753. $ratio = $this->bingratio((int)$image["width"], (int)$image["height"]);
  754. $out["image"][] = [
  755. "title" => $image["title"],
  756. "source" => [
  757. [
  758. "url" => $image["image"],
  759. "width" => (int)$image["width"],
  760. "height" => (int)$image["height"]
  761. ],
  762. [
  763. "url" => $this->bingimg($image["thumbnail"]),
  764. "width" => $ratio[0],
  765. "height" => $ratio[1]
  766. ]
  767. ],
  768. "url" => $this->unshiturl($image["url"])
  769. ];
  770. }
  771. }
  772. }
  773. //
  774. // Get videos
  775. //
  776. $js_tmp =
  777. preg_split(
  778. '/DDG\.duckbar\.load\(\s*\'videos\'\s*,\s*/',
  779. $js,
  780. 2
  781. );
  782. if(count($js_tmp) > 1){
  783. $json =
  784. json_decode(
  785. $this->fuckhtml
  786. ->extract_json(
  787. $js_tmp[1]
  788. ),
  789. true
  790. );
  791. if($json !== null){
  792. foreach($json["results"] as $video){
  793. $thumb = [
  794. "ratio" => null,
  795. "url" => null
  796. ];
  797. foreach(["large", "medium", "small"] as $contender){
  798. if(isset($video["images"][$contender])){
  799. $thumb = [
  800. "ratio" => "16:9",
  801. "url" => $this->bingimg($video["images"][$contender])
  802. ];
  803. break;
  804. }
  805. }
  806. $out["video"][] = [
  807. "title" => $this->titledots($video["title"]),
  808. "description" =>
  809. $video["description"] != "" ?
  810. $this->titledots($video["description"]) : null,
  811. "date" =>
  812. isset($video["published"]) ?
  813. strtotime($video["published"]) : null,
  814. "duration" =>
  815. $video["duration"] != "" ?
  816. $this->hms2int($video["duration"]) : null,
  817. "views" =>
  818. isset($video["statistics"]["viewCount"]) ?
  819. (int)$video["statistics"]["viewCount"] : null,
  820. "thumb" => $thumb,
  821. "url" => $this->unshiturl($video["content"])
  822. ];
  823. }
  824. }
  825. }
  826. //
  827. // Get news
  828. //
  829. $js_tmp =
  830. preg_split(
  831. '/DDG\.duckbar\.load\(\s*\'news\'\s*,\s*/',
  832. $js,
  833. 2
  834. );
  835. if(count($js_tmp) > 1){
  836. $json =
  837. json_decode(
  838. $this->fuckhtml
  839. ->extract_json(
  840. $js_tmp[1]
  841. ),
  842. true
  843. );
  844. if($json !== null){
  845. foreach($json["results"] as $news){
  846. if(isset($news["image"])){
  847. $thumb = [
  848. "ratio" => "16:9",
  849. "url" => $news["image"]
  850. ];
  851. }else{
  852. $thumb = [
  853. "ratio" => null,
  854. "url" => null
  855. ];
  856. }
  857. $out["news"][] = [
  858. "title" => $news["title"],
  859. "description" =>
  860. $this->fuckhtml
  861. ->getTextContent(
  862. $news["excerpt"]
  863. ),
  864. "date" => (int)$news["date"],
  865. "thumb" => $thumb,
  866. "url" => $news["url"]
  867. ];
  868. }
  869. }
  870. }
  871. //
  872. // Get related searches
  873. //
  874. $js_tmp =
  875. preg_split(
  876. '/DDG\.duckbar\.loadModule\(\s*\'related_searches\'\s*,\s*/',
  877. $js,
  878. 2
  879. );
  880. if(count($js_tmp) > 1){
  881. $json =
  882. json_decode(
  883. $this->fuckhtml
  884. ->extract_json(
  885. $js_tmp[1]
  886. ),
  887. true
  888. );
  889. if($json !== null){
  890. foreach($json["results"] as $related){
  891. $out["related"][] = $related["text"];
  892. }
  893. }
  894. }
  895. //
  896. // Get instant answers
  897. //
  898. $js_tmp =
  899. preg_split(
  900. '/DDG\.duckbar\.add\(\s*/',
  901. $html . $js,
  902. 2
  903. );
  904. if(count($js_tmp) > 1){
  905. $json =
  906. json_decode(
  907. $this->fuckhtml
  908. ->extract_json(
  909. $js_tmp[1]
  910. ),
  911. true
  912. );
  913. if($json !== null){
  914. $json = $json["data"];
  915. $table = [];
  916. $sublinks = [];
  917. $description = [];
  918. // get official website
  919. if(
  920. isset($json["OfficialWebsite"]) &&
  921. $json["OfficialWebsite"] !== null
  922. ){
  923. $sublinks["Website"] = $json["OfficialWebsite"];
  924. }
  925. // get sublinks & table elements
  926. if(isset($json["Infobox"]["content"])){
  927. foreach($json["Infobox"]["content"] as $info){
  928. if($info["data_type"] == "string"){
  929. // add table element
  930. $table[$info["label"]] = $info["value"];
  931. continue;
  932. }
  933. if($info["data_type"] == "wd_description"){
  934. $description[] = [
  935. "type" => "quote",
  936. "value" => $info["value"]
  937. ];
  938. continue;
  939. }
  940. // add sublink
  941. switch($info["data_type"]){
  942. case "official_site":
  943. case "official_website":
  944. $type = "Website";
  945. break;
  946. case "wikipedia": $type = "Wikipedia"; break;
  947. case "itunes": $type = "iTunes"; break;
  948. case "amazon": $type = "Amazon"; break;
  949. case "imdb_title_id":
  950. case "imdb_id":
  951. case "imdb_name_id":
  952. $type = "IMDb";
  953. $delim = substr($info["value"], 0, 2);
  954. if($delim == "nm"){
  955. $prefix = "https://www.imdb.com/name/";
  956. }elseif($delim == "tt"){
  957. $prefix = "https://www.imdb.com/title/";
  958. }elseif($delim == "co"){
  959. $prefix = "https://www.imdb.com/search/title/?companies=";
  960. }else{
  961. $prefix = "https://www.imdb.com/title/";
  962. }
  963. break;
  964. case "imdb_name_id": $prefix = "https://www.imdb.com/name/"; $type = "IMDb"; break;
  965. case "twitter_profile": $prefix = "https://twitter.com/"; $type = "Twitter"; break;
  966. case "instagram_profile": $prefix = "https://instagram.com/"; $type = "Instagram"; break;
  967. case "facebook_profile": $prefix = "https://facebook.com/"; $type = "Facebook"; break;
  968. case "spotify_artist_id": $prefix = "https://open.spotify.com/artist/"; $type = "Spotify"; break;
  969. case "itunes_artist_id": $prefix = "https://music.apple.com/us/artist/"; $type = "iTunes"; break;
  970. case "rotten_tomatoes": $prefix = "https://rottentomatoes.com/"; $type = "Rotten Tomatoes"; break;
  971. case "youtube_channel": $prefix = "https://youtube.com/channel/"; $type = "YouTube"; break;
  972. case "soundcloud_id": $prefix = "https://soundcloud.com/"; $type = "SoundCloud"; break;
  973. default:
  974. $prefix = null;
  975. $type = false;
  976. }
  977. if($type !== false){
  978. if($prefix === null){
  979. $sublinks[$type] = $info["value"];
  980. }else{
  981. $sublinks[$type] = $prefix . $info["value"];
  982. }
  983. }
  984. }
  985. }
  986. if(isset($json["Abstract"])){
  987. $description = $this->parse_rich_text($json["Abstract"]);
  988. }
  989. if(
  990. !isset($json["Image"]) ||
  991. $json["Image"] == "" ||
  992. $json["Image"] === null ||
  993. $json["Image"] == "https://duckduckgo.com/i/"
  994. ){
  995. $image = null;
  996. }else{
  997. if(
  998. preg_match(
  999. '/^https?:\/\//',
  1000. $json["Image"]
  1001. )
  1002. ){
  1003. $image = $json["Image"];
  1004. }else{
  1005. $image = "https://duckduckgo.com" . $json["Image"];
  1006. }
  1007. }
  1008. $out["answer"][] = [
  1009. "title" => $json["Heading"],
  1010. "description" => $description,
  1011. "url" => $json["AbstractURL"],
  1012. "thumb" => $image,
  1013. "table" => $table,
  1014. "sublink" => $sublinks
  1015. ];
  1016. }
  1017. }
  1018. if($get["extendedsearch"] == "no"){
  1019. return $out;
  1020. }
  1021. //
  1022. // Parse additional data endpoints
  1023. //
  1024. //nrj('/js/spice/dictionary/definition/create', null, null, null, null, 'dictionary_definition');
  1025. preg_match_all(
  1026. '/nrj\(\s*\'([^\']+)\'/',
  1027. $js,
  1028. $nrj
  1029. );
  1030. if(isset($nrj[1])){
  1031. foreach($nrj[1] as $potential_endpoint){
  1032. //
  1033. // Probe for wordnik definition
  1034. //
  1035. preg_match(
  1036. '/\/js\/spice\/dictionary\/definition\/([^\/]+)/',
  1037. $potential_endpoint,
  1038. $word
  1039. );
  1040. if(isset($word[1])){
  1041. $word = $word[1];
  1042. // found wordnik definition & word
  1043. try{
  1044. $nik =
  1045. $this->get(
  1046. $proxy,
  1047. "https://duckduckgo.com/js/spice/dictionary/definition/" . $word,
  1048. [],
  1049. ddg::req_xhr
  1050. );
  1051. }catch(Exception $e){
  1052. // fail gracefully
  1053. return $out;
  1054. }
  1055. // remove javascript
  1056. $js_tmp =
  1057. preg_split(
  1058. '/ddg_spice_dictionary_definition\(\s*/',
  1059. $nik,
  1060. 2
  1061. );
  1062. if(count($js_tmp) > 1){
  1063. $nik =
  1064. json_decode(
  1065. $this->fuckhtml
  1066. ->extract_json(
  1067. $js_tmp[1]
  1068. ),
  1069. true
  1070. );
  1071. }
  1072. if($nik === null){
  1073. return $out;
  1074. }
  1075. $answer_cat = [];
  1076. $answer = [];
  1077. foreach($nik as $snippet){
  1078. if(!isset($snippet["partOfSpeech"])){ continue; }
  1079. $push = [];
  1080. // add text snippet
  1081. if(isset($snippet["text"])){
  1082. $push[] = [
  1083. "type" => "text",
  1084. "value" =>
  1085. $this->fuckhtml
  1086. ->getTextContent(
  1087. $snippet["text"]
  1088. )
  1089. ];
  1090. }
  1091. // add example uses
  1092. if(isset($snippet["exampleUses"])){
  1093. foreach($snippet["exampleUses"] as $example){
  1094. $push[] = [
  1095. "type" => "quote",
  1096. "value" => "\"" .
  1097. $this->fuckhtml
  1098. ->getTextContent(
  1099. $example["text"]
  1100. ) . "\""
  1101. ];
  1102. }
  1103. }
  1104. // add citations
  1105. if(isset($snippet["citations"])){
  1106. foreach($snippet["citations"] as $citation){
  1107. if(!isset($citation["cite"])){ continue; }
  1108. $text =
  1109. $this->fuckhtml
  1110. ->getTextContent(
  1111. $citation["cite"]
  1112. );
  1113. if(isset($citation["source"])){
  1114. $text .=
  1115. " - " .
  1116. $this->fuckhtml
  1117. ->getTextContent(
  1118. $citation["source"]
  1119. );
  1120. }
  1121. $push[] = [
  1122. "type" => "quote",
  1123. "value" => $text
  1124. ];
  1125. }
  1126. }
  1127. // add related words
  1128. if(isset($snippet["relatedWords"])){
  1129. $relations = [];
  1130. foreach($snippet["relatedWords"] as $related){
  1131. $words = [];
  1132. foreach($related["words"] as $wrd){
  1133. $words[] =
  1134. $this->fuckhtml
  1135. ->getTextContent(
  1136. $wrd
  1137. );
  1138. }
  1139. if(
  1140. count($words) !== 0 &&
  1141. isset($related["relationshipType"])
  1142. ){
  1143. $relations[ucfirst($related["relationshipType"]) . "s"] =
  1144. implode(", ", $words);
  1145. }
  1146. }
  1147. foreach($relations as $relation_title => $relation_content){
  1148. $push[] = [
  1149. "type" => "quote",
  1150. "value" => $relation_title . ": " . $relation_content
  1151. ];
  1152. }
  1153. }
  1154. if(count($push) !== 0){
  1155. // push data to answer_cat
  1156. if(!isset($answer_cat[$snippet["partOfSpeech"]])){
  1157. $answer_cat[$snippet["partOfSpeech"]] = [];
  1158. }
  1159. $answer_cat[$snippet["partOfSpeech"]] =
  1160. array_merge(
  1161. $answer_cat[$snippet["partOfSpeech"]],
  1162. $push
  1163. );
  1164. }
  1165. }
  1166. foreach($answer_cat as $answer_title => $answer_content){
  1167. $i = 0;
  1168. $answer[] = [
  1169. "type" => "title",
  1170. "value" => $answer_title
  1171. ];
  1172. $old_type = $answer[count($answer) - 1]["type"];
  1173. foreach($answer_content as $ans){
  1174. if(
  1175. $ans["type"] == "text" &&
  1176. $old_type == "text"
  1177. ){
  1178. $i++;
  1179. $c = count($answer) - 1;
  1180. // append text to existing textfield
  1181. $answer[$c] = [
  1182. "type" => "text",
  1183. "value" => $answer[$c]["value"] . "\n" . $i . ". " . $ans["value"]
  1184. ];
  1185. }elseif($ans["type"] == "text"){
  1186. $i++;
  1187. $answer[] = [
  1188. "type" => "text",
  1189. "value" => $i . ". " . $ans["value"]
  1190. ];
  1191. }else{
  1192. // append normally
  1193. $answer[] = $ans;
  1194. }
  1195. $old_type = $ans["type"];
  1196. }
  1197. }
  1198. // yeah.. sometimes duckduckgo doesnt give us a definition back
  1199. if(count($answer) !== 0){
  1200. $out["answer"][] = [
  1201. "title" => ucfirst($word),
  1202. "description" => $answer,
  1203. "url" => "https://www.wordnik.com/words/" . $word,
  1204. "thumb" => null,
  1205. "table" => [],
  1206. "sublink" => []
  1207. ];
  1208. }
  1209. }
  1210. //
  1211. // Parse stackoverflow answer
  1212. //
  1213. if(
  1214. preg_match(
  1215. '/^\/a\.js.*src_id=stack_overflow/',
  1216. $potential_endpoint
  1217. )
  1218. ){
  1219. // found stackoverflow answer
  1220. try{
  1221. $json =
  1222. $this->get(
  1223. $proxy,
  1224. "https://duckduckgo.com" . $potential_endpoint,
  1225. [],
  1226. ddg::req_xhr
  1227. );
  1228. }catch(Exception $e){
  1229. // fail gracefully
  1230. return $out;
  1231. }
  1232. $json = explode("DDG.duckbar.add_array(", $json, 2);
  1233. if(count($json) === 2){
  1234. $json =
  1235. json_decode(
  1236. $this->fuckhtml
  1237. ->extract_json(
  1238. $json[1]
  1239. ),
  1240. true
  1241. );
  1242. if(
  1243. $json !== null &&
  1244. isset($json[0]["data"])
  1245. ){
  1246. $json = $json[0]["data"];
  1247. foreach($json as $answer){
  1248. if(isset($answer["Heading"])){
  1249. $title = $answer["Heading"];
  1250. }elseif(isset($answer["title"])){
  1251. $title = $answer["title"];
  1252. }else{
  1253. $title = null;
  1254. }
  1255. if(
  1256. $title !== null &&
  1257. isset($answer["Abstract"])
  1258. ){
  1259. $description = $this->parse_rich_text($answer["Abstract"]);
  1260. $out["answer"][] = [
  1261. "title" => $title,
  1262. "description" => $description,
  1263. "url" => $answer["AbstractURL"],
  1264. "thumb" => null,
  1265. "table" => [],
  1266. "sublink" => []
  1267. ];
  1268. }
  1269. }
  1270. }
  1271. }
  1272. }
  1273. }
  1274. }
  1275. return $out;
  1276. }
  1277. public function image($get){
  1278. if($get["npt"]){
  1279. [$js_link, $proxy] = $this->backend->get($get["npt"], "images");
  1280. }else{
  1281. if(strlen($get["s"]) === 0){
  1282. throw new Exception("Search term is empty!");
  1283. }
  1284. $proxy = $this->backend->get_ip();
  1285. $filters = [];
  1286. if($get["date"] != "any"){ $filters[] = "time:{$get["date"]}"; }
  1287. if($get["size"] != "any"){ $filters[] = "size:{$get["size"]}"; }
  1288. if($get["color"] != "any"){ $filters[] = "color:{$get["color"]}"; }
  1289. if($get["type"] != "any"){ $filters[] = "type:{$get["type"]}"; }
  1290. if($get["layout"] != "any"){ $filters[] = "layout:{$get["layout"]}"; }
  1291. if($get["license"] != "any"){ $filters[] = "license:{$get["license"]}"; }
  1292. $filters = implode(",", $filters);
  1293. $get_filters = [
  1294. "q" => $get["s"],
  1295. "iax" => "images",
  1296. "ia" => "images"
  1297. ];
  1298. if($filters != ""){
  1299. $get_filters["iaf"] = $filters;
  1300. }
  1301. $nsfw = $get["nsfw"] == "yes" ? "-1" : "1";
  1302. $get_filters["kp"] = $nsfw;
  1303. try{
  1304. $html = $this->get(
  1305. $proxy,
  1306. "https://duckduckgo.com",
  1307. $get_filters,
  1308. ddg::req_web
  1309. );
  1310. }catch(Exception $err){
  1311. throw new Exception("Failed to fetch search page");
  1312. }
  1313. preg_match(
  1314. '/vqd="([0-9-]+)"/',
  1315. $html,
  1316. $vqd
  1317. );
  1318. if(!isset($vqd[1])){
  1319. throw new Exception("Failed to grep VQD token");
  1320. }
  1321. $js_link =
  1322. "i.js?" .
  1323. http_build_query([
  1324. "l" => $get["country"],
  1325. "o" => "json",
  1326. "q" => $get["s"],
  1327. "vqd" => $vqd[1],
  1328. "f" => $filters,
  1329. "p" => $nsfw
  1330. ]);
  1331. }
  1332. try{
  1333. $json =
  1334. $this->get(
  1335. $proxy,
  1336. "https://duckduckgo.com/" . $js_link,
  1337. [],
  1338. ddg::req_xhr
  1339. );
  1340. }catch(Exception $error){
  1341. throw new Exception("Failed to get i.js");
  1342. }
  1343. $json = json_decode($json, true);
  1344. if($json === null){
  1345. throw new Exception("Failed to decode JSON");
  1346. }
  1347. $out = [
  1348. "status" => "ok",
  1349. "npt" => null,
  1350. "image" => []
  1351. ];
  1352. if(!isset($json["results"])){
  1353. return $out;
  1354. }
  1355. // get npt
  1356. if(
  1357. isset($json["next"]) &&
  1358. $json["next"] !== null
  1359. ){
  1360. $vqd = null;
  1361. if(isset($vqd[1])){
  1362. $vqd = $vqd[1];
  1363. }else{
  1364. $vqd = array_values($json["vqd"]);
  1365. if(count($vqd) > 0){
  1366. $vqd = $vqd[0];
  1367. }
  1368. }
  1369. if($vqd !== null){
  1370. $out["npt"] =
  1371. $this->backend->store(
  1372. $json["next"] . "&vqd=" . $vqd,
  1373. "images",
  1374. $proxy
  1375. );
  1376. }
  1377. }
  1378. // get images
  1379. foreach($json["results"] as $image){
  1380. $ratio =
  1381. $this->bingratio(
  1382. (int)$image["width"],
  1383. (int)$image["height"]
  1384. );
  1385. $out["image"][] = [
  1386. "title" => $this->titledots($image["title"]),
  1387. "source" => [
  1388. [
  1389. "url" => $image["image"],
  1390. "width" => (int)$image["width"],
  1391. "height" => (int)$image["height"]
  1392. ],
  1393. [
  1394. "url" => $this->bingimg($image["thumbnail"]),
  1395. "width" => $ratio[0],
  1396. "height" => $ratio[1]
  1397. ]
  1398. ],
  1399. "url" => $this->unshiturl($image["url"])
  1400. ];
  1401. }
  1402. return $out;
  1403. }
  1404. public function video($get){
  1405. if($get["npt"]){
  1406. [$js_link, $proxy] = $this->backend->get($get["npt"], "videos");
  1407. }else{
  1408. if(strlen($get["s"]) === 0){
  1409. throw new Exception("Search term is empty!");
  1410. }
  1411. $proxy = $this->backend->get_ip();
  1412. $get_filters = [
  1413. "q" => $get["s"],
  1414. "iax" => "videos",
  1415. "ia" => "videos"
  1416. ];
  1417. switch($get["nsfw"]){
  1418. case "yes": $nsfw = "-2"; break;
  1419. case "maybe": $nsfw = "-1"; break;
  1420. case "no": $nsfw = "1"; break;
  1421. }
  1422. $filters = [];
  1423. if($get["date"] != "any"){ $filters[] = "publishedAfter:{$date}"; }
  1424. if($get["resolution"] != "any"){ $filters[] = "videoDefinition:{$resolution}"; }
  1425. if($get["duration"] != "any"){ $filters[] = "videoDuration:{$duration}"; }
  1426. if($get["license"] != "any"){ $filters[] = "videoLicense:{$license}"; }
  1427. $filters = implode(",", $filters);
  1428. if($filters != ""){
  1429. $get_filters["iaf"] = $filters;
  1430. }
  1431. try{
  1432. $html =
  1433. $this->get(
  1434. $proxy,
  1435. "https://duckduckgo.com/",
  1436. $get_filters,
  1437. ddg::req_web
  1438. );
  1439. }catch(Exception $error){
  1440. throw new Exception("Failed to fetch search page");
  1441. }
  1442. preg_match(
  1443. '/vqd="([0-9-]+)"/',
  1444. $html,
  1445. $vqd
  1446. );
  1447. if(!isset($vqd[1])){
  1448. throw new Exception("Failed to grep VQD token");
  1449. }
  1450. $js_link =
  1451. "v.js?" .
  1452. http_build_query([
  1453. "l" => $get["country"],
  1454. "o" => "json",
  1455. "sr" => "1",
  1456. "q" => $get["s"],
  1457. "vqd" => $vqd[1],
  1458. "f" => $filters,
  1459. "p" => $nsfw
  1460. ]);
  1461. }
  1462. try{
  1463. $json =
  1464. $this->get(
  1465. $proxy,
  1466. "https://duckduckgo.com/" . $js_link,
  1467. [],
  1468. ddg::req_xhr
  1469. );
  1470. }catch(Exception $error){
  1471. throw new Exception("Failed to fetch JSON");
  1472. }
  1473. $json = json_decode($json, true);
  1474. if($json === null){
  1475. throw new Exception("Failed to decode JSON");
  1476. }
  1477. $out = [
  1478. "status" => "ok",
  1479. "npt" => null,
  1480. "video" => [],
  1481. "author" => [],
  1482. "livestream" => [],
  1483. "playlist" => [],
  1484. "reel" => []
  1485. ];
  1486. if(!isset($json["results"])){
  1487. return $out;
  1488. }
  1489. // get NPT
  1490. if(
  1491. isset($json["next"]) &&
  1492. $json["next"] !== null
  1493. ){
  1494. $out["npt"] =
  1495. $this->backend->store(
  1496. $json["next"],
  1497. "videos",
  1498. $proxy
  1499. );
  1500. }
  1501. foreach($json["results"] as $video){
  1502. $thumb = [
  1503. "ratio" => null,
  1504. "url" => null
  1505. ];
  1506. foreach(["large", "medium", "small"] as $contender){
  1507. if(isset($video["images"][$contender])){
  1508. $thumb = [
  1509. "ratio" => "16:9",
  1510. "url" => $this->bingimg($video["images"][$contender])
  1511. ];
  1512. break;
  1513. }
  1514. }
  1515. $out["video"][] = [
  1516. "title" => $this->titledots($video["title"]),
  1517. "description" => $this->titledots($video["description"]),
  1518. "author" => [
  1519. "name" =>
  1520. (
  1521. isset($video["uploader"]) &&
  1522. $video["uploader"] != ""
  1523. ) ?
  1524. $video["uploader"] : null,
  1525. "url" => null,
  1526. "avatar" => null
  1527. ],
  1528. "date" =>
  1529. (
  1530. isset($video["published"]) &&
  1531. $video["published"] != ""
  1532. ) ?
  1533. strtotime($video["published"]) : null,
  1534. "duration" =>
  1535. (
  1536. isset($video["duration"]) &&
  1537. $video["duration"] != ""
  1538. ) ?
  1539. $this->hms2int($video["duration"]) : null,
  1540. "views" =>
  1541. isset($video["statistics"]["viewCount"]) ?
  1542. (int)$video["statistics"]["viewCount"] : null,
  1543. "thumb" => $thumb,
  1544. "url" => $this->unshiturl($video["content"])
  1545. ];
  1546. }
  1547. return $out;
  1548. }
  1549. public function news($get){
  1550. if($get["npt"]){
  1551. [$js_link, $proxy] = $this->backend->get($get["npt"], "news");
  1552. }else{
  1553. if(strlen($get["s"]) === 0){
  1554. throw new Exception("Search term is empty!");
  1555. }
  1556. $proxy = $this->backend->get_ip();
  1557. $get_filters = [
  1558. "q" => $get["s"],
  1559. "iar" => "news",
  1560. "ia" => "news"
  1561. ];
  1562. if($get["date"] != "any"){
  1563. $date = $get["date"];
  1564. $get_filters["df"] = $date;
  1565. }else{
  1566. $date = "";
  1567. }
  1568. switch($get["nsfw"]){
  1569. case "yes": $get_filters["kp"] = "-2"; break;
  1570. case "maybe": $get_filters["kp"] = "-1"; break;
  1571. case "no": $get_filters["kp"] = "1"; break;
  1572. }
  1573. try{
  1574. $html =
  1575. $this->get(
  1576. $proxy,
  1577. "https://duckduckgo.com/",
  1578. $get_filters,
  1579. ddg::req_web
  1580. );
  1581. }catch(Exception $error){
  1582. throw new Exception("Failed to fetch search page");
  1583. }
  1584. preg_match(
  1585. '/vqd="([0-9-]+)"/',
  1586. $html,
  1587. $vqd
  1588. );
  1589. if(!isset($vqd[1])){
  1590. throw new Exception("Failed to grep VQD token");
  1591. }
  1592. $js_link =
  1593. "news.js?" .
  1594. http_build_query([
  1595. "l" => $get["country"],
  1596. "o" => "json",
  1597. "noamp" => "1",
  1598. "m" => "30",
  1599. "q" => $get["s"],
  1600. "vqd" => $vqd[1],
  1601. "p" => $get_filters["kp"],
  1602. "df" => $date,
  1603. "u" => "bing"
  1604. ]);
  1605. }
  1606. try{
  1607. $json =
  1608. $this->get(
  1609. $proxy,
  1610. "https://duckduckgo.com/" . $js_link,
  1611. [],
  1612. ddg::req_xhr
  1613. );
  1614. }catch(Exception $error){
  1615. throw new Exception("Failed to fetch JSON");
  1616. }
  1617. $json = json_decode($json, true);
  1618. if($json === null){
  1619. throw new Exception("Failed to decode JSON");
  1620. }
  1621. $out = [
  1622. "status" => "ok",
  1623. "npt" => null,
  1624. "news" => []
  1625. ];
  1626. if(!isset($json["results"])){
  1627. return $out;
  1628. }
  1629. // get NPT
  1630. if(
  1631. isset($json["next"]) &&
  1632. $json["next"] !== null
  1633. ){
  1634. $out["npt"] =
  1635. $this->backend->store(
  1636. $json["next"],
  1637. "news",
  1638. $proxy
  1639. );
  1640. }
  1641. foreach($json["results"] as $news){
  1642. if(
  1643. isset($news["image"]) &&
  1644. $news["image"] != ""
  1645. ){
  1646. $thumb = [
  1647. "ratio" => "16:9",
  1648. "url" => $news["image"]
  1649. ];
  1650. }else{
  1651. $thumb = [
  1652. "ratio" => null,
  1653. "url" => null
  1654. ];
  1655. }
  1656. $out["news"][] = [
  1657. "title" => $news["title"],
  1658. "author" =>
  1659. (
  1660. isset($news["source"]) &&
  1661. $news["source"] != ""
  1662. ) ?
  1663. $news["source"] : null,
  1664. "description" =>
  1665. (
  1666. isset($news["excerpt"]) &&
  1667. $news["excerpt"] != ""
  1668. ) ?
  1669. $this->fuckhtml
  1670. ->getTextContent(
  1671. $news["excerpt"]
  1672. ) : null,
  1673. "date" =>
  1674. isset($news["date"]) ?
  1675. (int)$news["date"] : null,
  1676. "thumb" => $thumb,
  1677. "url" => $this->unshiturl($news["url"])
  1678. ];
  1679. }
  1680. return $out;
  1681. }
  1682. private function parse_rich_text($html){
  1683. $description = [];
  1684. // pre-process the html, remove useless elements
  1685. $html =
  1686. strip_tags(
  1687. $html,
  1688. [
  1689. "h1", "h2", "h3", "h4", "h5", "h6", "h7",
  1690. "pre", "code"
  1691. ]
  1692. );
  1693. $html =
  1694. preg_replace(
  1695. '/<(\/?)pre *[^>]*>\s*<\/?code *[^>]*>/i',
  1696. '<$1pre>',
  1697. $html
  1698. );
  1699. $this->fuckhtml->load($html);
  1700. $tags =
  1701. $this->fuckhtml
  1702. ->getElementsByTagName(
  1703. "*"
  1704. );
  1705. if(count($tags) === 0){
  1706. $description[] = [
  1707. "type" => "text",
  1708. "value" =>
  1709. trim(
  1710. $this->fuckhtml
  1711. ->getTextContent(
  1712. $html,
  1713. true,
  1714. false
  1715. )
  1716. )
  1717. ];
  1718. }else{
  1719. $start = 0;
  1720. $was_code_block = true;
  1721. foreach($tags as $tag){
  1722. $text =
  1723. $this->fuckhtml
  1724. ->getTextContent(
  1725. substr(
  1726. $html,
  1727. $start,
  1728. $tag["startPos"] - $start
  1729. ),
  1730. true,
  1731. false
  1732. );
  1733. if($was_code_block){
  1734. $text = ltrim($text);
  1735. $was_code_block = false;
  1736. }
  1737. $description[] = [
  1738. "type" => "text",
  1739. "value" => $text
  1740. ];
  1741. switch($tag["tagName"]){
  1742. case "pre":
  1743. $append = "code";
  1744. $was_code_block = true;
  1745. $c = count($description) - 1;
  1746. $description[$c]["value"] =
  1747. rtrim($description[$c]["value"]);
  1748. break;
  1749. case "code":
  1750. $append = "inline_code";
  1751. $c = count($description) - 1;
  1752. $description[$c]["value"] =
  1753. rtrim($description[$c]["value"]) . " ";
  1754. break;
  1755. case "h1":
  1756. case "h2":
  1757. case "h3":
  1758. case "h4":
  1759. case "h5":
  1760. case "h6":
  1761. case "h7":
  1762. $append = "title";
  1763. $c = count($description) - 1;
  1764. $description[$c]["value"] =
  1765. rtrim($description[$c]["value"]);
  1766. break;
  1767. }
  1768. $description[] = [
  1769. "type" => $append,
  1770. "value" =>
  1771. trim(
  1772. $this->fuckhtml
  1773. ->getTextContent(
  1774. $tag,
  1775. true,
  1776. false
  1777. )
  1778. )
  1779. ];
  1780. $start = $tag["endPos"];
  1781. }
  1782. // shit out remainder
  1783. $description[] = [
  1784. "type" => "text",
  1785. "value" =>
  1786. trim(
  1787. $this->fuckhtml
  1788. ->getTextContent(
  1789. substr(
  1790. $html,
  1791. $start
  1792. ),
  1793. true,
  1794. false
  1795. )
  1796. )
  1797. ];
  1798. }
  1799. return $description;
  1800. }
  1801. private function titledots($title){
  1802. $substr = substr($title, -3);
  1803. if(
  1804. $substr == "..." ||
  1805. $substr == "…"
  1806. ){
  1807. return trim(substr($title, 0, -3));
  1808. }
  1809. return trim($title);
  1810. }
  1811. private function hms2int($time){
  1812. $parts = explode(":", $time, 3);
  1813. $time = 0;
  1814. if(count($parts) === 3){
  1815. // hours
  1816. $time = $time + ((int)$parts[0] * 3600);
  1817. array_shift($parts);
  1818. }
  1819. if(count($parts) === 2){
  1820. // minutes
  1821. $time = $time + ((int)$parts[0] * 60);
  1822. array_shift($parts);
  1823. }
  1824. // seconds
  1825. $time = $time + (int)$parts[0];
  1826. return $time;
  1827. }
  1828. private function unshiturl($url){
  1829. // check for domains w/out first short subdomain (ex: www.)
  1830. $domain = parse_url($url, PHP_URL_HOST);
  1831. $subdomain = preg_replace(
  1832. '/^[A-z0-9]{1,3}\./',
  1833. "",
  1834. $domain
  1835. );
  1836. switch($subdomain){
  1837. case "ebay.com.au":
  1838. case "ebay.at":
  1839. case "ebay.ca":
  1840. case "ebay.fr":
  1841. case "ebay.de":
  1842. case "ebay.com.hk":
  1843. case "ebay.ie":
  1844. case "ebay.it":
  1845. case "ebay.com.my":
  1846. case "ebay.nl":
  1847. case "ebay.ph":
  1848. case "ebay.pl":
  1849. case "ebay.com.sg":
  1850. case "ebay.es":
  1851. case "ebay.ch":
  1852. case "ebay.co.uk":
  1853. case "cafr.ebay.ca":
  1854. case "ebay.com":
  1855. case "community.ebay.com":
  1856. case "pages.ebay.com":
  1857. // remove ebay tracking elements
  1858. $old_params = parse_url($url, PHP_URL_QUERY);
  1859. parse_str($old_params, $params);
  1860. if(isset($params["mkevt"])){ unset($params["mkevt"]); }
  1861. if(isset($params["mkcid"])){ unset($params["mkcid"]); }
  1862. if(isset($params["mkrid"])){ unset($params["mkrid"]); }
  1863. if(isset($params["campid"])){ unset($params["campid"]); }
  1864. if(isset($params["customid"])){ unset($params["customid"]); }
  1865. if(isset($params["toolid"])){ unset($params["toolid"]); }
  1866. if(isset($params["_sop"])){ unset($params["_sop"]); }
  1867. if(isset($params["_dcat"])){ unset($params["_dcat"]); }
  1868. if(isset($params["epid"])){ unset($params["epid"]); }
  1869. if(isset($params["epid"])){ unset($params["oid"]); }
  1870. $params = http_build_query($params);
  1871. if(strlen($params) === 0){
  1872. $replace = "\?";
  1873. }else{
  1874. $replace = "";
  1875. }
  1876. $url = preg_replace(
  1877. "/" . $replace . preg_quote($old_params, "/") . "$/",
  1878. $params,
  1879. $url
  1880. );
  1881. break;
  1882. }
  1883. return $url;
  1884. }
  1885. private function bingimg($url){
  1886. $image = parse_url($url);
  1887. $id = null;
  1888. if(isset($image["query"])){
  1889. parse_str($image["query"], $str);
  1890. if(isset($str["id"])){
  1891. $id = $str["id"];
  1892. }
  1893. }
  1894. if($id === null){
  1895. $id = explode("/th/id/", $image["path"], 2);
  1896. if(count($id) !== 2){
  1897. // malformed
  1898. return $url;
  1899. }
  1900. $id = $id[1];
  1901. }
  1902. return "https://" . $image["host"] . "/th?id=" . rawurlencode($id);
  1903. }
  1904. private function bingratio($width, $height){
  1905. $ratio = [
  1906. 474 / $width,
  1907. 474 / $height
  1908. ];
  1909. if($ratio[0] < $ratio[1]){
  1910. $ratio = $ratio[0];
  1911. }else{
  1912. $ratio = $ratio[1];
  1913. }
  1914. return [
  1915. floor($width * $ratio),
  1916. floor($height * $ratio)
  1917. ];
  1918. }
  1919. }