ddg.php 39 KB

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