ddg.php 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227
  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. // Parse additional data endpoints
  899. //
  900. //nrj('/js/spice/dictionary/definition/create', null, null, null, null, 'dictionary_definition');
  901. preg_match_all(
  902. '/nrj\(\s*\'([^\']+)\'/',
  903. $js,
  904. $nrj
  905. );
  906. if(isset($nrj[1])){
  907. foreach($nrj[1] as $potential_endpoint){
  908. //
  909. // Probe for wordnik definition
  910. //
  911. preg_match(
  912. '/\/js\/spice\/dictionary\/definition\/([^\/]+)/',
  913. $potential_endpoint,
  914. $word
  915. );
  916. if(isset($word[1])){
  917. $word = $word[1];
  918. // found wordnik definition & word
  919. try{
  920. $nik =
  921. $this->get(
  922. $proxy,
  923. "https://duckduckgo.com/js/spice/dictionary/definition/" . $word,
  924. [],
  925. ddg::req_xhr
  926. );
  927. }catch(Exception $e){
  928. // fail gracefully
  929. return $out;
  930. }
  931. // remove javascript
  932. $js_tmp =
  933. preg_split(
  934. '/ddg_spice_dictionary_definition\(\s*/',
  935. $nik,
  936. 2
  937. );
  938. if(count($js_tmp) > 1){
  939. $nik =
  940. json_decode(
  941. $this->fuckhtml
  942. ->extract_json(
  943. $js_tmp[1]
  944. ),
  945. true
  946. );
  947. }
  948. if($nik === null){
  949. return $out;
  950. }
  951. $answer_cat = [];
  952. $answer = [];
  953. foreach($nik as $snippet){
  954. if(!isset($snippet["partOfSpeech"])){ continue; }
  955. $push = [];
  956. // add text snippet
  957. if(isset($snippet["text"])){
  958. $push[] = [
  959. "type" => "text",
  960. "value" =>
  961. $this->fuckhtml
  962. ->getTextContent(
  963. $snippet["text"]
  964. )
  965. ];
  966. }
  967. // add example uses
  968. if(isset($snippet["exampleUses"])){
  969. foreach($snippet["exampleUses"] as $example){
  970. $push[] = [
  971. "type" => "quote",
  972. "value" => "\"" .
  973. $this->fuckhtml
  974. ->getTextContent(
  975. $example["text"]
  976. ) . "\""
  977. ];
  978. }
  979. }
  980. // add citations
  981. if(isset($snippet["citations"])){
  982. foreach($snippet["citations"] as $citation){
  983. if(!isset($citation["cite"])){ continue; }
  984. $text =
  985. $this->fuckhtml
  986. ->getTextContent(
  987. $citation["cite"]
  988. );
  989. if(isset($citation["source"])){
  990. $text .=
  991. " - " .
  992. $this->fuckhtml
  993. ->getTextContent(
  994. $citation["source"]
  995. );
  996. }
  997. $push[] = [
  998. "type" => "quote",
  999. "value" => $text
  1000. ];
  1001. }
  1002. }
  1003. // add related words
  1004. if(isset($snippet["relatedWords"])){
  1005. $relations = [];
  1006. foreach($snippet["relatedWords"] as $related){
  1007. $words = [];
  1008. foreach($related["words"] as $wrd){
  1009. $words[] =
  1010. $this->fuckhtml
  1011. ->getTextContent(
  1012. $wrd
  1013. );
  1014. }
  1015. if(
  1016. count($words) !== 0 &&
  1017. isset($related["relationshipType"])
  1018. ){
  1019. $relations[ucfirst($related["relationshipType"]) . "s"] =
  1020. implode(", ", $words);
  1021. }
  1022. }
  1023. foreach($relations as $relation_title => $relation_content){
  1024. $push[] = [
  1025. "type" => "quote",
  1026. "value" => $relation_title . ": " . $relation_content
  1027. ];
  1028. }
  1029. }
  1030. if(count($push) !== 0){
  1031. // push data to answer_cat
  1032. if(!isset($answer_cat[$snippet["partOfSpeech"]])){
  1033. $answer_cat[$snippet["partOfSpeech"]] = [];
  1034. }
  1035. $answer_cat[$snippet["partOfSpeech"]] =
  1036. array_merge(
  1037. $answer_cat[$snippet["partOfSpeech"]],
  1038. $push
  1039. );
  1040. }
  1041. }
  1042. foreach($answer_cat as $answer_title => $answer_content){
  1043. $i = 0;
  1044. $answer[] = [
  1045. "type" => "title",
  1046. "value" => $answer_title
  1047. ];
  1048. $old_type = $answer[count($answer) - 1]["type"];
  1049. foreach($answer_content as $ans){
  1050. if(
  1051. $ans["type"] == "text" &&
  1052. $old_type == "text"
  1053. ){
  1054. $i++;
  1055. $c = count($answer) - 1;
  1056. // append text to existing textfield
  1057. $answer[$c] = [
  1058. "type" => "text",
  1059. "value" => $answer[$c]["value"] . "\n" . $i . ". " . $ans["value"]
  1060. ];
  1061. }elseif($ans["type"] == "text"){
  1062. $i++;
  1063. $answer[] = [
  1064. "type" => "text",
  1065. "value" => $i . ". " . $ans["value"]
  1066. ];
  1067. }else{
  1068. // append normally
  1069. $answer[] = $ans;
  1070. }
  1071. $old_type = $ans["type"];
  1072. }
  1073. }
  1074. // yeah.. sometimes duckduckgo doesnt give us a definition back
  1075. if(count($answer) !== 0){
  1076. $out["answer"][] = [
  1077. "title" => ucfirst($word),
  1078. "description" => $answer,
  1079. "url" => "https://www.wordnik.com/words/" . $word,
  1080. "thumb" => null,
  1081. "table" => [],
  1082. "sublink" => []
  1083. ];
  1084. }
  1085. }
  1086. //
  1087. // Parse stackoverflow answer
  1088. //
  1089. if(
  1090. preg_match(
  1091. '/^\/a\.js.*src_id=stack_overflow/',
  1092. $potential_endpoint
  1093. )
  1094. ){
  1095. // found stackoverflow answer
  1096. try{
  1097. $json =
  1098. $this->get(
  1099. $proxy,
  1100. "https://duckduckgo.com" . $potential_endpoint,
  1101. [],
  1102. ddg::req_xhr
  1103. );
  1104. }catch(Exception $e){
  1105. // fail gracefully
  1106. return $out;
  1107. }
  1108. $json = explode("DDG.duckbar.add_array(", $json, 2);
  1109. if(count($json) === 2){
  1110. $json =
  1111. json_decode(
  1112. $this->fuckhtml
  1113. ->extract_json(
  1114. $json[1]
  1115. ),
  1116. true
  1117. );
  1118. if(
  1119. $json !== null &&
  1120. isset($json[0]["data"])
  1121. ){
  1122. $json = $json[0]["data"];
  1123. foreach($json as $answer){
  1124. if(isset($answer["Heading"])){
  1125. $title = $answer["Heading"];
  1126. }elseif(isset($answer["title"])){
  1127. $title = $answer["title"];
  1128. }else{
  1129. $title = null;
  1130. }
  1131. if(
  1132. $title !== null &&
  1133. isset($answer["Abstract"])
  1134. ){
  1135. // got some data
  1136. $description = [];
  1137. $html = &$answer["Abstract"];
  1138. // pre-process the html, remove useless elements
  1139. $html =
  1140. strip_tags(
  1141. $html,
  1142. [
  1143. "h1", "h2", "h3", "h4", "h5", "h6", "h7",
  1144. "pre", "code"
  1145. ]
  1146. );
  1147. $html =
  1148. preg_replace(
  1149. '/<(\/?)pre *[^>]*>\s*<\/?code *[^>]*>/i',
  1150. '<$1pre>',
  1151. $html
  1152. );
  1153. $this->fuckhtml->load($html);
  1154. $tags =
  1155. $this->fuckhtml
  1156. ->getElementsByTagName(
  1157. "*"
  1158. );
  1159. if(count($tags) === 0){
  1160. $description = [
  1161. "type" => "text",
  1162. "value" =>
  1163. trim(
  1164. $this->fuckhtml
  1165. ->getTextContent(
  1166. substr(
  1167. $html,
  1168. $start,
  1169. $tag["startPos"] - $start
  1170. ),
  1171. true,
  1172. false
  1173. )
  1174. )
  1175. ];
  1176. }else{
  1177. $start = 0;
  1178. $was_code_block = true;
  1179. foreach($tags as $tag){
  1180. $text =
  1181. $this->fuckhtml
  1182. ->getTextContent(
  1183. substr(
  1184. $html,
  1185. $start,
  1186. $tag["startPos"] - $start
  1187. ),
  1188. true,
  1189. false
  1190. );
  1191. if($was_code_block){
  1192. $text = ltrim($text);
  1193. $was_code_block = false;
  1194. }
  1195. $description[] = [
  1196. "type" => "text",
  1197. "value" => $text
  1198. ];
  1199. switch($tag["tagName"]){
  1200. case "pre":
  1201. $append = "code";
  1202. $was_code_block = true;
  1203. $c = count($description) - 1;
  1204. $description[$c]["value"] =
  1205. rtrim($description[$c]["value"]);
  1206. break;
  1207. case "code":
  1208. $append = "inline_code";
  1209. $c = count($description) - 1;
  1210. $description[$c]["value"] =
  1211. rtrim($description[$c]["value"]) . " ";
  1212. break;
  1213. case "h1":
  1214. case "h2":
  1215. case "h3":
  1216. case "h4":
  1217. case "h5":
  1218. case "h6":
  1219. case "h7":
  1220. $append = "title";
  1221. $c = count($description) - 1;
  1222. $description[$c]["value"] =
  1223. rtrim($description[$c]["value"]);
  1224. break;
  1225. }
  1226. $description[] = [
  1227. "type" => $append,
  1228. "value" =>
  1229. trim(
  1230. $this->fuckhtml
  1231. ->getTextContent(
  1232. $tag,
  1233. true,
  1234. false
  1235. )
  1236. )
  1237. ];
  1238. $start = $tag["endPos"];
  1239. }
  1240. // shit out remainder
  1241. $description[] = [
  1242. "type" => "text",
  1243. "value" =>
  1244. trim(
  1245. $this->fuckhtml
  1246. ->getTextContent(
  1247. substr(
  1248. $html,
  1249. $start
  1250. ),
  1251. true,
  1252. false
  1253. )
  1254. )
  1255. ];
  1256. }
  1257. $out["answer"][] = [
  1258. "title" => $title,
  1259. "description" => $description,
  1260. "url" => $answer["AbstractURL"],
  1261. "thumb" => null,
  1262. "table" => [],
  1263. "sublink" => []
  1264. ];
  1265. }
  1266. }
  1267. }
  1268. }
  1269. }
  1270. }
  1271. }
  1272. return $out;
  1273. }
  1274. public function image($get){
  1275. if($get["npt"]){
  1276. [$js_link, $proxy] = $this->backend->get($get["npt"], "images");
  1277. }else{
  1278. if(strlen($get["s"]) === 0){
  1279. throw new Exception("Search term is empty!");
  1280. }
  1281. $proxy = $this->backend->get_ip();
  1282. $filters = [];
  1283. if($get["date"] != "any"){ $filters[] = "time:{$get["date"]}"; }
  1284. if($get["size"] != "any"){ $filters[] = "size:{$get["size"]}"; }
  1285. if($get["color"] != "any"){ $filters[] = "color:{$get["color"]}"; }
  1286. if($get["type"] != "any"){ $filters[] = "type:{$get["type"]}"; }
  1287. if($get["layout"] != "any"){ $filters[] = "layout:{$get["layout"]}"; }
  1288. if($get["license"] != "any"){ $filters[] = "license:{$get["license"]}"; }
  1289. $filters = implode(",", $filters);
  1290. $get_filters = [
  1291. "q" => $get["s"],
  1292. "iax" => "images",
  1293. "ia" => "images"
  1294. ];
  1295. if($filters != ""){
  1296. $get_filters["iaf"] = $filters;
  1297. }
  1298. $nsfw = $get["nsfw"] == "yes" ? "-1" : "1";
  1299. $get_filters["kp"] = $nsfw;
  1300. try{
  1301. $html = $this->get(
  1302. $proxy,
  1303. "https://duckduckgo.com",
  1304. $get_filters,
  1305. ddg::req_web
  1306. );
  1307. }catch(Exception $err){
  1308. throw new Exception("Failed to fetch search page");
  1309. }
  1310. preg_match(
  1311. '/vqd="([0-9-]+)"/',
  1312. $html,
  1313. $vqd
  1314. );
  1315. if(!isset($vqd[1])){
  1316. throw new Exception("Failed to grep VQD token");
  1317. }
  1318. $js_link =
  1319. "i.js?" .
  1320. http_build_query([
  1321. "l" => $get["country"],
  1322. "o" => "json",
  1323. "q" => $get["s"],
  1324. "vqd" => $vqd[1],
  1325. "f" => $filters,
  1326. "p" => $nsfw
  1327. ]);
  1328. }
  1329. try{
  1330. $json =
  1331. $this->get(
  1332. $proxy,
  1333. "https://duckduckgo.com/" . $js_link,
  1334. [],
  1335. ddg::req_xhr
  1336. );
  1337. }catch(Exception $error){
  1338. throw new Exception("Failed to get i.js");
  1339. }
  1340. $json = json_decode($json, true);
  1341. if($json === null){
  1342. throw new Exception("Failed to decode JSON");
  1343. }
  1344. $out = [
  1345. "status" => "ok",
  1346. "npt" => null,
  1347. "image" => []
  1348. ];
  1349. if(!isset($json["results"])){
  1350. return $out;
  1351. }
  1352. // get npt
  1353. if(
  1354. isset($json["next"]) &&
  1355. $json["next"] !== null
  1356. ){
  1357. $vqd = null;
  1358. if(isset($vqd[1])){
  1359. $vqd = $vqd[1];
  1360. }else{
  1361. $vqd = array_values($json["vqd"]);
  1362. if(count($vqd) > 0){
  1363. $vqd = $vqd[0];
  1364. }
  1365. }
  1366. if($vqd !== null){
  1367. $out["npt"] =
  1368. $this->backend->store(
  1369. $json["next"] . "&vqd=" . $vqd,
  1370. "images",
  1371. $proxy
  1372. );
  1373. }
  1374. }
  1375. // get images
  1376. foreach($json["results"] as $image){
  1377. $ratio =
  1378. $this->bingratio(
  1379. (int)$image["width"],
  1380. (int)$image["height"]
  1381. );
  1382. $out["image"][] = [
  1383. "title" => $this->titledots($image["title"]),
  1384. "source" => [
  1385. [
  1386. "url" => $image["image"],
  1387. "width" => (int)$image["width"],
  1388. "height" => (int)$image["height"]
  1389. ],
  1390. [
  1391. "url" => $this->bingimg($image["thumbnail"]),
  1392. "width" => $ratio[0],
  1393. "height" => $ratio[1]
  1394. ]
  1395. ],
  1396. "url" => $this->unshiturl($image["url"])
  1397. ];
  1398. }
  1399. return $out;
  1400. }
  1401. public function video($get){
  1402. if($get["npt"]){
  1403. [$js_link, $proxy] = $this->backend->get($get["npt"], "videos");
  1404. }else{
  1405. if(strlen($get["s"]) === 0){
  1406. throw new Exception("Search term is empty!");
  1407. }
  1408. $proxy = $this->backend->get_ip();
  1409. $get_filters = [
  1410. "q" => $get["s"],
  1411. "iax" => "videos",
  1412. "ia" => "videos"
  1413. ];
  1414. switch($get["nsfw"]){
  1415. case "yes": $nsfw = "-2"; break;
  1416. case "maybe": $nsfw = "-1"; break;
  1417. case "no": $nsfw = "1"; break;
  1418. }
  1419. $filters = [];
  1420. if($get["date"] != "any"){ $filters[] = "publishedAfter:{$date}"; }
  1421. if($get["resolution"] != "any"){ $filters[] = "videoDefinition:{$resolution}"; }
  1422. if($get["duration"] != "any"){ $filters[] = "videoDuration:{$duration}"; }
  1423. if($get["license"] != "any"){ $filters[] = "videoLicense:{$license}"; }
  1424. $filters = implode(",", $filters);
  1425. if($filters != ""){
  1426. $get_filters["iaf"] = $filters;
  1427. }
  1428. try{
  1429. $html =
  1430. $this->get(
  1431. $proxy,
  1432. "https://duckduckgo.com/",
  1433. $get_filters,
  1434. ddg::req_web
  1435. );
  1436. }catch(Exception $error){
  1437. throw new Exception("Failed to fetch search page");
  1438. }
  1439. preg_match(
  1440. '/vqd="([0-9-]+)"/',
  1441. $html,
  1442. $vqd
  1443. );
  1444. if(!isset($vqd[1])){
  1445. throw new Exception("Failed to grep VQD token");
  1446. }
  1447. $js_link =
  1448. "v.js?" .
  1449. http_build_query([
  1450. "l" => $get["country"],
  1451. "o" => "json",
  1452. "sr" => "1",
  1453. "q" => $get["s"],
  1454. "vqd" => $vqd[1],
  1455. "f" => $filters,
  1456. "p" => $nsfw
  1457. ]);
  1458. }
  1459. try{
  1460. $json =
  1461. $this->get(
  1462. $proxy,
  1463. "https://duckduckgo.com/" . $js_link,
  1464. [],
  1465. ddg::req_xhr
  1466. );
  1467. }catch(Exception $error){
  1468. throw new Exception("Failed to fetch JSON");
  1469. }
  1470. $json = json_decode($json, true);
  1471. if($json === null){
  1472. throw new Exception("Failed to decode JSON");
  1473. }
  1474. $out = [
  1475. "status" => "ok",
  1476. "npt" => null,
  1477. "video" => [],
  1478. "author" => [],
  1479. "livestream" => [],
  1480. "playlist" => [],
  1481. "reel" => []
  1482. ];
  1483. if(!isset($json["results"])){
  1484. return $out;
  1485. }
  1486. // get NPT
  1487. if(
  1488. isset($json["next"]) &&
  1489. $json["next"] !== null
  1490. ){
  1491. $out["npt"] =
  1492. $this->backend->store(
  1493. $json["next"],
  1494. "videos",
  1495. $proxy
  1496. );
  1497. }
  1498. foreach($json["results"] as $video){
  1499. $thumb = [
  1500. "ratio" => null,
  1501. "url" => null
  1502. ];
  1503. foreach(["large", "medium", "small"] as $contender){
  1504. if(isset($video["images"][$contender])){
  1505. $thumb = [
  1506. "ratio" => "16:9",
  1507. "url" => $this->bingimg($video["images"][$contender])
  1508. ];
  1509. break;
  1510. }
  1511. }
  1512. $out["video"][] = [
  1513. "title" => $this->titledots($video["title"]),
  1514. "description" => $this->titledots($video["description"]),
  1515. "author" => [
  1516. "name" =>
  1517. (
  1518. isset($video["uploader"]) &&
  1519. $video["uploader"] != ""
  1520. ) ?
  1521. $video["uploader"] : null,
  1522. "url" => null,
  1523. "avatar" => null
  1524. ],
  1525. "date" =>
  1526. (
  1527. isset($video["published"]) &&
  1528. $video["published"] != ""
  1529. ) ?
  1530. strtotime($video["published"]) : null,
  1531. "duration" =>
  1532. (
  1533. isset($video["duration"]) &&
  1534. $video["duration"] != ""
  1535. ) ?
  1536. $this->hms2int($video["duration"]) : null,
  1537. "views" =>
  1538. isset($video["statistics"]["viewCount"]) ?
  1539. (int)$video["statistics"]["viewCount"] : null,
  1540. "thumb" => $thumb,
  1541. "url" => $this->unshiturl($video["content"])
  1542. ];
  1543. }
  1544. return $out;
  1545. }
  1546. public function news($get){
  1547. if($get["npt"]){
  1548. [$js_link, $proxy] = $this->backend->get($get["npt"], "news");
  1549. }else{
  1550. if(strlen($get["s"]) === 0){
  1551. throw new Exception("Search term is empty!");
  1552. }
  1553. $proxy = $this->backend->get_ip();
  1554. $get_filters = [
  1555. "q" => $get["s"],
  1556. "iar" => "news",
  1557. "ia" => "news"
  1558. ];
  1559. if($get["date"] != "any"){
  1560. $date = $get["date"];
  1561. $get_filters["df"] = $date;
  1562. }else{
  1563. $date = "";
  1564. }
  1565. switch($get["nsfw"]){
  1566. case "yes": $get_filters["kp"] = "-2"; break;
  1567. case "maybe": $get_filters["kp"] = "-1"; break;
  1568. case "no": $get_filters["kp"] = "1"; break;
  1569. }
  1570. try{
  1571. $html =
  1572. $this->get(
  1573. $proxy,
  1574. "https://duckduckgo.com/",
  1575. $get_filters,
  1576. ddg::req_web
  1577. );
  1578. }catch(Exception $error){
  1579. throw new Exception("Failed to fetch search page");
  1580. }
  1581. preg_match(
  1582. '/vqd="([0-9-]+)"/',
  1583. $html,
  1584. $vqd
  1585. );
  1586. if(!isset($vqd[1])){
  1587. throw new Exception("Failed to grep VQD token");
  1588. }
  1589. $js_link =
  1590. "news.js?" .
  1591. http_build_query([
  1592. "l" => $get["country"],
  1593. "o" => "json",
  1594. "noamp" => "1",
  1595. "m" => "30",
  1596. "q" => $get["s"],
  1597. "vqd" => $vqd[1],
  1598. "p" => $get_filters["kp"],
  1599. "df" => $date,
  1600. "u" => "bing"
  1601. ]);
  1602. }
  1603. try{
  1604. $json =
  1605. $this->get(
  1606. $proxy,
  1607. "https://duckduckgo.com/" . $js_link,
  1608. [],
  1609. ddg::req_xhr
  1610. );
  1611. }catch(Exception $error){
  1612. throw new Exception("Failed to fetch JSON");
  1613. }
  1614. $json = json_decode($json, true);
  1615. if($json === null){
  1616. throw new Exception("Failed to decode JSON");
  1617. }
  1618. $out = [
  1619. "status" => "ok",
  1620. "npt" => null,
  1621. "news" => []
  1622. ];
  1623. if(!isset($json["results"])){
  1624. return $out;
  1625. }
  1626. // get NPT
  1627. if(
  1628. isset($json["next"]) &&
  1629. $json["next"] !== null
  1630. ){
  1631. $out["npt"] =
  1632. $this->backend->store(
  1633. $json["next"],
  1634. "news",
  1635. $proxy
  1636. );
  1637. }
  1638. foreach($json["results"] as $news){
  1639. if(
  1640. isset($news["image"]) &&
  1641. $news["image"] != ""
  1642. ){
  1643. $thumb = [
  1644. "ratio" => "16:9",
  1645. "url" => $news["image"]
  1646. ];
  1647. }else{
  1648. $thumb = [
  1649. "ratio" => null,
  1650. "url" => null
  1651. ];
  1652. }
  1653. $out["news"][] = [
  1654. "title" => $news["title"],
  1655. "author" =>
  1656. (
  1657. isset($news["source"]) &&
  1658. $news["source"] != ""
  1659. ) ?
  1660. $news["source"] : null,
  1661. "description" =>
  1662. (
  1663. isset($news["excerpt"]) &&
  1664. $news["excerpt"] != ""
  1665. ) ?
  1666. $this->fuckhtml
  1667. ->getTextContent(
  1668. $news["excerpt"]
  1669. ) : null,
  1670. "date" =>
  1671. isset($news["date"]) ?
  1672. (int)$news["date"] : null,
  1673. "thumb" => $thumb,
  1674. "url" => $this->unshiturl($news["url"])
  1675. ];
  1676. }
  1677. return $out;
  1678. }
  1679. private function titledots($title){
  1680. $substr = substr($title, -3);
  1681. if(
  1682. $substr == "..." ||
  1683. $substr == "…"
  1684. ){
  1685. return trim(substr($title, 0, -3));
  1686. }
  1687. return trim($title);
  1688. }
  1689. private function hms2int($time){
  1690. $parts = explode(":", $time, 3);
  1691. $time = 0;
  1692. if(count($parts) === 3){
  1693. // hours
  1694. $time = $time + ((int)$parts[0] * 3600);
  1695. array_shift($parts);
  1696. }
  1697. if(count($parts) === 2){
  1698. // minutes
  1699. $time = $time + ((int)$parts[0] * 60);
  1700. array_shift($parts);
  1701. }
  1702. // seconds
  1703. $time = $time + (int)$parts[0];
  1704. return $time;
  1705. }
  1706. private function unshiturl($url){
  1707. // check for domains w/out first short subdomain (ex: www.)
  1708. $domain = parse_url($url, PHP_URL_HOST);
  1709. $subdomain = preg_replace(
  1710. '/^[A-z0-9]{1,3}\./',
  1711. "",
  1712. $domain
  1713. );
  1714. switch($subdomain){
  1715. case "ebay.com.au":
  1716. case "ebay.at":
  1717. case "ebay.ca":
  1718. case "ebay.fr":
  1719. case "ebay.de":
  1720. case "ebay.com.hk":
  1721. case "ebay.ie":
  1722. case "ebay.it":
  1723. case "ebay.com.my":
  1724. case "ebay.nl":
  1725. case "ebay.ph":
  1726. case "ebay.pl":
  1727. case "ebay.com.sg":
  1728. case "ebay.es":
  1729. case "ebay.ch":
  1730. case "ebay.co.uk":
  1731. case "cafr.ebay.ca":
  1732. case "ebay.com":
  1733. case "community.ebay.com":
  1734. case "pages.ebay.com":
  1735. // remove ebay tracking elements
  1736. $old_params = parse_url($url, PHP_URL_QUERY);
  1737. parse_str($old_params, $params);
  1738. if(isset($params["mkevt"])){ unset($params["mkevt"]); }
  1739. if(isset($params["mkcid"])){ unset($params["mkcid"]); }
  1740. if(isset($params["mkrid"])){ unset($params["mkrid"]); }
  1741. if(isset($params["campid"])){ unset($params["campid"]); }
  1742. if(isset($params["customid"])){ unset($params["customid"]); }
  1743. if(isset($params["toolid"])){ unset($params["toolid"]); }
  1744. if(isset($params["_sop"])){ unset($params["_sop"]); }
  1745. if(isset($params["_dcat"])){ unset($params["_dcat"]); }
  1746. if(isset($params["epid"])){ unset($params["epid"]); }
  1747. if(isset($params["epid"])){ unset($params["oid"]); }
  1748. $params = http_build_query($params);
  1749. if(strlen($params) === 0){
  1750. $replace = "\?";
  1751. }else{
  1752. $replace = "";
  1753. }
  1754. $url = preg_replace(
  1755. "/" . $replace . preg_quote($old_params, "/") . "$/",
  1756. $params,
  1757. $url
  1758. );
  1759. break;
  1760. }
  1761. return $url;
  1762. }
  1763. private function bingimg($url){
  1764. $image = parse_url($url);
  1765. $id = null;
  1766. if(isset($image["query"])){
  1767. parse_str($image["query"], $str);
  1768. if(isset($str["id"])){
  1769. $id = $str["id"];
  1770. }
  1771. }
  1772. if($id === null){
  1773. $id = explode("/th/id/", $image["path"], 2);
  1774. if(count($id) !== 2){
  1775. // malformed
  1776. return $url;
  1777. }
  1778. $id = $id[1];
  1779. }
  1780. return "https://" . $image["host"] . "/th?id=" . rawurlencode($id);
  1781. }
  1782. private function bingratio($width, $height){
  1783. $ratio = [
  1784. 474 / $width,
  1785. 474 / $height
  1786. ];
  1787. if($ratio[0] < $ratio[1]){
  1788. $ratio = $ratio[0];
  1789. }else{
  1790. $ratio = $ratio[1];
  1791. }
  1792. return [
  1793. floor($width * $ratio),
  1794. floor($height * $ratio)
  1795. ];
  1796. }
  1797. }