ddg.php 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246
  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. $item["t"] == "DEEP_ERROR_NO_RESULTS"
  462. ){
  463. return $out;
  464. }
  465. $table = [];
  466. // get youtube video information
  467. if(isset($item["video"]["thumbnail_url_template"])){
  468. $thumb =
  469. [
  470. "ratio" => "16:9",
  471. "url" => $this->bingimg($item["video"]["thumbnail_url_template"])
  472. ];
  473. }else{
  474. $thumb =
  475. [
  476. "ratio" => null,
  477. "url" => null
  478. ];
  479. }
  480. // get table items
  481. if(isset($item["rf"])){
  482. foreach($item["rf"] as $hint){
  483. if(
  484. !isset($hint["label"]["text"]) ||
  485. !isset($hint["items"][0]["text"])
  486. ){
  487. continue;
  488. }
  489. $text = [];
  490. foreach($hint["items"] as $text_part){
  491. $text[] = $text_part["text"];
  492. }
  493. $text = implode(", ", $text);
  494. if(is_numeric($text)){
  495. $text = number_format((string)$text);
  496. }
  497. $table[$hint["label"]["text"]] = $text;
  498. }
  499. }
  500. // get ratings
  501. if(isset($item["ar"])){
  502. foreach($item["ar"] as $rating){
  503. if(
  504. isset($rating["aggregateRating"]["bestRating"]) &&
  505. isset($rating["aggregateRating"]["ratingValue"])
  506. ){
  507. $text = $rating["aggregateRating"]["ratingValue"] . "/" . $rating["aggregateRating"]["bestRating"];
  508. if(isset($rating["aggregateRating"]["reviewCount"])){
  509. $text .= " (" . number_format($rating["aggregateRating"]["reviewCount"]) . " votes)";
  510. }
  511. $table["Rating"] = $text;
  512. }
  513. }
  514. }
  515. // get sublinks
  516. $sublinks = [];
  517. if(isset($item["l"])){
  518. foreach($item["l"] as $sublink){
  519. $sublinks[] = [
  520. "title" => $this->titledots($sublink["text"]),
  521. "description" => $this->titledots($sublink["snippet"]),
  522. "url" => $sublink["targetUrl"],
  523. "date" => null
  524. ];
  525. }
  526. }
  527. $title =
  528. $this->titledots(
  529. $this->fuckhtml
  530. ->getTextContent(
  531. $item["t"]
  532. )
  533. );
  534. if(
  535. $title == "EOF" &&
  536. strpos(
  537. $item["c"],
  538. "google"
  539. )
  540. ){
  541. continue;
  542. }
  543. // parse search result
  544. $out["web"][] = [
  545. "title" =>
  546. $this->titledots(
  547. $this->fuckhtml
  548. ->getTextContent(
  549. $item["t"]
  550. )
  551. ),
  552. "description" =>
  553. isset($item["a"]) ?
  554. $this->titledots(
  555. $this->fuckhtml
  556. ->getTextContent(
  557. $item["a"]
  558. )
  559. ) : null,
  560. "url" => $this->unshiturl($item["c"]),
  561. "date" =>
  562. isset($item["e"]) ?
  563. strtotime($item["e"]) : null,
  564. "type" => "web",
  565. "thumb" => $thumb,
  566. "sublink" => $sublinks,
  567. "table" => $table
  568. ];
  569. continue;
  570. }
  571. if(isset($item["n"])){
  572. // get NPT
  573. $out["npt"] =
  574. $this->backend->store(
  575. $item["n"],
  576. "web",
  577. $proxy
  578. );
  579. continue;
  580. }
  581. }
  582. //
  583. // Get spelling
  584. //
  585. $js_tmp =
  586. preg_split(
  587. '/DDG\.page\.showMessage\(\s*\'spelling\'\s*,\s*/',
  588. $js,
  589. 2
  590. );
  591. if(count($js_tmp) > 1){
  592. $json =
  593. json_decode(
  594. $this->fuckhtml
  595. ->extract_json(
  596. $js_tmp[1]
  597. ),
  598. true
  599. );
  600. if($json !== null){
  601. // parse spelling
  602. // qc=2: including
  603. switch((int)$json["qc"]){
  604. case 2:
  605. $type = "including";
  606. break;
  607. default:
  608. $type = "not_many";
  609. break;
  610. }
  611. $out["spelling"] = [
  612. "type" => $type,
  613. "using" =>
  614. $this->fuckhtml
  615. ->getTextContent(
  616. $json["suggestion"]
  617. ),
  618. "correction" => html_entity_decode($json["recourseText"])
  619. ];
  620. }
  621. }
  622. //
  623. // Get images
  624. //
  625. $js_tmp =
  626. preg_split(
  627. '/DDG\.duckbar\.load\(\s*\'images\'\s*,\s*/',
  628. $js,
  629. 2
  630. );
  631. if(count($js_tmp) > 1){
  632. $json =
  633. json_decode(
  634. $this->fuckhtml
  635. ->extract_json(
  636. $js_tmp[1]
  637. ),
  638. true
  639. );
  640. if($json !== null){
  641. foreach($json["results"] as $image){
  642. $ratio = $this->bingratio((int)$image["width"], (int)$image["height"]);
  643. $out["image"][] = [
  644. "title" => $image["title"],
  645. "source" => [
  646. [
  647. "url" => $image["image"],
  648. "width" => (int)$image["width"],
  649. "height" => (int)$image["height"]
  650. ],
  651. [
  652. "url" => $this->bingimg($image["thumbnail"]),
  653. "width" => $ratio[0],
  654. "height" => $ratio[1]
  655. ]
  656. ],
  657. "url" => $this->unshiturl($image["url"])
  658. ];
  659. }
  660. }
  661. }
  662. //
  663. // Get videos
  664. //
  665. $js_tmp =
  666. preg_split(
  667. '/DDG\.duckbar\.load\(\s*\'videos\'\s*,\s*/',
  668. $js,
  669. 2
  670. );
  671. if(count($js_tmp) > 1){
  672. $json =
  673. json_decode(
  674. $this->fuckhtml
  675. ->extract_json(
  676. $js_tmp[1]
  677. ),
  678. true
  679. );
  680. if($json !== null){
  681. foreach($json["results"] as $video){
  682. $thumb = [
  683. "ratio" => null,
  684. "url" => null
  685. ];
  686. foreach(["large", "medium", "small"] as $contender){
  687. if(isset($video["images"][$contender])){
  688. $thumb = [
  689. "ratio" => "16:9",
  690. "url" => $this->bingimg($video["images"][$contender])
  691. ];
  692. break;
  693. }
  694. }
  695. $out["video"][] = [
  696. "title" => $this->titledots($video["title"]),
  697. "description" =>
  698. $video["description"] != "" ?
  699. $this->titledots($video["description"]) : null,
  700. "date" =>
  701. isset($video["published"]) ?
  702. strtotime($video["published"]) : null,
  703. "duration" =>
  704. $video["duration"] != "" ?
  705. $this->hms2int($video["duration"]) : null,
  706. "views" =>
  707. isset($video["statistics"]["viewCount"]) ?
  708. (int)$video["statistics"]["viewCount"] : null,
  709. "thumb" => $thumb,
  710. "url" => $this->unshiturl($video["content"])
  711. ];
  712. }
  713. }
  714. }
  715. //
  716. // Get news
  717. //
  718. $js_tmp =
  719. preg_split(
  720. '/DDG\.duckbar\.load\(\s*\'news\'\s*,\s*/',
  721. $js,
  722. 2
  723. );
  724. if(count($js_tmp) > 1){
  725. $json =
  726. json_decode(
  727. $this->fuckhtml
  728. ->extract_json(
  729. $js_tmp[1]
  730. ),
  731. true
  732. );
  733. if($json !== null){
  734. foreach($json["results"] as $news){
  735. if(isset($news["image"])){
  736. $thumb = [
  737. "ratio" => "16:9",
  738. "url" => $news["image"]
  739. ];
  740. }else{
  741. $thumb = [
  742. "ratio" => null,
  743. "url" => null
  744. ];
  745. }
  746. $out["news"][] = [
  747. "title" => $news["title"],
  748. "description" =>
  749. $this->fuckhtml
  750. ->getTextContent(
  751. $news["excerpt"]
  752. ),
  753. "date" => (int)$news["date"],
  754. "thumb" => $thumb,
  755. "url" => $news["url"]
  756. ];
  757. }
  758. }
  759. }
  760. //
  761. // Get related searches
  762. //
  763. $js_tmp =
  764. preg_split(
  765. '/DDG\.duckbar\.loadModule\(\s*\'related_searches\'\s*,\s*/',
  766. $js,
  767. 2
  768. );
  769. if(count($js_tmp) > 1){
  770. $json =
  771. json_decode(
  772. $this->fuckhtml
  773. ->extract_json(
  774. $js_tmp[1]
  775. ),
  776. true
  777. );
  778. if($json !== null){
  779. foreach($json["results"] as $related){
  780. $out["related"][] = $related["text"];
  781. }
  782. }
  783. }
  784. //
  785. // Get instant answers
  786. //
  787. $js_tmp =
  788. preg_split(
  789. '/DDG\.duckbar\.add\(\s*/',
  790. $html . $js,
  791. 2
  792. );
  793. if(count($js_tmp) > 1){
  794. $json =
  795. json_decode(
  796. $this->fuckhtml
  797. ->extract_json(
  798. $js_tmp[1]
  799. ),
  800. true
  801. );
  802. if($json !== null){
  803. $json = $json["data"];
  804. $table = [];
  805. $sublinks = [];
  806. $description = [];
  807. // get official website
  808. if(
  809. isset($json["OfficialWebsite"]) &&
  810. $json["OfficialWebsite"] !== null
  811. ){
  812. $sublinks["Website"] = $json["OfficialWebsite"];
  813. }
  814. // get sublinks & table elements
  815. if(isset($json["Infobox"]["content"])){
  816. foreach($json["Infobox"]["content"] as $info){
  817. if($info["data_type"] == "string"){
  818. // add table element
  819. $table[$info["label"]] = $info["value"];
  820. continue;
  821. }
  822. if($info["data_type"] == "wd_description"){
  823. $description[] = [
  824. "type" => "quote",
  825. "value" => $info["value"]
  826. ];
  827. continue;
  828. }
  829. // add sublink
  830. switch($info["data_type"]){
  831. case "official_site":
  832. case "official_website":
  833. $type = "Website";
  834. break;
  835. case "wikipedia": $type = "Wikipedia"; break;
  836. case "itunes": $type = "iTunes"; break;
  837. case "amazon": $type = "Amazon"; break;
  838. case "imdb_title_id":
  839. case "imdb_id":
  840. case "imdb_name_id":
  841. $type = "IMDb";
  842. $delim = substr($info["value"], 0, 2);
  843. if($delim == "nm"){
  844. $prefix = "https://www.imdb.com/name/";
  845. }elseif($delim == "tt"){
  846. $prefix = "https://www.imdb.com/title/";
  847. }elseif($delim == "co"){
  848. $prefix = "https://www.imdb.com/search/title/?companies=";
  849. }else{
  850. $prefix = "https://www.imdb.com/title/";
  851. }
  852. break;
  853. case "imdb_name_id": $prefix = "https://www.imdb.com/name/"; $type = "IMDb"; break;
  854. case "twitter_profile": $prefix = "https://twitter.com/"; $type = "Twitter"; break;
  855. case "instagram_profile": $prefix = "https://instagram.com/"; $type = "Instagram"; break;
  856. case "facebook_profile": $prefix = "https://facebook.com/"; $type = "Facebook"; break;
  857. case "spotify_artist_id": $prefix = "https://open.spotify.com/artist/"; $type = "Spotify"; break;
  858. case "itunes_artist_id": $prefix = "https://music.apple.com/us/artist/"; $type = "iTunes"; break;
  859. case "rotten_tomatoes": $prefix = "https://rottentomatoes.com/"; $type = "Rotten Tomatoes"; break;
  860. case "youtube_channel": $prefix = "https://youtube.com/channel/"; $type = "YouTube"; break;
  861. case "soundcloud_id": $prefix = "https://soundcloud.com/"; $type = "SoundCloud"; break;
  862. default:
  863. $prefix = null;
  864. $type = false;
  865. }
  866. if($type !== false){
  867. if($prefix === null){
  868. $sublinks[$type] = $info["value"];
  869. }else{
  870. $sublinks[$type] = $prefix . $info["value"];
  871. }
  872. }
  873. }
  874. }
  875. if(isset($json["Abstract"])){
  876. $description = $this->parse_rich_text($json["Abstract"]);
  877. }
  878. if(
  879. !isset($json["Image"]) ||
  880. $json["Image"] == "" ||
  881. $json["Image"] === null ||
  882. $json["Image"] == "https://duckduckgo.com/i/"
  883. ){
  884. $image = null;
  885. }else{
  886. if(
  887. preg_match(
  888. '/^https?:\/\//',
  889. $json["Image"]
  890. )
  891. ){
  892. $image = $json["Image"];
  893. }else{
  894. $image = "https://duckduckgo.com" . $json["Image"];
  895. }
  896. }
  897. $out["answer"][] = [
  898. "title" => $json["Heading"],
  899. "description" => $description,
  900. "url" => $json["AbstractURL"],
  901. "thumb" => $image,
  902. "table" => $table,
  903. "sublink" => $sublinks
  904. ];
  905. }
  906. }
  907. if($get["extendedsearch"] == "no"){
  908. return $out;
  909. }
  910. //
  911. // Parse additional data endpoints
  912. //
  913. //nrj('/js/spice/dictionary/definition/create', null, null, null, null, 'dictionary_definition');
  914. preg_match_all(
  915. '/nrj\(\s*\'([^\']+)\'/',
  916. $js,
  917. $nrj
  918. );
  919. if(isset($nrj[1])){
  920. foreach($nrj[1] as $potential_endpoint){
  921. //
  922. // Probe for wordnik definition
  923. //
  924. preg_match(
  925. '/\/js\/spice\/dictionary\/definition\/([^\/]+)/',
  926. $potential_endpoint,
  927. $word
  928. );
  929. if(isset($word[1])){
  930. $word = $word[1];
  931. // found wordnik definition & word
  932. try{
  933. $nik =
  934. $this->get(
  935. $proxy,
  936. "https://duckduckgo.com/js/spice/dictionary/definition/" . $word,
  937. [],
  938. ddg::req_xhr
  939. );
  940. }catch(Exception $e){
  941. // fail gracefully
  942. return $out;
  943. }
  944. // remove javascript
  945. $js_tmp =
  946. preg_split(
  947. '/ddg_spice_dictionary_definition\(\s*/',
  948. $nik,
  949. 2
  950. );
  951. if(count($js_tmp) > 1){
  952. $nik =
  953. json_decode(
  954. $this->fuckhtml
  955. ->extract_json(
  956. $js_tmp[1]
  957. ),
  958. true
  959. );
  960. }
  961. if($nik === null){
  962. return $out;
  963. }
  964. $answer_cat = [];
  965. $answer = [];
  966. foreach($nik as $snippet){
  967. if(!isset($snippet["partOfSpeech"])){ continue; }
  968. $push = [];
  969. // add text snippet
  970. if(isset($snippet["text"])){
  971. $push[] = [
  972. "type" => "text",
  973. "value" =>
  974. $this->fuckhtml
  975. ->getTextContent(
  976. $snippet["text"]
  977. )
  978. ];
  979. }
  980. // add example uses
  981. if(isset($snippet["exampleUses"])){
  982. foreach($snippet["exampleUses"] as $example){
  983. $push[] = [
  984. "type" => "quote",
  985. "value" => "\"" .
  986. $this->fuckhtml
  987. ->getTextContent(
  988. $example["text"]
  989. ) . "\""
  990. ];
  991. }
  992. }
  993. // add citations
  994. if(isset($snippet["citations"])){
  995. foreach($snippet["citations"] as $citation){
  996. if(!isset($citation["cite"])){ continue; }
  997. $text =
  998. $this->fuckhtml
  999. ->getTextContent(
  1000. $citation["cite"]
  1001. );
  1002. if(isset($citation["source"])){
  1003. $text .=
  1004. " - " .
  1005. $this->fuckhtml
  1006. ->getTextContent(
  1007. $citation["source"]
  1008. );
  1009. }
  1010. $push[] = [
  1011. "type" => "quote",
  1012. "value" => $text
  1013. ];
  1014. }
  1015. }
  1016. // add related words
  1017. if(isset($snippet["relatedWords"])){
  1018. $relations = [];
  1019. foreach($snippet["relatedWords"] as $related){
  1020. $words = [];
  1021. foreach($related["words"] as $wrd){
  1022. $words[] =
  1023. $this->fuckhtml
  1024. ->getTextContent(
  1025. $wrd
  1026. );
  1027. }
  1028. if(
  1029. count($words) !== 0 &&
  1030. isset($related["relationshipType"])
  1031. ){
  1032. $relations[ucfirst($related["relationshipType"]) . "s"] =
  1033. implode(", ", $words);
  1034. }
  1035. }
  1036. foreach($relations as $relation_title => $relation_content){
  1037. $push[] = [
  1038. "type" => "quote",
  1039. "value" => $relation_title . ": " . $relation_content
  1040. ];
  1041. }
  1042. }
  1043. if(count($push) !== 0){
  1044. // push data to answer_cat
  1045. if(!isset($answer_cat[$snippet["partOfSpeech"]])){
  1046. $answer_cat[$snippet["partOfSpeech"]] = [];
  1047. }
  1048. $answer_cat[$snippet["partOfSpeech"]] =
  1049. array_merge(
  1050. $answer_cat[$snippet["partOfSpeech"]],
  1051. $push
  1052. );
  1053. }
  1054. }
  1055. foreach($answer_cat as $answer_title => $answer_content){
  1056. $i = 0;
  1057. $answer[] = [
  1058. "type" => "title",
  1059. "value" => $answer_title
  1060. ];
  1061. $old_type = $answer[count($answer) - 1]["type"];
  1062. foreach($answer_content as $ans){
  1063. if(
  1064. $ans["type"] == "text" &&
  1065. $old_type == "text"
  1066. ){
  1067. $i++;
  1068. $c = count($answer) - 1;
  1069. // append text to existing textfield
  1070. $answer[$c] = [
  1071. "type" => "text",
  1072. "value" => $answer[$c]["value"] . "\n" . $i . ". " . $ans["value"]
  1073. ];
  1074. }elseif($ans["type"] == "text"){
  1075. $i++;
  1076. $answer[] = [
  1077. "type" => "text",
  1078. "value" => $i . ". " . $ans["value"]
  1079. ];
  1080. }else{
  1081. // append normally
  1082. $answer[] = $ans;
  1083. }
  1084. $old_type = $ans["type"];
  1085. }
  1086. }
  1087. // yeah.. sometimes duckduckgo doesnt give us a definition back
  1088. if(count($answer) !== 0){
  1089. $out["answer"][] = [
  1090. "title" => ucfirst($word),
  1091. "description" => $answer,
  1092. "url" => "https://www.wordnik.com/words/" . $word,
  1093. "thumb" => null,
  1094. "table" => [],
  1095. "sublink" => []
  1096. ];
  1097. }
  1098. }
  1099. //
  1100. // Parse stackoverflow answer
  1101. //
  1102. if(
  1103. preg_match(
  1104. '/^\/a\.js.*src_id=stack_overflow/',
  1105. $potential_endpoint
  1106. )
  1107. ){
  1108. // found stackoverflow answer
  1109. try{
  1110. $json =
  1111. $this->get(
  1112. $proxy,
  1113. "https://duckduckgo.com" . $potential_endpoint,
  1114. [],
  1115. ddg::req_xhr
  1116. );
  1117. }catch(Exception $e){
  1118. // fail gracefully
  1119. return $out;
  1120. }
  1121. $json = explode("DDG.duckbar.add_array(", $json, 2);
  1122. if(count($json) === 2){
  1123. $json =
  1124. json_decode(
  1125. $this->fuckhtml
  1126. ->extract_json(
  1127. $json[1]
  1128. ),
  1129. true
  1130. );
  1131. if(
  1132. $json !== null &&
  1133. isset($json[0]["data"])
  1134. ){
  1135. $json = $json[0]["data"];
  1136. foreach($json as $answer){
  1137. if(isset($answer["Heading"])){
  1138. $title = $answer["Heading"];
  1139. }elseif(isset($answer["title"])){
  1140. $title = $answer["title"];
  1141. }else{
  1142. $title = null;
  1143. }
  1144. if(
  1145. $title !== null &&
  1146. isset($answer["Abstract"])
  1147. ){
  1148. $description = $this->parse_rich_text($answer["Abstract"]);
  1149. $out["answer"][] = [
  1150. "title" => $title,
  1151. "description" => $description,
  1152. "url" => $answer["AbstractURL"],
  1153. "thumb" => null,
  1154. "table" => [],
  1155. "sublink" => []
  1156. ];
  1157. }
  1158. }
  1159. }
  1160. }
  1161. }
  1162. }
  1163. }
  1164. return $out;
  1165. }
  1166. public function image($get){
  1167. if($get["npt"]){
  1168. [$js_link, $proxy] = $this->backend->get($get["npt"], "images");
  1169. }else{
  1170. if(strlen($get["s"]) === 0){
  1171. throw new Exception("Search term is empty!");
  1172. }
  1173. $proxy = $this->backend->get_ip();
  1174. $filters = [];
  1175. if($get["date"] != "any"){ $filters[] = "time:{$get["date"]}"; }
  1176. if($get["size"] != "any"){ $filters[] = "size:{$get["size"]}"; }
  1177. if($get["color"] != "any"){ $filters[] = "color:{$get["color"]}"; }
  1178. if($get["type"] != "any"){ $filters[] = "type:{$get["type"]}"; }
  1179. if($get["layout"] != "any"){ $filters[] = "layout:{$get["layout"]}"; }
  1180. if($get["license"] != "any"){ $filters[] = "license:{$get["license"]}"; }
  1181. $filters = implode(",", $filters);
  1182. $get_filters = [
  1183. "q" => $get["s"],
  1184. "iax" => "images",
  1185. "ia" => "images"
  1186. ];
  1187. if($filters != ""){
  1188. $get_filters["iaf"] = $filters;
  1189. }
  1190. $nsfw = $get["nsfw"] == "yes" ? "-1" : "1";
  1191. $get_filters["kp"] = $nsfw;
  1192. try{
  1193. $html = $this->get(
  1194. $proxy,
  1195. "https://duckduckgo.com",
  1196. $get_filters,
  1197. ddg::req_web
  1198. );
  1199. }catch(Exception $err){
  1200. throw new Exception("Failed to fetch search page");
  1201. }
  1202. preg_match(
  1203. '/vqd="([0-9-]+)"/',
  1204. $html,
  1205. $vqd
  1206. );
  1207. if(!isset($vqd[1])){
  1208. throw new Exception("Failed to grep VQD token");
  1209. }
  1210. $js_link =
  1211. "i.js?" .
  1212. http_build_query([
  1213. "l" => $get["country"],
  1214. "o" => "json",
  1215. "q" => $get["s"],
  1216. "vqd" => $vqd[1],
  1217. "f" => $filters,
  1218. "p" => $nsfw
  1219. ]);
  1220. }
  1221. try{
  1222. $json =
  1223. $this->get(
  1224. $proxy,
  1225. "https://duckduckgo.com/" . $js_link,
  1226. [],
  1227. ddg::req_xhr
  1228. );
  1229. }catch(Exception $error){
  1230. throw new Exception("Failed to get i.js");
  1231. }
  1232. $json = json_decode($json, true);
  1233. if($json === null){
  1234. throw new Exception("Failed to decode JSON");
  1235. }
  1236. $out = [
  1237. "status" => "ok",
  1238. "npt" => null,
  1239. "image" => []
  1240. ];
  1241. if(!isset($json["results"])){
  1242. return $out;
  1243. }
  1244. // get npt
  1245. if(
  1246. isset($json["next"]) &&
  1247. $json["next"] !== null
  1248. ){
  1249. $vqd = null;
  1250. if(isset($vqd[1])){
  1251. $vqd = $vqd[1];
  1252. }else{
  1253. $vqd = array_values($json["vqd"]);
  1254. if(count($vqd) > 0){
  1255. $vqd = $vqd[0];
  1256. }
  1257. }
  1258. if($vqd !== null){
  1259. $out["npt"] =
  1260. $this->backend->store(
  1261. $json["next"] . "&vqd=" . $vqd,
  1262. "images",
  1263. $proxy
  1264. );
  1265. }
  1266. }
  1267. // get images
  1268. foreach($json["results"] as $image){
  1269. $ratio =
  1270. $this->bingratio(
  1271. (int)$image["width"],
  1272. (int)$image["height"]
  1273. );
  1274. $out["image"][] = [
  1275. "title" => $this->titledots($image["title"]),
  1276. "source" => [
  1277. [
  1278. "url" => $image["image"],
  1279. "width" => (int)$image["width"],
  1280. "height" => (int)$image["height"]
  1281. ],
  1282. [
  1283. "url" => $this->bingimg($image["thumbnail"]),
  1284. "width" => $ratio[0],
  1285. "height" => $ratio[1]
  1286. ]
  1287. ],
  1288. "url" => $this->unshiturl($image["url"])
  1289. ];
  1290. }
  1291. return $out;
  1292. }
  1293. public function video($get){
  1294. if($get["npt"]){
  1295. [$js_link, $proxy] = $this->backend->get($get["npt"], "videos");
  1296. }else{
  1297. if(strlen($get["s"]) === 0){
  1298. throw new Exception("Search term is empty!");
  1299. }
  1300. $proxy = $this->backend->get_ip();
  1301. $get_filters = [
  1302. "q" => $get["s"],
  1303. "iax" => "videos",
  1304. "ia" => "videos"
  1305. ];
  1306. switch($get["nsfw"]){
  1307. case "yes": $nsfw = "-2"; break;
  1308. case "maybe": $nsfw = "-1"; break;
  1309. case "no": $nsfw = "1"; break;
  1310. }
  1311. $filters = [];
  1312. if($get["date"] != "any"){ $filters[] = "publishedAfter:{$date}"; }
  1313. if($get["resolution"] != "any"){ $filters[] = "videoDefinition:{$resolution}"; }
  1314. if($get["duration"] != "any"){ $filters[] = "videoDuration:{$duration}"; }
  1315. if($get["license"] != "any"){ $filters[] = "videoLicense:{$license}"; }
  1316. $filters = implode(",", $filters);
  1317. if($filters != ""){
  1318. $get_filters["iaf"] = $filters;
  1319. }
  1320. try{
  1321. $html =
  1322. $this->get(
  1323. $proxy,
  1324. "https://duckduckgo.com/",
  1325. $get_filters,
  1326. ddg::req_web
  1327. );
  1328. }catch(Exception $error){
  1329. throw new Exception("Failed to fetch search page");
  1330. }
  1331. preg_match(
  1332. '/vqd="([0-9-]+)"/',
  1333. $html,
  1334. $vqd
  1335. );
  1336. if(!isset($vqd[1])){
  1337. throw new Exception("Failed to grep VQD token");
  1338. }
  1339. $js_link =
  1340. "v.js?" .
  1341. http_build_query([
  1342. "l" => $get["country"],
  1343. "o" => "json",
  1344. "sr" => "1",
  1345. "q" => $get["s"],
  1346. "vqd" => $vqd[1],
  1347. "f" => $filters,
  1348. "p" => $nsfw
  1349. ]);
  1350. }
  1351. try{
  1352. $json =
  1353. $this->get(
  1354. $proxy,
  1355. "https://duckduckgo.com/" . $js_link,
  1356. [],
  1357. ddg::req_xhr
  1358. );
  1359. }catch(Exception $error){
  1360. throw new Exception("Failed to fetch JSON");
  1361. }
  1362. $json = json_decode($json, true);
  1363. if($json === null){
  1364. throw new Exception("Failed to decode JSON");
  1365. }
  1366. $out = [
  1367. "status" => "ok",
  1368. "npt" => null,
  1369. "video" => [],
  1370. "author" => [],
  1371. "livestream" => [],
  1372. "playlist" => [],
  1373. "reel" => []
  1374. ];
  1375. if(!isset($json["results"])){
  1376. return $out;
  1377. }
  1378. // get NPT
  1379. if(
  1380. isset($json["next"]) &&
  1381. $json["next"] !== null
  1382. ){
  1383. $out["npt"] =
  1384. $this->backend->store(
  1385. $json["next"],
  1386. "videos",
  1387. $proxy
  1388. );
  1389. }
  1390. foreach($json["results"] as $video){
  1391. $thumb = [
  1392. "ratio" => null,
  1393. "url" => null
  1394. ];
  1395. foreach(["large", "medium", "small"] as $contender){
  1396. if(isset($video["images"][$contender])){
  1397. $thumb = [
  1398. "ratio" => "16:9",
  1399. "url" => $this->bingimg($video["images"][$contender])
  1400. ];
  1401. break;
  1402. }
  1403. }
  1404. $out["video"][] = [
  1405. "title" => $this->titledots($video["title"]),
  1406. "description" => $this->titledots($video["description"]),
  1407. "author" => [
  1408. "name" =>
  1409. (
  1410. isset($video["uploader"]) &&
  1411. $video["uploader"] != ""
  1412. ) ?
  1413. $video["uploader"] : null,
  1414. "url" => null,
  1415. "avatar" => null
  1416. ],
  1417. "date" =>
  1418. (
  1419. isset($video["published"]) &&
  1420. $video["published"] != ""
  1421. ) ?
  1422. strtotime($video["published"]) : null,
  1423. "duration" =>
  1424. (
  1425. isset($video["duration"]) &&
  1426. $video["duration"] != ""
  1427. ) ?
  1428. $this->hms2int($video["duration"]) : null,
  1429. "views" =>
  1430. isset($video["statistics"]["viewCount"]) ?
  1431. (int)$video["statistics"]["viewCount"] : null,
  1432. "thumb" => $thumb,
  1433. "url" => $this->unshiturl($video["content"])
  1434. ];
  1435. }
  1436. return $out;
  1437. }
  1438. public function news($get){
  1439. if($get["npt"]){
  1440. [$js_link, $proxy] = $this->backend->get($get["npt"], "news");
  1441. }else{
  1442. if(strlen($get["s"]) === 0){
  1443. throw new Exception("Search term is empty!");
  1444. }
  1445. $proxy = $this->backend->get_ip();
  1446. $get_filters = [
  1447. "q" => $get["s"],
  1448. "iar" => "news",
  1449. "ia" => "news"
  1450. ];
  1451. if($get["date"] != "any"){
  1452. $date = $get["date"];
  1453. $get_filters["df"] = $date;
  1454. }else{
  1455. $date = "";
  1456. }
  1457. switch($get["nsfw"]){
  1458. case "yes": $get_filters["kp"] = "-2"; break;
  1459. case "maybe": $get_filters["kp"] = "-1"; break;
  1460. case "no": $get_filters["kp"] = "1"; break;
  1461. }
  1462. try{
  1463. $html =
  1464. $this->get(
  1465. $proxy,
  1466. "https://duckduckgo.com/",
  1467. $get_filters,
  1468. ddg::req_web
  1469. );
  1470. }catch(Exception $error){
  1471. throw new Exception("Failed to fetch search page");
  1472. }
  1473. preg_match(
  1474. '/vqd="([0-9-]+)"/',
  1475. $html,
  1476. $vqd
  1477. );
  1478. if(!isset($vqd[1])){
  1479. throw new Exception("Failed to grep VQD token");
  1480. }
  1481. $js_link =
  1482. "news.js?" .
  1483. http_build_query([
  1484. "l" => $get["country"],
  1485. "o" => "json",
  1486. "noamp" => "1",
  1487. "m" => "30",
  1488. "q" => $get["s"],
  1489. "vqd" => $vqd[1],
  1490. "p" => $get_filters["kp"],
  1491. "df" => $date,
  1492. "u" => "bing"
  1493. ]);
  1494. }
  1495. try{
  1496. $json =
  1497. $this->get(
  1498. $proxy,
  1499. "https://duckduckgo.com/" . $js_link,
  1500. [],
  1501. ddg::req_xhr
  1502. );
  1503. }catch(Exception $error){
  1504. throw new Exception("Failed to fetch JSON");
  1505. }
  1506. $json = json_decode($json, true);
  1507. if($json === null){
  1508. throw new Exception("Failed to decode JSON");
  1509. }
  1510. $out = [
  1511. "status" => "ok",
  1512. "npt" => null,
  1513. "news" => []
  1514. ];
  1515. if(!isset($json["results"])){
  1516. return $out;
  1517. }
  1518. // get NPT
  1519. if(
  1520. isset($json["next"]) &&
  1521. $json["next"] !== null
  1522. ){
  1523. $out["npt"] =
  1524. $this->backend->store(
  1525. $json["next"],
  1526. "news",
  1527. $proxy
  1528. );
  1529. }
  1530. foreach($json["results"] as $news){
  1531. if(
  1532. isset($news["image"]) &&
  1533. $news["image"] != ""
  1534. ){
  1535. $thumb = [
  1536. "ratio" => "16:9",
  1537. "url" => $news["image"]
  1538. ];
  1539. }else{
  1540. $thumb = [
  1541. "ratio" => null,
  1542. "url" => null
  1543. ];
  1544. }
  1545. $out["news"][] = [
  1546. "title" => $news["title"],
  1547. "author" =>
  1548. (
  1549. isset($news["source"]) &&
  1550. $news["source"] != ""
  1551. ) ?
  1552. $news["source"] : null,
  1553. "description" =>
  1554. (
  1555. isset($news["excerpt"]) &&
  1556. $news["excerpt"] != ""
  1557. ) ?
  1558. $this->fuckhtml
  1559. ->getTextContent(
  1560. $news["excerpt"]
  1561. ) : null,
  1562. "date" =>
  1563. isset($news["date"]) ?
  1564. (int)$news["date"] : null,
  1565. "thumb" => $thumb,
  1566. "url" => $this->unshiturl($news["url"])
  1567. ];
  1568. }
  1569. return $out;
  1570. }
  1571. private function parse_rich_text($html){
  1572. $description = [];
  1573. // pre-process the html, remove useless elements
  1574. $html =
  1575. strip_tags(
  1576. $html,
  1577. [
  1578. "h1", "h2", "h3", "h4", "h5", "h6", "h7",
  1579. "pre", "code"
  1580. ]
  1581. );
  1582. $html =
  1583. preg_replace(
  1584. '/<(\/?)pre *[^>]*>\s*<\/?code *[^>]*>/i',
  1585. '<$1pre>',
  1586. $html
  1587. );
  1588. $this->fuckhtml->load($html);
  1589. $tags =
  1590. $this->fuckhtml
  1591. ->getElementsByTagName(
  1592. "*"
  1593. );
  1594. if(count($tags) === 0){
  1595. $description[] = [
  1596. "type" => "text",
  1597. "value" =>
  1598. trim(
  1599. $this->fuckhtml
  1600. ->getTextContent(
  1601. $html,
  1602. true,
  1603. false
  1604. )
  1605. )
  1606. ];
  1607. }else{
  1608. $start = 0;
  1609. $was_code_block = true;
  1610. foreach($tags as $tag){
  1611. $text =
  1612. $this->fuckhtml
  1613. ->getTextContent(
  1614. substr(
  1615. $html,
  1616. $start,
  1617. $tag["startPos"] - $start
  1618. ),
  1619. true,
  1620. false
  1621. );
  1622. if($was_code_block){
  1623. $text = ltrim($text);
  1624. $was_code_block = false;
  1625. }
  1626. $description[] = [
  1627. "type" => "text",
  1628. "value" => $text
  1629. ];
  1630. switch($tag["tagName"]){
  1631. case "pre":
  1632. $append = "code";
  1633. $was_code_block = true;
  1634. $c = count($description) - 1;
  1635. $description[$c]["value"] =
  1636. rtrim($description[$c]["value"]);
  1637. break;
  1638. case "code":
  1639. $append = "inline_code";
  1640. $c = count($description) - 1;
  1641. $description[$c]["value"] =
  1642. rtrim($description[$c]["value"]) . " ";
  1643. break;
  1644. case "h1":
  1645. case "h2":
  1646. case "h3":
  1647. case "h4":
  1648. case "h5":
  1649. case "h6":
  1650. case "h7":
  1651. $append = "title";
  1652. $c = count($description) - 1;
  1653. $description[$c]["value"] =
  1654. rtrim($description[$c]["value"]);
  1655. break;
  1656. }
  1657. $description[] = [
  1658. "type" => $append,
  1659. "value" =>
  1660. trim(
  1661. $this->fuckhtml
  1662. ->getTextContent(
  1663. $tag,
  1664. true,
  1665. false
  1666. )
  1667. )
  1668. ];
  1669. $start = $tag["endPos"];
  1670. }
  1671. // shit out remainder
  1672. $description[] = [
  1673. "type" => "text",
  1674. "value" =>
  1675. trim(
  1676. $this->fuckhtml
  1677. ->getTextContent(
  1678. substr(
  1679. $html,
  1680. $start
  1681. ),
  1682. true,
  1683. false
  1684. )
  1685. )
  1686. ];
  1687. }
  1688. return $description;
  1689. }
  1690. private function titledots($title){
  1691. $substr = substr($title, -3);
  1692. if(
  1693. $substr == "..." ||
  1694. $substr == "…"
  1695. ){
  1696. return trim(substr($title, 0, -3));
  1697. }
  1698. return trim($title);
  1699. }
  1700. private function hms2int($time){
  1701. $parts = explode(":", $time, 3);
  1702. $time = 0;
  1703. if(count($parts) === 3){
  1704. // hours
  1705. $time = $time + ((int)$parts[0] * 3600);
  1706. array_shift($parts);
  1707. }
  1708. if(count($parts) === 2){
  1709. // minutes
  1710. $time = $time + ((int)$parts[0] * 60);
  1711. array_shift($parts);
  1712. }
  1713. // seconds
  1714. $time = $time + (int)$parts[0];
  1715. return $time;
  1716. }
  1717. private function unshiturl($url){
  1718. // check for domains w/out first short subdomain (ex: www.)
  1719. $domain = parse_url($url, PHP_URL_HOST);
  1720. $subdomain = preg_replace(
  1721. '/^[A-z0-9]{1,3}\./',
  1722. "",
  1723. $domain
  1724. );
  1725. switch($subdomain){
  1726. case "ebay.com.au":
  1727. case "ebay.at":
  1728. case "ebay.ca":
  1729. case "ebay.fr":
  1730. case "ebay.de":
  1731. case "ebay.com.hk":
  1732. case "ebay.ie":
  1733. case "ebay.it":
  1734. case "ebay.com.my":
  1735. case "ebay.nl":
  1736. case "ebay.ph":
  1737. case "ebay.pl":
  1738. case "ebay.com.sg":
  1739. case "ebay.es":
  1740. case "ebay.ch":
  1741. case "ebay.co.uk":
  1742. case "cafr.ebay.ca":
  1743. case "ebay.com":
  1744. case "community.ebay.com":
  1745. case "pages.ebay.com":
  1746. // remove ebay tracking elements
  1747. $old_params = parse_url($url, PHP_URL_QUERY);
  1748. parse_str($old_params, $params);
  1749. if(isset($params["mkevt"])){ unset($params["mkevt"]); }
  1750. if(isset($params["mkcid"])){ unset($params["mkcid"]); }
  1751. if(isset($params["mkrid"])){ unset($params["mkrid"]); }
  1752. if(isset($params["campid"])){ unset($params["campid"]); }
  1753. if(isset($params["customid"])){ unset($params["customid"]); }
  1754. if(isset($params["toolid"])){ unset($params["toolid"]); }
  1755. if(isset($params["_sop"])){ unset($params["_sop"]); }
  1756. if(isset($params["_dcat"])){ unset($params["_dcat"]); }
  1757. if(isset($params["epid"])){ unset($params["epid"]); }
  1758. if(isset($params["epid"])){ unset($params["oid"]); }
  1759. $params = http_build_query($params);
  1760. if(strlen($params) === 0){
  1761. $replace = "\?";
  1762. }else{
  1763. $replace = "";
  1764. }
  1765. $url = preg_replace(
  1766. "/" . $replace . preg_quote($old_params, "/") . "$/",
  1767. $params,
  1768. $url
  1769. );
  1770. break;
  1771. }
  1772. return $url;
  1773. }
  1774. private function bingimg($url){
  1775. $image = parse_url($url);
  1776. $id = null;
  1777. if(isset($image["query"])){
  1778. parse_str($image["query"], $str);
  1779. if(isset($str["id"])){
  1780. $id = $str["id"];
  1781. }
  1782. }
  1783. if($id === null){
  1784. $id = explode("/th/id/", $image["path"], 2);
  1785. if(count($id) !== 2){
  1786. // malformed
  1787. return $url;
  1788. }
  1789. $id = $id[1];
  1790. }
  1791. return "https://" . $image["host"] . "/th?id=" . rawurlencode($id);
  1792. }
  1793. private function bingratio($width, $height){
  1794. $ratio = [
  1795. 474 / $width,
  1796. 474 / $height
  1797. ];
  1798. if($ratio[0] < $ratio[1]){
  1799. $ratio = $ratio[0];
  1800. }else{
  1801. $ratio = $ratio[1];
  1802. }
  1803. return [
  1804. floor($width * $ratio),
  1805. floor($height * $ratio)
  1806. ];
  1807. }
  1808. }