ddg.php 43 KB

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