ddg.php 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972
  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. $parse = parse_url($url);
  1570. parse_str($parse["query"], $parts);
  1571. return "https://" . $parse["host"] . "/th?id=" . urlencode($parts["id"]);
  1572. }
  1573. private function bingratio($width, $height){
  1574. $ratio = [
  1575. 474 / $width,
  1576. 474 / $height
  1577. ];
  1578. if($ratio[0] < $ratio[1]){
  1579. $ratio = $ratio[0];
  1580. }else{
  1581. $ratio = $ratio[1];
  1582. }
  1583. return [
  1584. floor($width * $ratio),
  1585. floor($height * $ratio)
  1586. ];
  1587. }
  1588. }