1
0

ddg.php 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967
  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. "no" => "No"
  264. ]
  265. ],
  266. "date" => [
  267. "display" => "Time fetched",
  268. "option" => [
  269. "any" => "Any time",
  270. "d" => "Past day",
  271. "w" => "Past week",
  272. "m" => "Past month"
  273. ]
  274. ],
  275. "resolution" => [ //videoDefinition
  276. "display" => "Resolution",
  277. "option" => [
  278. "any" => "Any resolution",
  279. "high" => "High definition",
  280. "standard" => "Standard definition"
  281. ]
  282. ],
  283. "duration" => [ // videoDuration
  284. "display" => "Duration",
  285. "option" => [
  286. "any" => "Any duration",
  287. "short" => "Short (>5min)",
  288. "medium" => "Medium (5-20min)",
  289. "long" => "Long (<20min)"
  290. ]
  291. ],
  292. "license" => [
  293. "display" => "License",
  294. "option" => [
  295. "any" => "Any license",
  296. "creativeCommon" => "Creative Commons",
  297. "youtube" => "YouTube Standard"
  298. ]
  299. ]
  300. ]
  301. );
  302. break;
  303. case "news":
  304. return array_merge($base,
  305. [
  306. "nsfw" => [
  307. "display" => "NSFW",
  308. "option" => [
  309. "yes" => "Yes",
  310. "maybe" => "Maybe",
  311. "no" => "No"
  312. ]
  313. ],
  314. "date" => [
  315. "display" => "Time posted",
  316. "option" => [
  317. "any" => "Any time",
  318. "d" => "Past day",
  319. "w" => "Past week",
  320. "m" => "Past month"
  321. ]
  322. ]
  323. ]
  324. );
  325. break;
  326. }
  327. }
  328. public function web($get){
  329. $out = [
  330. "status" => "ok",
  331. "spelling" => [
  332. "type" => "no_correction",
  333. "using" => null,
  334. "correction" => null
  335. ],
  336. "npt" => null,
  337. "answer" => [],
  338. "web" => [],
  339. "image" => [],
  340. "video" => [],
  341. "news" => [],
  342. "related" => []
  343. ];
  344. if($get["npt"]){
  345. [$js_link, $proxy] = $this->backend->get($get["npt"], "web");
  346. $js_link = "https://links.duckduckgo.com" . $js_link;
  347. $html = "";
  348. $get["extendedsearch"] = "no";
  349. }else{
  350. if(strlen($get["s"]) === 0){
  351. throw new Exception("Search term is empty!");
  352. }
  353. $proxy = $this->backend->get_ip();
  354. // generate filters
  355. $get_filters = [
  356. "q" => $get["s"]
  357. ];
  358. if($get["country"] == "any"){
  359. $get_filters["kl"] = "wt-wt";
  360. }else{
  361. $get_filters["kl"] = $get["country"];
  362. }
  363. switch($get["nsfw"]){
  364. case "yes": $get_filters["kp"] = "-2"; break;
  365. case "maybe": $get_filters["kp"] = "-1"; break;
  366. case "no": $get_filters["kp"] = "1"; break;
  367. }
  368. $df = true;
  369. if($get["newer"] === false){
  370. if($get["older"] !== false){
  371. $start = 36000;
  372. $end = $get["older"];
  373. }else{
  374. $df = false;
  375. }
  376. }else{
  377. $start = $get["newer"];
  378. if($get["older"] !== false){
  379. $end = $get["older"];
  380. }else{
  381. $end = time();
  382. }
  383. }
  384. if($df === true){
  385. $get_filters["df"] = date("Y-m-d", $start) . ".." . date("Y-m-d", $end);
  386. }
  387. //
  388. // Get HTML
  389. //
  390. try{
  391. $html = $this->get(
  392. $proxy,
  393. "https://duckduckgo.com/",
  394. $get_filters
  395. );
  396. }catch(Exception $e){
  397. throw new Exception("Failed to fetch search page");
  398. }
  399. $this->fuckhtml->load($html);
  400. $script =
  401. $this->fuckhtml
  402. ->getElementById(
  403. "deep_preload_link",
  404. "link"
  405. );
  406. if(
  407. $script === null ||
  408. !isset($script["attributes"]["href"])
  409. ){
  410. throw new Exception("Failed to grep d.js");
  411. }
  412. $js_link =
  413. $this->fuckhtml
  414. ->getTextContent(
  415. $script["attributes"]["href"]
  416. );
  417. }
  418. //
  419. // Get d.js
  420. //
  421. try{
  422. $js = $this->get(
  423. $proxy,
  424. $js_link,
  425. [],
  426. ddg::req_xhr
  427. );
  428. }catch(Exception $e){
  429. throw new Exception("Failed to fetch d.js");
  430. }
  431. //echo htmlspecialchars($js);
  432. $js_tmp =
  433. preg_split(
  434. '/DDG\.pageLayout\.load\(\s*\'d\'\s*,\s*/',
  435. $js,
  436. 2
  437. );
  438. if(count($js_tmp) <= 1){
  439. throw new Exception("Failed to grep pageLayout(d)");
  440. }
  441. $json =
  442. json_decode(
  443. $this->fuckhtml
  444. ->extract_json(
  445. $js_tmp[1]
  446. ),
  447. true
  448. );
  449. if($json === null){
  450. throw new Exception("Failed to decode JSON");
  451. }
  452. //
  453. // Get search results + NPT token
  454. //
  455. foreach($json as $item){
  456. if(isset($item["c"])){
  457. $table = [];
  458. // get youtube video information
  459. if(isset($item["video"]["thumbnail_url_template"])){
  460. $thumb =
  461. [
  462. "ratio" => "16:9",
  463. "url" => $this->bingimg($item["video"]["thumbnail_url_template"])
  464. ];
  465. }else{
  466. $thumb =
  467. [
  468. "ratio" => null,
  469. "url" => null
  470. ];
  471. }
  472. // get table items
  473. if(isset($item["rf"])){
  474. foreach($item["rf"] as $hint){
  475. if(
  476. !isset($hint["label"]["text"]) ||
  477. !isset($hint["items"][0]["text"])
  478. ){
  479. continue;
  480. }
  481. $text = [];
  482. foreach($hint["items"] as $text_part){
  483. $text[] = $text_part["text"];
  484. }
  485. $text = implode(", ", $text);
  486. if(is_numeric($text)){
  487. $text = number_format((string)$text);
  488. }
  489. $table[$hint["label"]["text"]] = $text;
  490. }
  491. }
  492. // get ratings
  493. if(isset($item["ar"])){
  494. foreach($item["ar"] as $rating){
  495. if(
  496. isset($rating["aggregateRating"]["bestRating"]) &&
  497. isset($rating["aggregateRating"]["ratingValue"])
  498. ){
  499. $text = $rating["aggregateRating"]["ratingValue"] . "/" . $rating["aggregateRating"]["bestRating"];
  500. if(isset($rating["aggregateRating"]["reviewCount"])){
  501. $text .= " (" . number_format($rating["aggregateRating"]["reviewCount"]) . " votes)";
  502. }
  503. $table["Rating"] = $text;
  504. }
  505. }
  506. }
  507. // get sublinks
  508. $sublinks = [];
  509. if(isset($item["l"])){
  510. foreach($item["l"] as $sublink){
  511. $sublinks[] = [
  512. "title" => $this->titledots($sublink["text"]),
  513. "description" => $this->titledots($sublink["snippet"]),
  514. "url" => $sublink["targetUrl"],
  515. "date" => null
  516. ];
  517. }
  518. }
  519. $title =
  520. $this->titledots(
  521. $this->fuckhtml
  522. ->getTextContent(
  523. $item["t"]
  524. )
  525. );
  526. if(
  527. $title == "EOF" &&
  528. strpos(
  529. $item["c"],
  530. "google"
  531. )
  532. ){
  533. continue;
  534. }
  535. // parse search result
  536. $out["web"][] = [
  537. "title" =>
  538. $this->titledots(
  539. $this->fuckhtml
  540. ->getTextContent(
  541. $item["t"]
  542. )
  543. ),
  544. "description" =>
  545. isset($item["a"]) ?
  546. $this->titledots(
  547. $this->fuckhtml
  548. ->getTextContent(
  549. $item["a"]
  550. )
  551. ) : null,
  552. "url" => $this->unshiturl($item["c"]),
  553. "date" =>
  554. isset($item["e"]) ?
  555. strtotime($item["e"]) : null,
  556. "type" => "web",
  557. "thumb" => $thumb,
  558. "sublink" => $sublinks,
  559. "table" => $table
  560. ];
  561. continue;
  562. }
  563. if(isset($item["n"])){
  564. // get NPT
  565. $out["npt"] =
  566. $this->backend->store(
  567. $item["n"],
  568. "web",
  569. $proxy
  570. );
  571. continue;
  572. }
  573. }
  574. //
  575. // Get spelling
  576. //
  577. $js_tmp =
  578. preg_split(
  579. '/DDG\.page\.showMessage\(\s*\'spelling\'\s*,\s*/',
  580. $js,
  581. 2
  582. );
  583. if(count($js_tmp) > 1){
  584. $json =
  585. json_decode(
  586. $this->fuckhtml
  587. ->extract_json(
  588. $js_tmp[1]
  589. ),
  590. true
  591. );
  592. if($json !== null){
  593. // parse spelling
  594. // qc=2: including
  595. switch((int)$json["qc"]){
  596. case 2:
  597. $type = "including";
  598. break;
  599. default:
  600. $type = "not_many";
  601. break;
  602. }
  603. $out["spelling"] = [
  604. "type" => $type,
  605. "using" =>
  606. $this->fuckhtml
  607. ->getTextContent(
  608. $json["suggestion"]
  609. ),
  610. "correction" => $json["recourseText"]
  611. ];
  612. }
  613. }
  614. //
  615. // Get images
  616. //
  617. $js_tmp =
  618. preg_split(
  619. '/DDG\.duckbar\.load\(\s*\'images\'\s*,\s*/',
  620. $js,
  621. 2
  622. );
  623. if(count($js_tmp) > 1){
  624. $json =
  625. json_decode(
  626. $this->fuckhtml
  627. ->extract_json(
  628. $js_tmp[1]
  629. ),
  630. true
  631. );
  632. if($json !== null){
  633. foreach($json["results"] as $image){
  634. $ratio = $this->bingratio((int)$image["width"], (int)$image["height"]);
  635. $out["image"][] = [
  636. "title" => $image["title"],
  637. "source" => [
  638. [
  639. "url" => $image["image"],
  640. "width" => (int)$image["width"],
  641. "height" => (int)$image["height"]
  642. ],
  643. [
  644. "url" => $this->bingimg($image["thumbnail"]),
  645. "width" => $ratio[0],
  646. "height" => $ratio[1]
  647. ]
  648. ],
  649. "url" => $this->unshiturl($image["url"])
  650. ];
  651. }
  652. }
  653. }
  654. //
  655. // Get videos
  656. //
  657. $js_tmp =
  658. preg_split(
  659. '/DDG\.duckbar\.load\(\s*\'videos\'\s*,\s*/',
  660. $js,
  661. 2
  662. );
  663. if(count($js_tmp) > 1){
  664. $json =
  665. json_decode(
  666. $this->fuckhtml
  667. ->extract_json(
  668. $js_tmp[1]
  669. ),
  670. true
  671. );
  672. if($json !== null){
  673. foreach($json["results"] as $video){
  674. $thumb = [
  675. "ratio" => null,
  676. "url" => null
  677. ];
  678. foreach(["large", "medium", "small"] as $contender){
  679. if(isset($video["images"][$contender])){
  680. $thumb = [
  681. "ratio" => "16:9",
  682. "url" => $this->bingimg($video["images"][$contender])
  683. ];
  684. break;
  685. }
  686. }
  687. $out["video"][] = [
  688. "title" => $this->titledots($video["title"]),
  689. "description" =>
  690. $video["description"] != "" ?
  691. $this->titledots($video["description"]) : null,
  692. "date" =>
  693. isset($video["published"]) ?
  694. strtotime($video["published"]) : null,
  695. "duration" =>
  696. $video["duration"] != "" ?
  697. $this->hms2int($video["duration"]) : null,
  698. "views" =>
  699. isset($video["statistics"]["viewCount"]) ?
  700. (int)$video["statistics"]["viewCount"] : null,
  701. "thumb" => $thumb,
  702. "url" => $this->unshiturl($video["content"])
  703. ];
  704. }
  705. }
  706. }
  707. //
  708. // Get news
  709. //
  710. $js_tmp =
  711. preg_split(
  712. '/DDG\.duckbar\.load\(\s*\'news\'\s*,\s*/',
  713. $js,
  714. 2
  715. );
  716. if(count($js_tmp) > 1){
  717. $json =
  718. json_decode(
  719. $this->fuckhtml
  720. ->extract_json(
  721. $js_tmp[1]
  722. ),
  723. true
  724. );
  725. if($json !== null){
  726. foreach($json["results"] as $news){
  727. if(isset($news["image"])){
  728. $thumb = [
  729. "ratio" => "16:9",
  730. "url" => $news["image"]
  731. ];
  732. }else{
  733. $thumb = [
  734. "ratio" => null,
  735. "url" => null
  736. ];
  737. }
  738. $out["news"][] = [
  739. "title" => $news["title"],
  740. "description" =>
  741. $this->fuckhtml
  742. ->getTextContent(
  743. $news["excerpt"]
  744. ),
  745. "date" => (int)$news["date"],
  746. "thumb" => $thumb,
  747. "url" => $news["url"]
  748. ];
  749. }
  750. }
  751. }
  752. //
  753. // Get related searches
  754. //
  755. $js_tmp =
  756. preg_split(
  757. '/DDG\.duckbar\.loadModule\(\s*\'related_searches\'\s*,\s*/',
  758. $js,
  759. 2
  760. );
  761. if(count($js_tmp) > 1){
  762. $json =
  763. json_decode(
  764. $this->fuckhtml
  765. ->extract_json(
  766. $js_tmp[1]
  767. ),
  768. true
  769. );
  770. if($json !== null){
  771. foreach($json["results"] as $related){
  772. $out["related"][] = $related["text"];
  773. }
  774. }
  775. }
  776. //
  777. // Get instant answers
  778. //
  779. $js_tmp =
  780. preg_split(
  781. '/DDG\.duckbar\.add\(\s*/',
  782. $html . $js,
  783. 2
  784. );
  785. if(count($js_tmp) > 1){
  786. $json =
  787. json_decode(
  788. $this->fuckhtml
  789. ->extract_json(
  790. $js_tmp[1]
  791. ),
  792. true
  793. );
  794. if($json !== null){
  795. $json = $json["data"];
  796. $table = [];
  797. $sublinks = [];
  798. $description = [];
  799. // get official website
  800. if(
  801. isset($json["OfficialWebsite"]) &&
  802. $json["OfficialWebsite"] !== null
  803. ){
  804. $sublinks["Website"] = $json["OfficialWebsite"];
  805. }
  806. // get sublinks & table elements
  807. if(isset($json["Infobox"]["content"])){
  808. foreach($json["Infobox"]["content"] as $info){
  809. if($info["data_type"] == "string"){
  810. // add table element
  811. $table[$info["label"]] = $info["value"];
  812. continue;
  813. }
  814. if($info["data_type"] == "wd_description"){
  815. $description[] = [
  816. "type" => "quote",
  817. "value" => $info["value"]
  818. ];
  819. continue;
  820. }
  821. // add sublink
  822. switch($info["data_type"]){
  823. case "official_site":
  824. case "official_website":
  825. $type = "Website";
  826. break;
  827. case "wikipedia": $type = "Wikipedia"; break;
  828. case "itunes": $type = "iTunes"; break;
  829. case "amazon": $type = "Amazon"; break;
  830. case "imdb_title_id":
  831. case "imdb_id":
  832. case "imdb_name_id":
  833. $type = "IMDb";
  834. $delim = substr($info["value"], 0, 2);
  835. if($delim == "nm"){
  836. $prefix = "https://www.imdb.com/name/";
  837. }elseif($delim == "tt"){
  838. $prefix = "https://www.imdb.com/title/";
  839. }elseif($delim == "co"){
  840. $prefix = "https://www.imdb.com/search/title/?companies=";
  841. }else{
  842. $prefix = "https://www.imdb.com/title/";
  843. }
  844. break;
  845. case "imdb_name_id": $prefix = "https://www.imdb.com/name/"; $type = "IMDb"; break;
  846. case "twitter_profile": $prefix = "https://twitter.com/"; $type = "Twitter"; break;
  847. case "instagram_profile": $prefix = "https://instagram.com/"; $type = "Instagram"; break;
  848. case "facebook_profile": $prefix = "https://facebook.com/"; $type = "Facebook"; break;
  849. case "spotify_artist_id": $prefix = "https://open.spotify.com/artist/"; $type = "Spotify"; break;
  850. case "itunes_artist_id": $prefix = "https://music.apple.com/us/artist/"; $type = "iTunes"; break;
  851. case "rotten_tomatoes": $prefix = "https://rottentomatoes.com/"; $type = "Rotten Tomatoes"; break;
  852. case "youtube_channel": $prefix = "https://youtube.com/channel/"; $type = "YouTube"; break;
  853. case "soundcloud_id": $prefix = "https://soundcloud.com/"; $type = "SoundCloud"; break;
  854. default:
  855. $prefix = null;
  856. $type = false;
  857. }
  858. if($type !== false){
  859. if($prefix === null){
  860. $sublinks[$type] = $info["value"];
  861. }else{
  862. $sublinks[$type] = $prefix . $info["value"];
  863. }
  864. }
  865. }
  866. }
  867. if(isset($json["Abstract"])){
  868. $description[] =
  869. [
  870. "type" => "text",
  871. "value" => $json["Abstract"]
  872. ];
  873. }
  874. $out["answer"][] = [
  875. "title" => $json["Heading"],
  876. "description" => $description,
  877. "url" => $json["AbstractURL"],
  878. "thumb" =>
  879. (isset($json["Image"]) && $json["Image"]) !== null ?
  880. "https://duckduckgo.com" . $json["Image"] : null,
  881. "table" => $table,
  882. "sublink" => $sublinks
  883. ];
  884. }
  885. }
  886. if($get["extendedsearch"] == "no"){
  887. return $out;
  888. }
  889. //
  890. // Get wordnik definition
  891. //
  892. //nrj('/js/spice/dictionary/definition/create', null, null, null, null, 'dictionary_definition');
  893. preg_match(
  894. '/nrj\(\s*\'([^\']+)\'/',
  895. $js,
  896. $nrj
  897. );
  898. if(isset($nrj[1])){
  899. $nrj = $nrj[1];
  900. preg_match(
  901. '/\/js\/spice\/dictionary\/definition\/([^\/]+)/',
  902. $nrj,
  903. $word
  904. );
  905. if(isset($word[1])){
  906. $word = $word[1];
  907. // found wordnik definition & word
  908. try{
  909. $nik =
  910. $this->get(
  911. $proxy,
  912. "https://duckduckgo.com/js/spice/dictionary/definition/" . $word,
  913. [],
  914. ddg::req_xhr
  915. );
  916. }catch(Exception $e){
  917. // fail gracefully
  918. return $out;
  919. }
  920. // remove javascript
  921. $js_tmp =
  922. preg_split(
  923. '/ddg_spice_dictionary_definition\(\s*/',
  924. $nik,
  925. 2
  926. );
  927. if(count($js_tmp) > 1){
  928. $nik =
  929. json_decode(
  930. $this->fuckhtml
  931. ->extract_json(
  932. $js_tmp[1]
  933. ),
  934. true
  935. );
  936. }
  937. if($nik === null){
  938. return $out;
  939. }
  940. $answer_cat = [];
  941. $answer = [];
  942. foreach($nik as $snippet){
  943. if(!isset($snippet["partOfSpeech"])){ continue; }
  944. $push = [];
  945. // add text snippet
  946. if(isset($snippet["text"])){
  947. $push[] = [
  948. "type" => "text",
  949. "value" =>
  950. $this->fuckhtml
  951. ->getTextContent(
  952. $snippet["text"]
  953. )
  954. ];
  955. }
  956. // add example uses
  957. if(isset($snippet["exampleUses"])){
  958. foreach($snippet["exampleUses"] as $example){
  959. $push[] = [
  960. "type" => "quote",
  961. "value" => "\"" .
  962. $this->fuckhtml
  963. ->getTextContent(
  964. $example["text"]
  965. ) . "\""
  966. ];
  967. }
  968. }
  969. // add citations
  970. if(isset($snippet["citations"])){
  971. foreach($snippet["citations"] as $citation){
  972. if(!isset($citation["cite"])){ continue; }
  973. $text =
  974. $this->fuckhtml
  975. ->getTextContent(
  976. $citation["cite"]
  977. );
  978. if(isset($citation["source"])){
  979. $text .=
  980. " - " .
  981. $this->fuckhtml
  982. ->getTextContent(
  983. $citation["source"]
  984. );
  985. }
  986. $push[] = [
  987. "type" => "quote",
  988. "value" => $text
  989. ];
  990. }
  991. }
  992. // add related words
  993. if(isset($snippet["relatedWords"])){
  994. $relations = [];
  995. foreach($snippet["relatedWords"] as $related){
  996. $words = [];
  997. foreach($related["words"] as $wrd){
  998. $words[] =
  999. $this->fuckhtml
  1000. ->getTextContent(
  1001. $wrd
  1002. );
  1003. }
  1004. if(
  1005. count($words) !== 0 &&
  1006. isset($related["relationshipType"])
  1007. ){
  1008. $relations[ucfirst($related["relationshipType"]) . "s"] =
  1009. implode(", ", $words);
  1010. }
  1011. }
  1012. foreach($relations as $relation_title => $relation_content){
  1013. $push[] = [
  1014. "type" => "quote",
  1015. "value" => $relation_title . ": " . $relation_content
  1016. ];
  1017. }
  1018. }
  1019. if(count($push) !== 0){
  1020. // push data to answer_cat
  1021. if(!isset($answer_cat[$snippet["partOfSpeech"]])){
  1022. $answer_cat[$snippet["partOfSpeech"]] = [];
  1023. }
  1024. $answer_cat[$snippet["partOfSpeech"]] =
  1025. array_merge(
  1026. $answer_cat[$snippet["partOfSpeech"]],
  1027. $push
  1028. );
  1029. }
  1030. }
  1031. foreach($answer_cat as $answer_title => $answer_content){
  1032. $i = 0;
  1033. $answer[] = [
  1034. "type" => "title",
  1035. "value" => $answer_title
  1036. ];
  1037. $old_type = $answer[count($answer) - 1]["type"];
  1038. foreach($answer_content as $ans){
  1039. if(
  1040. $ans["type"] == "text" &&
  1041. $old_type == "text"
  1042. ){
  1043. $i++;
  1044. $c = count($answer) - 1;
  1045. // append text to existing textfield
  1046. $answer[$c] = [
  1047. "type" => "text",
  1048. "value" => $answer[$c]["value"] . "\n" . $i . ". " . $ans["value"]
  1049. ];
  1050. }elseif($ans["type"] == "text"){
  1051. $i++;
  1052. $answer[] = [
  1053. "type" => "text",
  1054. "value" => $i . ". " . $ans["value"]
  1055. ];
  1056. }else{
  1057. // append normally
  1058. $answer[] = $ans;
  1059. }
  1060. $old_type = $ans["type"];
  1061. }
  1062. }
  1063. // yeah.. sometimes duckduckgo doesnt give us a definition back
  1064. if(count($answer) !== 0){
  1065. $out["answer"][] = [
  1066. "title" => ucfirst($word),
  1067. "description" => $answer,
  1068. "url" => "https://www.wordnik.com/words/" . $word,
  1069. "thumb" => null,
  1070. "table" => [],
  1071. "sublink" => []
  1072. ];
  1073. }
  1074. }
  1075. }
  1076. return $out;
  1077. }
  1078. public function image($get){
  1079. if($get["npt"]){
  1080. [$js_link, $proxy] = $this->backend->get($get["npt"], "images");
  1081. }else{
  1082. if(strlen($get["s"]) === 0){
  1083. throw new Exception("Search term is empty!");
  1084. }
  1085. $proxy = $this->backend->get_ip();
  1086. $filters = [];
  1087. if($get["date"] != "any"){ $filters[] = "time:{$get["date"]}"; }
  1088. if($get["size"] != "any"){ $filters[] = "size:{$get["size"]}"; }
  1089. if($get["color"] != "any"){ $filters[] = "color:{$get["color"]}"; }
  1090. if($get["type"] != "any"){ $filters[] = "type:{$get["type"]}"; }
  1091. if($get["layout"] != "any"){ $filters[] = "layout:{$get["layout"]}"; }
  1092. if($get["license"] != "any"){ $filters[] = "license:{$get["license"]}"; }
  1093. $filters = implode(",", $filters);
  1094. $get_filters = [
  1095. "q" => $get["s"],
  1096. "iax" => "images",
  1097. "ia" => "images"
  1098. ];
  1099. if($filters != ""){
  1100. $get_filters["iaf"] = $filters;
  1101. }
  1102. $nsfw = $get["nsfw"] == "yes" ? "-2" : "-1";
  1103. $get_filters["kp"] = $nsfw;
  1104. try{
  1105. $html = $this->get(
  1106. $proxy,
  1107. "https://duckduckgo.com",
  1108. $get_filters,
  1109. ddg::req_web
  1110. );
  1111. }catch(Exception $err){
  1112. throw new Exception("Failed to fetch search page");
  1113. }
  1114. preg_match(
  1115. '/vqd="([0-9-]+)"/',
  1116. $html,
  1117. $vqd
  1118. );
  1119. if(!isset($vqd[1])){
  1120. throw new Exception("Failed to grep VQD token");
  1121. }
  1122. $js_link =
  1123. "i.js?" .
  1124. http_build_query([
  1125. "l" => $get["country"],
  1126. "o" => "json",
  1127. "q" => $get["s"],
  1128. "vqd" => $vqd[1],
  1129. "f" => $filters,
  1130. "p" => $nsfw
  1131. ]);
  1132. }
  1133. try{
  1134. $json =
  1135. $this->get(
  1136. $proxy,
  1137. "https://duckduckgo.com/" . $js_link,
  1138. [],
  1139. ddg::req_xhr
  1140. );
  1141. }catch(Exception $error){
  1142. throw new Exception("Failed to get i.js");
  1143. }
  1144. $json = json_decode($json, true);
  1145. if($json === null){
  1146. throw new Exception("Failed to decode JSON");
  1147. }
  1148. $out = [
  1149. "status" => "ok",
  1150. "npt" => null,
  1151. "image" => []
  1152. ];
  1153. if(!isset($json["results"])){
  1154. return $out;
  1155. }
  1156. // get npt
  1157. if(
  1158. isset($json["next"]) &&
  1159. $json["next"] !== null
  1160. ){
  1161. $vqd = null;
  1162. if(isset($vqd[1])){
  1163. $vqd = $vqd[1];
  1164. }else{
  1165. $vqd = array_values($json["vqd"]);
  1166. if(count($vqd) > 0){
  1167. $vqd = $vqd[0];
  1168. }
  1169. }
  1170. if($vqd !== null){
  1171. $out["npt"] =
  1172. $this->backend->store(
  1173. $json["next"] . "&vqd=" . $vqd,
  1174. "images",
  1175. $proxy
  1176. );
  1177. }
  1178. }
  1179. // get images
  1180. foreach($json["results"] as $image){
  1181. $ratio =
  1182. $this->bingratio(
  1183. (int)$image["width"],
  1184. (int)$image["height"]
  1185. );
  1186. $out["image"][] = [
  1187. "title" => $this->titledots($image["title"]),
  1188. "source" => [
  1189. [
  1190. "url" => $image["image"],
  1191. "width" => (int)$image["width"],
  1192. "height" => (int)$image["height"]
  1193. ],
  1194. [
  1195. "url" => $this->bingimg($image["thumbnail"]),
  1196. "width" => $ratio[0],
  1197. "height" => $ratio[1]
  1198. ]
  1199. ],
  1200. "url" => $this->unshiturl($image["url"])
  1201. ];
  1202. }
  1203. return $out;
  1204. }
  1205. public function video($get){
  1206. if($get["npt"]){
  1207. [$js_link, $proxy] = $this->backend->get($get["npt"], "videos");
  1208. }else{
  1209. if(strlen($get["s"]) === 0){
  1210. throw new Exception("Search term is empty!");
  1211. }
  1212. $proxy = $this->backend->get_ip();
  1213. $get_filters = [
  1214. "q" => $get["s"],
  1215. "iax" => "videos",
  1216. "ia" => "videos"
  1217. ];
  1218. $nsfw = $get["nsfw"] == "yes" ? "-2" : "-1";
  1219. $get_filters["kp"] = $nsfw;
  1220. $filters = [];
  1221. if($get["date"] != "any"){ $filters[] = "publishedAfter:{$date}"; }
  1222. if($get["resolution"] != "any"){ $filters[] = "videoDefinition:{$resolution}"; }
  1223. if($get["duration"] != "any"){ $filters[] = "videoDuration:{$duration}"; }
  1224. if($get["license"] != "any"){ $filters[] = "videoLicense:{$license}"; }
  1225. $filters = implode(",", $filters);
  1226. if($filters != ""){
  1227. $get_filters["iaf"] = $filters;
  1228. }
  1229. try{
  1230. $html =
  1231. $this->get(
  1232. $proxy,
  1233. "https://duckduckgo.com/",
  1234. $get_filters,
  1235. ddg::req_web
  1236. );
  1237. }catch(Exception $error){
  1238. throw new Exception("Failed to fetch search page");
  1239. }
  1240. preg_match(
  1241. '/vqd="([0-9-]+)"/',
  1242. $html,
  1243. $vqd
  1244. );
  1245. if(!isset($vqd[1])){
  1246. throw new Exception("Failed to grep VQD token");
  1247. }
  1248. $js_link =
  1249. "v.js?" .
  1250. http_build_query([
  1251. "l" => $get["country"],
  1252. "o" => "json",
  1253. "sr" => "1",
  1254. "q" => $get["s"],
  1255. "vqd" => $vqd[1],
  1256. "f" => $filters,
  1257. "p" => $nsfw
  1258. ]);
  1259. }
  1260. try{
  1261. $json =
  1262. $this->get(
  1263. $proxy,
  1264. "https://duckduckgo.com/" . $js_link,
  1265. [],
  1266. ddg::req_xhr
  1267. );
  1268. }catch(Exception $error){
  1269. throw new Exception("Failed to fetch JSON");
  1270. }
  1271. $json = json_decode($json, true);
  1272. if($json === null){
  1273. throw new Exception("Failed to decode JSON");
  1274. }
  1275. $out = [
  1276. "status" => "ok",
  1277. "npt" => null,
  1278. "video" => [],
  1279. "author" => [],
  1280. "livestream" => [],
  1281. "playlist" => [],
  1282. "reel" => []
  1283. ];
  1284. if(!isset($json["results"])){
  1285. return $out;
  1286. }
  1287. // get NPT
  1288. if(
  1289. isset($json["next"]) &&
  1290. $json["next"] !== null
  1291. ){
  1292. $out["npt"] =
  1293. $this->backend->store(
  1294. $json["next"],
  1295. "videos",
  1296. $proxy
  1297. );
  1298. }
  1299. foreach($json["results"] as $video){
  1300. $thumb = [
  1301. "ratio" => null,
  1302. "url" => null
  1303. ];
  1304. foreach(["large", "medium", "small"] as $contender){
  1305. if(isset($video["images"][$contender])){
  1306. $thumb = [
  1307. "ratio" => "16:9",
  1308. "url" => $this->bingimg($video["images"][$contender])
  1309. ];
  1310. break;
  1311. }
  1312. }
  1313. $out["video"][] = [
  1314. "title" => $this->titledots($video["title"]),
  1315. "description" => $this->titledots($video["description"]),
  1316. "author" => [
  1317. "name" =>
  1318. (
  1319. isset($video["uploader"]) &&
  1320. $video["uploader"] != ""
  1321. ) ?
  1322. $video["uploader"] : null,
  1323. "url" => null,
  1324. "avatar" => null
  1325. ],
  1326. "date" =>
  1327. (
  1328. isset($video["published"]) &&
  1329. $video["published"] != ""
  1330. ) ?
  1331. strtotime($video["published"]) : null,
  1332. "duration" =>
  1333. (
  1334. isset($video["duration"]) &&
  1335. $video["duration"] != ""
  1336. ) ?
  1337. $this->hms2int($video["duration"]) : null,
  1338. "views" =>
  1339. isset($video["statistics"]["viewCount"]) ?
  1340. (int)$video["statistics"]["viewCount"] : null,
  1341. "thumb" => $thumb,
  1342. "url" => $this->unshiturl($video["content"])
  1343. ];
  1344. }
  1345. return $out;
  1346. }
  1347. public function news($get){
  1348. if($get["npt"]){
  1349. [$js_link, $proxy] = $this->backend->get($get["npt"], "news");
  1350. }else{
  1351. if(strlen($get["s"]) === 0){
  1352. throw new Exception("Search term is empty!");
  1353. }
  1354. $proxy = $this->backend->get_ip();
  1355. $get_filters = [
  1356. "q" => $get["s"],
  1357. "iar" => "news",
  1358. "ia" => "news"
  1359. ];
  1360. if($get["date"] != "any"){
  1361. $date = $get["date"];
  1362. $get_filters["df"] = $date;
  1363. }else{
  1364. $date = "";
  1365. }
  1366. switch($get["nsfw"]){
  1367. case "yes": $get_filters["kp"] = "-2"; break;
  1368. case "maybe": $get_filters["kp"] = "-1"; break;
  1369. case "no": $get_filters["kp"] = "1"; break;
  1370. }
  1371. try{
  1372. $html =
  1373. $this->get(
  1374. $proxy,
  1375. "https://duckduckgo.com/",
  1376. $get_filters,
  1377. ddg::req_web
  1378. );
  1379. }catch(Exception $error){
  1380. throw new Exception("Failed to fetch search page");
  1381. }
  1382. preg_match(
  1383. '/vqd="([0-9-]+)"/',
  1384. $html,
  1385. $vqd
  1386. );
  1387. if(!isset($vqd[1])){
  1388. throw new Exception("Failed to grep VQD token");
  1389. }
  1390. $js_link =
  1391. "news.js?" .
  1392. http_build_query([
  1393. "l" => $get["country"],
  1394. "o" => "json",
  1395. "noamp" => "1",
  1396. "m" => "30",
  1397. "q" => $get["s"],
  1398. "vqd" => $vqd[1],
  1399. "p" => $get_filters["kp"],
  1400. "df" => $date,
  1401. "u" => "bing"
  1402. ]);
  1403. }
  1404. try{
  1405. $json =
  1406. $this->get(
  1407. $proxy,
  1408. "https://duckduckgo.com/" . $js_link,
  1409. [],
  1410. ddg::req_xhr
  1411. );
  1412. }catch(Exception $error){
  1413. throw new Exception("Failed to fetch JSON");
  1414. }
  1415. $json = json_decode($json, true);
  1416. if($json === null){
  1417. throw new Exception("Failed to decode JSON");
  1418. }
  1419. $out = [
  1420. "status" => "ok",
  1421. "npt" => null,
  1422. "news" => []
  1423. ];
  1424. if(!isset($json["results"])){
  1425. return $out;
  1426. }
  1427. // get NPT
  1428. if(
  1429. isset($json["next"]) &&
  1430. $json["next"] !== null
  1431. ){
  1432. $out["npt"] =
  1433. $this->backend->store(
  1434. $json["next"],
  1435. "news",
  1436. $proxy
  1437. );
  1438. }
  1439. foreach($json["results"] as $news){
  1440. if(
  1441. isset($news["image"]) &&
  1442. $news["image"] != ""
  1443. ){
  1444. $thumb = [
  1445. "ratio" => "16:9",
  1446. "url" => $news["image"]
  1447. ];
  1448. }else{
  1449. $thumb = [
  1450. "ratio" => null,
  1451. "url" => null
  1452. ];
  1453. }
  1454. $out["news"][] = [
  1455. "title" => $news["title"],
  1456. "author" =>
  1457. (
  1458. isset($news["source"]) &&
  1459. $news["source"] != ""
  1460. ) ?
  1461. $news["source"] : null,
  1462. "description" =>
  1463. (
  1464. isset($news["excerpt"]) &&
  1465. $news["excerpt"] != ""
  1466. ) ?
  1467. $this->fuckhtml
  1468. ->getTextContent(
  1469. $news["excerpt"]
  1470. ) : null,
  1471. "date" =>
  1472. isset($news["date"]) ?
  1473. (int)$news["date"] : null,
  1474. "thumb" => $thumb,
  1475. "url" => $this->unshiturl($news["url"])
  1476. ];
  1477. }
  1478. return $out;
  1479. }
  1480. private function titledots($title){
  1481. $substr = substr($title, -3);
  1482. if(
  1483. $substr == "..." ||
  1484. $substr == "…"
  1485. ){
  1486. return trim(substr($title, 0, -3));
  1487. }
  1488. return trim($title);
  1489. }
  1490. private function hms2int($time){
  1491. $parts = explode(":", $time, 3);
  1492. $time = 0;
  1493. if(count($parts) === 3){
  1494. // hours
  1495. $time = $time + ((int)$parts[0] * 3600);
  1496. array_shift($parts);
  1497. }
  1498. if(count($parts) === 2){
  1499. // minutes
  1500. $time = $time + ((int)$parts[0] * 60);
  1501. array_shift($parts);
  1502. }
  1503. // seconds
  1504. $time = $time + (int)$parts[0];
  1505. return $time;
  1506. }
  1507. private function unshiturl($url){
  1508. // check for domains w/out first short subdomain (ex: www.)
  1509. $domain = parse_url($url, PHP_URL_HOST);
  1510. $subdomain = preg_replace(
  1511. '/^[A-z0-9]{1,3}\./',
  1512. "",
  1513. $domain
  1514. );
  1515. switch($subdomain){
  1516. case "ebay.com.au":
  1517. case "ebay.at":
  1518. case "ebay.ca":
  1519. case "ebay.fr":
  1520. case "ebay.de":
  1521. case "ebay.com.hk":
  1522. case "ebay.ie":
  1523. case "ebay.it":
  1524. case "ebay.com.my":
  1525. case "ebay.nl":
  1526. case "ebay.ph":
  1527. case "ebay.pl":
  1528. case "ebay.com.sg":
  1529. case "ebay.es":
  1530. case "ebay.ch":
  1531. case "ebay.co.uk":
  1532. case "cafr.ebay.ca":
  1533. case "ebay.com":
  1534. case "community.ebay.com":
  1535. case "pages.ebay.com":
  1536. // remove ebay tracking elements
  1537. $old_params = parse_url($url, PHP_URL_QUERY);
  1538. parse_str($old_params, $params);
  1539. if(isset($params["mkevt"])){ unset($params["mkevt"]); }
  1540. if(isset($params["mkcid"])){ unset($params["mkcid"]); }
  1541. if(isset($params["mkrid"])){ unset($params["mkrid"]); }
  1542. if(isset($params["campid"])){ unset($params["campid"]); }
  1543. if(isset($params["customid"])){ unset($params["customid"]); }
  1544. if(isset($params["toolid"])){ unset($params["toolid"]); }
  1545. if(isset($params["_sop"])){ unset($params["_sop"]); }
  1546. if(isset($params["_dcat"])){ unset($params["_dcat"]); }
  1547. if(isset($params["epid"])){ unset($params["epid"]); }
  1548. if(isset($params["epid"])){ unset($params["oid"]); }
  1549. $params = http_build_query($params);
  1550. if(strlen($params) === 0){
  1551. $replace = "\?";
  1552. }else{
  1553. $replace = "";
  1554. }
  1555. $url = preg_replace(
  1556. "/" . $replace . preg_quote($old_params, "/") . "$/",
  1557. $params,
  1558. $url
  1559. );
  1560. break;
  1561. }
  1562. return $url;
  1563. }
  1564. private function bingimg($url){
  1565. $parse = parse_url($url);
  1566. parse_str($parse["query"], $parts);
  1567. return "https://" . $parse["host"] . "/th?id=" . urlencode($parts["id"]);
  1568. }
  1569. private function bingratio($width, $height){
  1570. $ratio = [
  1571. 474 / $width,
  1572. 474 / $height
  1573. ];
  1574. if($ratio[0] < $ratio[1]){
  1575. $ratio = $ratio[0];
  1576. }else{
  1577. $ratio = $ratio[1];
  1578. }
  1579. return [
  1580. floor($width * $ratio),
  1581. floor($height * $ratio)
  1582. ];
  1583. }
  1584. }