ddg.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995
  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. $id = explode("/th/id/", $image["path"], 2);
  1579. if(count($id) !== 2){
  1580. // malformed
  1581. return $url;
  1582. }
  1583. $id = $id[1];
  1584. }
  1585. return "https://" . $image["host"] . "/th?id=" . rawurlencode($id);
  1586. }
  1587. private function bingratio($width, $height){
  1588. $ratio = [
  1589. 474 / $width,
  1590. 474 / $height
  1591. ];
  1592. if($ratio[0] < $ratio[1]){
  1593. $ratio = $ratio[0];
  1594. }else{
  1595. $ratio = $ratio[1];
  1596. }
  1597. return [
  1598. floor($width * $ratio),
  1599. floor($height * $ratio)
  1600. ];
  1601. }
  1602. }