ddg.php 39 KB

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