ddg.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383
  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. //$js = file_get_contents("scraper/fuck.js");
  433. //echo htmlspecialchars($js);
  434. $js_tmp =
  435. preg_split(
  436. '/DDG\.pageLayout\.load\(\s*\'d\'\s*,\s*/',
  437. $js,
  438. 2
  439. );
  440. if(count($js_tmp) <= 1){
  441. //
  442. // Detect javascript challenge
  443. //
  444. if(
  445. preg_match(
  446. '/DDG\.deep\.initialize\(\'([^\']+)\'\ *\+ *jsa/i',
  447. $js,
  448. $challenge_url
  449. )
  450. ){
  451. throw new Exception("DuckDuckGo returned a JSA challenge");
  452. // get JSA initial token
  453. if(
  454. !preg_match(
  455. '/let jsa *= *([0-9]+)/',
  456. $js,
  457. $jsa
  458. )
  459. ){
  460. $jsa = 0;
  461. }else{
  462. $jsa = (int)$jsa[1];
  463. }
  464. // get function bodies
  465. preg_match_all(
  466. '/let *([A-Za-z0-9]+) *= *function\(.*\) *{(.*)};/sU',
  467. $js,
  468. $functions
  469. );
  470. $parsed_functions = [];
  471. for($i=0; $i<count($functions[0]); $i++){
  472. $functions[2][$i] = trim($functions[2][$i]);
  473. if(
  474. preg_match(
  475. '/return num *\* *([0-9]+)/i',
  476. $functions[2][$i],
  477. $num
  478. )
  479. ){
  480. $parsed_functions[$functions[1][$i]] = [
  481. "type" => "multiplication",
  482. "num" => (int)$num[1]
  483. ];
  484. continue;
  485. }
  486. if(
  487. preg_match(
  488. '/innerHTML *= *`([^`]+)`/i',
  489. $functions[2][$i],
  490. $challenge
  491. )
  492. ){
  493. $challenge[1] =
  494. preg_replace(
  495. '/<\/(br)>/',
  496. '<$1>',
  497. $challenge[1]
  498. );
  499. $parsed_functions[$functions[1][$i]] = [
  500. "type" => "challenge",
  501. "text" => $challenge[1]
  502. ];
  503. }
  504. }
  505. // get function call order
  506. preg_match_all(
  507. '/jsa *= *([A-Za-z0-9]+)\(jsa\)/i',
  508. $js,
  509. $call_order
  510. );
  511. foreach($call_order[1] as $order){
  512. if(!isset($parsed_functions[$order])){
  513. throw new Exception("JS challenge solve failure: DuckDuckGo called an unknown function");
  514. }
  515. if($parsed_functions[$order]["type"] == "multiplication"){
  516. $jsa = $jsa * $parsed_functions[$order]["num"];
  517. continue;
  518. }
  519. if($parsed_functions[$order]["type"] == "challenge"){
  520. // @TODO get parsed length
  521. //$parsed_functions[$order]["text"]
  522. $jsa = $jsa + strlen($parsed_functions[$order]["text"]);
  523. }
  524. }
  525. try{
  526. $js = $this->get(
  527. $proxy,
  528. "https://links.duckduckgo.com" . $challenge_url[1] . $jsa,
  529. [],
  530. ddg::req_xhr
  531. );
  532. }catch(Exception $error){
  533. throw new Exception("Failed to get challenged d.js");
  534. }
  535. }
  536. //
  537. // Detect JavaScript anomaly failure thingy
  538. //
  539. if(
  540. preg_match(
  541. '/DDG.deep.anomalyDetectionBlock\({/',
  542. $js
  543. )
  544. ){
  545. throw new Exception("DuckDuckGo detected an anomaly in the Javascript challenge response");
  546. }
  547. throw new Exception("Failed to grep pageLayout(d)");
  548. }
  549. $json =
  550. json_decode(
  551. $this->fuckhtml
  552. ->extract_json(
  553. $js_tmp[1]
  554. ),
  555. true
  556. );
  557. if($json === null){
  558. throw new Exception("Failed to decode JSON");
  559. }
  560. //
  561. // Get search results + NPT token
  562. //
  563. foreach($json as $item){
  564. if(isset($item["c"])){
  565. if(
  566. !isset($item["s"]) &&
  567. isset($item["t"]) &&
  568. (
  569. $item["t"] == "DEEP_ERROR_NO_RESULTS" ||
  570. $item["t"] == "DEEP_SIMPLE_NO_RESULTS"
  571. )
  572. ){
  573. return $out;
  574. }
  575. $table = [];
  576. // get youtube video information
  577. if(isset($item["video"]["thumbnail_url_template"])){
  578. $thumb =
  579. [
  580. "ratio" => "16:9",
  581. "url" => $this->bingimg($item["video"]["thumbnail_url_template"])
  582. ];
  583. }else{
  584. $thumb =
  585. [
  586. "ratio" => null,
  587. "url" => null
  588. ];
  589. }
  590. // get table items
  591. if(isset($item["rf"])){
  592. foreach($item["rf"] as $hint){
  593. if(
  594. !isset($hint["label"]["text"]) ||
  595. !isset($hint["items"][0]["text"])
  596. ){
  597. continue;
  598. }
  599. $text = [];
  600. foreach($hint["items"] as $text_part){
  601. $text[] = $text_part["text"];
  602. }
  603. $text = implode(", ", $text);
  604. if(is_numeric($text)){
  605. $text = number_format((string)$text);
  606. }
  607. $table[$hint["label"]["text"]] = $text;
  608. }
  609. }
  610. // get ratings
  611. if(isset($item["ar"])){
  612. foreach($item["ar"] as $rating){
  613. if(
  614. isset($rating["aggregateRating"]["bestRating"]) &&
  615. isset($rating["aggregateRating"]["ratingValue"])
  616. ){
  617. $text = $rating["aggregateRating"]["ratingValue"] . "/" . $rating["aggregateRating"]["bestRating"];
  618. if(isset($rating["aggregateRating"]["reviewCount"])){
  619. $text .= " (" . number_format($rating["aggregateRating"]["reviewCount"]) . " votes)";
  620. }
  621. $table["Rating"] = $text;
  622. }
  623. }
  624. }
  625. // get sublinks
  626. $sublinks = [];
  627. if(isset($item["l"])){
  628. foreach($item["l"] as $sublink){
  629. $sublinks[] = [
  630. "title" => $this->titledots($sublink["text"]),
  631. "description" => $this->titledots($sublink["snippet"]),
  632. "url" => $sublink["targetUrl"],
  633. "date" => null
  634. ];
  635. }
  636. }
  637. $title =
  638. $this->titledots(
  639. $this->fuckhtml
  640. ->getTextContent(
  641. $item["t"]
  642. )
  643. );
  644. if(
  645. $title == "EOF" &&
  646. strpos(
  647. $item["c"],
  648. "google"
  649. )
  650. ){
  651. continue;
  652. }
  653. // parse search result
  654. $out["web"][] = [
  655. "title" =>
  656. $this->titledots(
  657. $this->fuckhtml
  658. ->getTextContent(
  659. $item["t"]
  660. )
  661. ),
  662. "description" =>
  663. isset($item["a"]) ?
  664. $this->titledots(
  665. $this->fuckhtml
  666. ->getTextContent(
  667. $item["a"]
  668. )
  669. ) : null,
  670. "url" => $this->unshiturl($item["c"]),
  671. "date" =>
  672. isset($item["e"]) ?
  673. strtotime($item["e"]) : null,
  674. "type" => "web",
  675. "thumb" => $thumb,
  676. "sublink" => $sublinks,
  677. "table" => $table
  678. ];
  679. continue;
  680. }
  681. if(isset($item["n"])){
  682. // get NPT
  683. $out["npt"] =
  684. $this->backend->store(
  685. $item["n"],
  686. "web",
  687. $proxy
  688. );
  689. continue;
  690. }
  691. }
  692. //
  693. // Get spelling
  694. //
  695. $js_tmp =
  696. preg_split(
  697. '/DDG\.page\.showMessage\(\s*\'spelling\'\s*,\s*/',
  698. $js,
  699. 2
  700. );
  701. if(count($js_tmp) > 1){
  702. $json =
  703. json_decode(
  704. $this->fuckhtml
  705. ->extract_json(
  706. $js_tmp[1]
  707. ),
  708. true
  709. );
  710. if($json !== null){
  711. // parse spelling
  712. // qc=2: including
  713. switch((int)$json["qc"]){
  714. case 2:
  715. $type = "including";
  716. break;
  717. default:
  718. $type = "not_many";
  719. break;
  720. }
  721. $out["spelling"] = [
  722. "type" => $type,
  723. "using" =>
  724. $this->fuckhtml
  725. ->getTextContent(
  726. $json["suggestion"]
  727. ),
  728. "correction" => html_entity_decode($json["recourseText"])
  729. ];
  730. }
  731. }
  732. //
  733. // Get images
  734. //
  735. $js_tmp =
  736. preg_split(
  737. '/DDG\.duckbar\.load\(\s*\'images\'\s*,\s*/',
  738. $js,
  739. 2
  740. );
  741. if(count($js_tmp) > 1){
  742. $json =
  743. json_decode(
  744. $this->fuckhtml
  745. ->extract_json(
  746. $js_tmp[1]
  747. ),
  748. true
  749. );
  750. if($json !== null){
  751. foreach($json["results"] as $image){
  752. $ratio = $this->bingratio((int)$image["width"], (int)$image["height"]);
  753. $out["image"][] = [
  754. "title" => $image["title"],
  755. "source" => [
  756. [
  757. "url" => $image["image"],
  758. "width" => (int)$image["width"],
  759. "height" => (int)$image["height"]
  760. ],
  761. [
  762. "url" => $this->bingimg($image["thumbnail"]),
  763. "width" => $ratio[0],
  764. "height" => $ratio[1]
  765. ]
  766. ],
  767. "url" => $this->unshiturl($image["url"])
  768. ];
  769. }
  770. }
  771. }
  772. //
  773. // Get videos
  774. //
  775. $js_tmp =
  776. preg_split(
  777. '/DDG\.duckbar\.load\(\s*\'videos\'\s*,\s*/',
  778. $js,
  779. 2
  780. );
  781. if(count($js_tmp) > 1){
  782. $json =
  783. json_decode(
  784. $this->fuckhtml
  785. ->extract_json(
  786. $js_tmp[1]
  787. ),
  788. true
  789. );
  790. if($json !== null){
  791. foreach($json["results"] as $video){
  792. $thumb = [
  793. "ratio" => null,
  794. "url" => null
  795. ];
  796. foreach(["large", "medium", "small"] as $contender){
  797. if(isset($video["images"][$contender])){
  798. $thumb = [
  799. "ratio" => "16:9",
  800. "url" => $this->bingimg($video["images"][$contender])
  801. ];
  802. break;
  803. }
  804. }
  805. $out["video"][] = [
  806. "title" => $this->titledots($video["title"]),
  807. "description" =>
  808. $video["description"] != "" ?
  809. $this->titledots($video["description"]) : null,
  810. "date" =>
  811. isset($video["published"]) ?
  812. strtotime($video["published"]) : null,
  813. "duration" =>
  814. $video["duration"] != "" ?
  815. $this->hms2int($video["duration"]) : null,
  816. "views" =>
  817. isset($video["statistics"]["viewCount"]) ?
  818. (int)$video["statistics"]["viewCount"] : null,
  819. "thumb" => $thumb,
  820. "url" => $this->unshiturl($video["content"])
  821. ];
  822. }
  823. }
  824. }
  825. //
  826. // Get news
  827. //
  828. $js_tmp =
  829. preg_split(
  830. '/DDG\.duckbar\.load\(\s*\'news\'\s*,\s*/',
  831. $js,
  832. 2
  833. );
  834. if(count($js_tmp) > 1){
  835. $json =
  836. json_decode(
  837. $this->fuckhtml
  838. ->extract_json(
  839. $js_tmp[1]
  840. ),
  841. true
  842. );
  843. if($json !== null){
  844. foreach($json["results"] as $news){
  845. if(isset($news["image"])){
  846. $thumb = [
  847. "ratio" => "16:9",
  848. "url" => $news["image"]
  849. ];
  850. }else{
  851. $thumb = [
  852. "ratio" => null,
  853. "url" => null
  854. ];
  855. }
  856. $out["news"][] = [
  857. "title" => $news["title"],
  858. "description" =>
  859. $this->fuckhtml
  860. ->getTextContent(
  861. $news["excerpt"]
  862. ),
  863. "date" => (int)$news["date"],
  864. "thumb" => $thumb,
  865. "url" => $news["url"]
  866. ];
  867. }
  868. }
  869. }
  870. //
  871. // Get related searches
  872. //
  873. $js_tmp =
  874. preg_split(
  875. '/DDG\.duckbar\.loadModule\(\s*\'related_searches\'\s*,\s*/',
  876. $js,
  877. 2
  878. );
  879. if(count($js_tmp) > 1){
  880. $json =
  881. json_decode(
  882. $this->fuckhtml
  883. ->extract_json(
  884. $js_tmp[1]
  885. ),
  886. true
  887. );
  888. if($json !== null){
  889. foreach($json["results"] as $related){
  890. $out["related"][] = $related["text"];
  891. }
  892. }
  893. }
  894. //
  895. // Get instant answers
  896. //
  897. $js_tmp =
  898. preg_split(
  899. '/DDG\.duckbar\.add\(\s*/',
  900. $html . $js,
  901. 2
  902. );
  903. if(count($js_tmp) > 1){
  904. $json =
  905. json_decode(
  906. $this->fuckhtml
  907. ->extract_json(
  908. $js_tmp[1]
  909. ),
  910. true
  911. );
  912. if($json !== null){
  913. $json = $json["data"];
  914. $table = [];
  915. $sublinks = [];
  916. $description = [];
  917. // get official website
  918. if(
  919. isset($json["OfficialWebsite"]) &&
  920. $json["OfficialWebsite"] !== null
  921. ){
  922. $sublinks["Website"] = $json["OfficialWebsite"];
  923. }
  924. // get sublinks & table elements
  925. if(isset($json["Infobox"]["content"])){
  926. foreach($json["Infobox"]["content"] as $info){
  927. if($info["data_type"] == "string"){
  928. // add table element
  929. $table[$info["label"]] = $info["value"];
  930. continue;
  931. }
  932. if($info["data_type"] == "wd_description"){
  933. $description[] = [
  934. "type" => "quote",
  935. "value" => $info["value"]
  936. ];
  937. continue;
  938. }
  939. // add sublink
  940. switch($info["data_type"]){
  941. case "official_site":
  942. case "official_website":
  943. $type = "Website";
  944. break;
  945. case "wikipedia": $type = "Wikipedia"; break;
  946. case "itunes": $type = "iTunes"; break;
  947. case "amazon": $type = "Amazon"; break;
  948. case "imdb_title_id":
  949. case "imdb_id":
  950. case "imdb_name_id":
  951. $type = "IMDb";
  952. $delim = substr($info["value"], 0, 2);
  953. if($delim == "nm"){
  954. $prefix = "https://www.imdb.com/name/";
  955. }elseif($delim == "tt"){
  956. $prefix = "https://www.imdb.com/title/";
  957. }elseif($delim == "co"){
  958. $prefix = "https://www.imdb.com/search/title/?companies=";
  959. }else{
  960. $prefix = "https://www.imdb.com/title/";
  961. }
  962. break;
  963. case "imdb_name_id": $prefix = "https://www.imdb.com/name/"; $type = "IMDb"; break;
  964. case "twitter_profile": $prefix = "https://twitter.com/"; $type = "Twitter"; break;
  965. case "instagram_profile": $prefix = "https://instagram.com/"; $type = "Instagram"; break;
  966. case "facebook_profile": $prefix = "https://facebook.com/"; $type = "Facebook"; break;
  967. case "spotify_artist_id": $prefix = "https://open.spotify.com/artist/"; $type = "Spotify"; break;
  968. case "itunes_artist_id": $prefix = "https://music.apple.com/us/artist/"; $type = "iTunes"; break;
  969. case "rotten_tomatoes": $prefix = "https://rottentomatoes.com/"; $type = "Rotten Tomatoes"; break;
  970. case "youtube_channel": $prefix = "https://youtube.com/channel/"; $type = "YouTube"; break;
  971. case "soundcloud_id": $prefix = "https://soundcloud.com/"; $type = "SoundCloud"; break;
  972. default:
  973. $prefix = null;
  974. $type = false;
  975. }
  976. if($type !== false){
  977. if($prefix === null){
  978. $sublinks[$type] = $info["value"];
  979. }else{
  980. $sublinks[$type] = $prefix . $info["value"];
  981. }
  982. }
  983. }
  984. }
  985. if(isset($json["Abstract"])){
  986. $description = $this->parse_rich_text($json["Abstract"]);
  987. }
  988. if(
  989. !isset($json["Image"]) ||
  990. $json["Image"] == "" ||
  991. $json["Image"] === null ||
  992. $json["Image"] == "https://duckduckgo.com/i/"
  993. ){
  994. $image = null;
  995. }else{
  996. if(
  997. preg_match(
  998. '/^https?:\/\//',
  999. $json["Image"]
  1000. )
  1001. ){
  1002. $image = $json["Image"];
  1003. }else{
  1004. $image = "https://duckduckgo.com" . $json["Image"];
  1005. }
  1006. }
  1007. $out["answer"][] = [
  1008. "title" => $json["Heading"],
  1009. "description" => $description,
  1010. "url" => $json["AbstractURL"],
  1011. "thumb" => $image,
  1012. "table" => $table,
  1013. "sublink" => $sublinks
  1014. ];
  1015. }
  1016. }
  1017. if($get["extendedsearch"] == "no"){
  1018. return $out;
  1019. }
  1020. //
  1021. // Parse additional data endpoints
  1022. //
  1023. //nrj('/js/spice/dictionary/definition/create', null, null, null, null, 'dictionary_definition');
  1024. preg_match_all(
  1025. '/nrj\(\s*\'([^\']+)\'/',
  1026. $js,
  1027. $nrj
  1028. );
  1029. if(isset($nrj[1])){
  1030. foreach($nrj[1] as $potential_endpoint){
  1031. //
  1032. // Probe for wordnik definition
  1033. //
  1034. preg_match(
  1035. '/\/js\/spice\/dictionary\/definition\/([^\/]+)/',
  1036. $potential_endpoint,
  1037. $word
  1038. );
  1039. if(isset($word[1])){
  1040. $word = $word[1];
  1041. // found wordnik definition & word
  1042. try{
  1043. $nik =
  1044. $this->get(
  1045. $proxy,
  1046. "https://duckduckgo.com/js/spice/dictionary/definition/" . $word,
  1047. [],
  1048. ddg::req_xhr
  1049. );
  1050. }catch(Exception $e){
  1051. // fail gracefully
  1052. return $out;
  1053. }
  1054. // remove javascript
  1055. $js_tmp =
  1056. preg_split(
  1057. '/ddg_spice_dictionary_definition\(\s*/',
  1058. $nik,
  1059. 2
  1060. );
  1061. if(count($js_tmp) > 1){
  1062. $nik =
  1063. json_decode(
  1064. $this->fuckhtml
  1065. ->extract_json(
  1066. $js_tmp[1]
  1067. ),
  1068. true
  1069. );
  1070. }
  1071. if($nik === null){
  1072. return $out;
  1073. }
  1074. $answer_cat = [];
  1075. $answer = [];
  1076. foreach($nik as $snippet){
  1077. if(!isset($snippet["partOfSpeech"])){ continue; }
  1078. $push = [];
  1079. // add text snippet
  1080. if(isset($snippet["text"])){
  1081. $push[] = [
  1082. "type" => "text",
  1083. "value" =>
  1084. $this->fuckhtml
  1085. ->getTextContent(
  1086. $snippet["text"]
  1087. )
  1088. ];
  1089. }
  1090. // add example uses
  1091. if(isset($snippet["exampleUses"])){
  1092. foreach($snippet["exampleUses"] as $example){
  1093. $push[] = [
  1094. "type" => "quote",
  1095. "value" => "\"" .
  1096. $this->fuckhtml
  1097. ->getTextContent(
  1098. $example["text"]
  1099. ) . "\""
  1100. ];
  1101. }
  1102. }
  1103. // add citations
  1104. if(isset($snippet["citations"])){
  1105. foreach($snippet["citations"] as $citation){
  1106. if(!isset($citation["cite"])){ continue; }
  1107. $text =
  1108. $this->fuckhtml
  1109. ->getTextContent(
  1110. $citation["cite"]
  1111. );
  1112. if(isset($citation["source"])){
  1113. $text .=
  1114. " - " .
  1115. $this->fuckhtml
  1116. ->getTextContent(
  1117. $citation["source"]
  1118. );
  1119. }
  1120. $push[] = [
  1121. "type" => "quote",
  1122. "value" => $text
  1123. ];
  1124. }
  1125. }
  1126. // add related words
  1127. if(isset($snippet["relatedWords"])){
  1128. $relations = [];
  1129. foreach($snippet["relatedWords"] as $related){
  1130. $words = [];
  1131. foreach($related["words"] as $wrd){
  1132. $words[] =
  1133. $this->fuckhtml
  1134. ->getTextContent(
  1135. $wrd
  1136. );
  1137. }
  1138. if(
  1139. count($words) !== 0 &&
  1140. isset($related["relationshipType"])
  1141. ){
  1142. $relations[ucfirst($related["relationshipType"]) . "s"] =
  1143. implode(", ", $words);
  1144. }
  1145. }
  1146. foreach($relations as $relation_title => $relation_content){
  1147. $push[] = [
  1148. "type" => "quote",
  1149. "value" => $relation_title . ": " . $relation_content
  1150. ];
  1151. }
  1152. }
  1153. if(count($push) !== 0){
  1154. // push data to answer_cat
  1155. if(!isset($answer_cat[$snippet["partOfSpeech"]])){
  1156. $answer_cat[$snippet["partOfSpeech"]] = [];
  1157. }
  1158. $answer_cat[$snippet["partOfSpeech"]] =
  1159. array_merge(
  1160. $answer_cat[$snippet["partOfSpeech"]],
  1161. $push
  1162. );
  1163. }
  1164. }
  1165. foreach($answer_cat as $answer_title => $answer_content){
  1166. $i = 0;
  1167. $answer[] = [
  1168. "type" => "title",
  1169. "value" => $answer_title
  1170. ];
  1171. $old_type = $answer[count($answer) - 1]["type"];
  1172. foreach($answer_content as $ans){
  1173. if(
  1174. $ans["type"] == "text" &&
  1175. $old_type == "text"
  1176. ){
  1177. $i++;
  1178. $c = count($answer) - 1;
  1179. // append text to existing textfield
  1180. $answer[$c] = [
  1181. "type" => "text",
  1182. "value" => $answer[$c]["value"] . "\n" . $i . ". " . $ans["value"]
  1183. ];
  1184. }elseif($ans["type"] == "text"){
  1185. $i++;
  1186. $answer[] = [
  1187. "type" => "text",
  1188. "value" => $i . ". " . $ans["value"]
  1189. ];
  1190. }else{
  1191. // append normally
  1192. $answer[] = $ans;
  1193. }
  1194. $old_type = $ans["type"];
  1195. }
  1196. }
  1197. // yeah.. sometimes duckduckgo doesnt give us a definition back
  1198. if(count($answer) !== 0){
  1199. $out["answer"][] = [
  1200. "title" => ucfirst($word),
  1201. "description" => $answer,
  1202. "url" => "https://www.wordnik.com/words/" . $word,
  1203. "thumb" => null,
  1204. "table" => [],
  1205. "sublink" => []
  1206. ];
  1207. }
  1208. }
  1209. //
  1210. // Parse stackoverflow answer
  1211. //
  1212. if(
  1213. preg_match(
  1214. '/^\/a\.js.*src_id=stack_overflow/',
  1215. $potential_endpoint
  1216. )
  1217. ){
  1218. // found stackoverflow answer
  1219. try{
  1220. $json =
  1221. $this->get(
  1222. $proxy,
  1223. "https://duckduckgo.com" . $potential_endpoint,
  1224. [],
  1225. ddg::req_xhr
  1226. );
  1227. }catch(Exception $e){
  1228. // fail gracefully
  1229. return $out;
  1230. }
  1231. $json = explode("DDG.duckbar.add_array(", $json, 2);
  1232. if(count($json) === 2){
  1233. $json =
  1234. json_decode(
  1235. $this->fuckhtml
  1236. ->extract_json(
  1237. $json[1]
  1238. ),
  1239. true
  1240. );
  1241. if(
  1242. $json !== null &&
  1243. isset($json[0]["data"])
  1244. ){
  1245. $json = $json[0]["data"];
  1246. foreach($json as $answer){
  1247. if(isset($answer["Heading"])){
  1248. $title = $answer["Heading"];
  1249. }elseif(isset($answer["title"])){
  1250. $title = $answer["title"];
  1251. }else{
  1252. $title = null;
  1253. }
  1254. if(
  1255. $title !== null &&
  1256. isset($answer["Abstract"])
  1257. ){
  1258. $description = $this->parse_rich_text($answer["Abstract"]);
  1259. $out["answer"][] = [
  1260. "title" => $title,
  1261. "description" => $description,
  1262. "url" => $answer["AbstractURL"],
  1263. "thumb" => null,
  1264. "table" => [],
  1265. "sublink" => []
  1266. ];
  1267. }
  1268. }
  1269. }
  1270. }
  1271. }
  1272. }
  1273. }
  1274. return $out;
  1275. }
  1276. public function image($get){
  1277. if($get["npt"]){
  1278. [$js_link, $proxy] = $this->backend->get($get["npt"], "images");
  1279. }else{
  1280. if(strlen($get["s"]) === 0){
  1281. throw new Exception("Search term is empty!");
  1282. }
  1283. $proxy = $this->backend->get_ip();
  1284. $filters = [];
  1285. if($get["date"] != "any"){ $filters[] = "time:{$get["date"]}"; }
  1286. if($get["size"] != "any"){ $filters[] = "size:{$get["size"]}"; }
  1287. if($get["color"] != "any"){ $filters[] = "color:{$get["color"]}"; }
  1288. if($get["type"] != "any"){ $filters[] = "type:{$get["type"]}"; }
  1289. if($get["layout"] != "any"){ $filters[] = "layout:{$get["layout"]}"; }
  1290. if($get["license"] != "any"){ $filters[] = "license:{$get["license"]}"; }
  1291. $filters = implode(",", $filters);
  1292. $get_filters = [
  1293. "q" => $get["s"],
  1294. "iax" => "images",
  1295. "ia" => "images"
  1296. ];
  1297. if($filters != ""){
  1298. $get_filters["iaf"] = $filters;
  1299. }
  1300. $nsfw = $get["nsfw"] == "yes" ? "-1" : "1";
  1301. $get_filters["kp"] = $nsfw;
  1302. try{
  1303. $html = $this->get(
  1304. $proxy,
  1305. "https://duckduckgo.com",
  1306. $get_filters,
  1307. ddg::req_web
  1308. );
  1309. }catch(Exception $err){
  1310. throw new Exception("Failed to fetch search page");
  1311. }
  1312. preg_match(
  1313. '/vqd="([0-9-]+)"/',
  1314. $html,
  1315. $vqd
  1316. );
  1317. if(!isset($vqd[1])){
  1318. throw new Exception("Failed to grep VQD token");
  1319. }
  1320. $js_link =
  1321. "i.js?" .
  1322. http_build_query([
  1323. "l" => $get["country"],
  1324. "o" => "json",
  1325. "q" => $get["s"],
  1326. "vqd" => $vqd[1],
  1327. "f" => $filters,
  1328. "p" => $nsfw
  1329. ]);
  1330. }
  1331. try{
  1332. $json =
  1333. $this->get(
  1334. $proxy,
  1335. "https://duckduckgo.com/" . $js_link,
  1336. [],
  1337. ddg::req_xhr
  1338. );
  1339. }catch(Exception $error){
  1340. throw new Exception("Failed to get i.js");
  1341. }
  1342. $json = json_decode($json, true);
  1343. if($json === null){
  1344. throw new Exception("Failed to decode JSON");
  1345. }
  1346. $out = [
  1347. "status" => "ok",
  1348. "npt" => null,
  1349. "image" => []
  1350. ];
  1351. if(!isset($json["results"])){
  1352. return $out;
  1353. }
  1354. // get npt
  1355. if(
  1356. isset($json["next"]) &&
  1357. $json["next"] !== null
  1358. ){
  1359. $vqd = null;
  1360. if(isset($vqd[1])){
  1361. $vqd = $vqd[1];
  1362. }else{
  1363. $vqd = array_values($json["vqd"]);
  1364. if(count($vqd) > 0){
  1365. $vqd = $vqd[0];
  1366. }
  1367. }
  1368. if($vqd !== null){
  1369. $out["npt"] =
  1370. $this->backend->store(
  1371. $json["next"] . "&vqd=" . $vqd,
  1372. "images",
  1373. $proxy
  1374. );
  1375. }
  1376. }
  1377. // get images
  1378. foreach($json["results"] as $image){
  1379. $ratio =
  1380. $this->bingratio(
  1381. (int)$image["width"],
  1382. (int)$image["height"]
  1383. );
  1384. $out["image"][] = [
  1385. "title" => $this->titledots($image["title"]),
  1386. "source" => [
  1387. [
  1388. "url" => $image["image"],
  1389. "width" => (int)$image["width"],
  1390. "height" => (int)$image["height"]
  1391. ],
  1392. [
  1393. "url" => $this->bingimg($image["thumbnail"]),
  1394. "width" => $ratio[0],
  1395. "height" => $ratio[1]
  1396. ]
  1397. ],
  1398. "url" => $this->unshiturl($image["url"])
  1399. ];
  1400. }
  1401. return $out;
  1402. }
  1403. public function video($get){
  1404. if($get["npt"]){
  1405. [$js_link, $proxy] = $this->backend->get($get["npt"], "videos");
  1406. }else{
  1407. if(strlen($get["s"]) === 0){
  1408. throw new Exception("Search term is empty!");
  1409. }
  1410. $proxy = $this->backend->get_ip();
  1411. $get_filters = [
  1412. "q" => $get["s"],
  1413. "iax" => "videos",
  1414. "ia" => "videos"
  1415. ];
  1416. switch($get["nsfw"]){
  1417. case "yes": $nsfw = "-2"; break;
  1418. case "maybe": $nsfw = "-1"; break;
  1419. case "no": $nsfw = "1"; break;
  1420. }
  1421. $filters = [];
  1422. if($get["date"] != "any"){ $filters[] = "publishedAfter:{$date}"; }
  1423. if($get["resolution"] != "any"){ $filters[] = "videoDefinition:{$resolution}"; }
  1424. if($get["duration"] != "any"){ $filters[] = "videoDuration:{$duration}"; }
  1425. if($get["license"] != "any"){ $filters[] = "videoLicense:{$license}"; }
  1426. $filters = implode(",", $filters);
  1427. if($filters != ""){
  1428. $get_filters["iaf"] = $filters;
  1429. }
  1430. try{
  1431. $html =
  1432. $this->get(
  1433. $proxy,
  1434. "https://duckduckgo.com/",
  1435. $get_filters,
  1436. ddg::req_web
  1437. );
  1438. }catch(Exception $error){
  1439. throw new Exception("Failed to fetch search page");
  1440. }
  1441. preg_match(
  1442. '/vqd="([0-9-]+)"/',
  1443. $html,
  1444. $vqd
  1445. );
  1446. if(!isset($vqd[1])){
  1447. throw new Exception("Failed to grep VQD token");
  1448. }
  1449. $js_link =
  1450. "v.js?" .
  1451. http_build_query([
  1452. "l" => $get["country"],
  1453. "o" => "json",
  1454. "sr" => "1",
  1455. "q" => $get["s"],
  1456. "vqd" => $vqd[1],
  1457. "f" => $filters,
  1458. "p" => $nsfw
  1459. ]);
  1460. }
  1461. try{
  1462. $json =
  1463. $this->get(
  1464. $proxy,
  1465. "https://duckduckgo.com/" . $js_link,
  1466. [],
  1467. ddg::req_xhr
  1468. );
  1469. }catch(Exception $error){
  1470. throw new Exception("Failed to fetch JSON");
  1471. }
  1472. $json = json_decode($json, true);
  1473. if($json === null){
  1474. throw new Exception("Failed to decode JSON");
  1475. }
  1476. $out = [
  1477. "status" => "ok",
  1478. "npt" => null,
  1479. "video" => [],
  1480. "author" => [],
  1481. "livestream" => [],
  1482. "playlist" => [],
  1483. "reel" => []
  1484. ];
  1485. if(!isset($json["results"])){
  1486. return $out;
  1487. }
  1488. // get NPT
  1489. if(
  1490. isset($json["next"]) &&
  1491. $json["next"] !== null
  1492. ){
  1493. $out["npt"] =
  1494. $this->backend->store(
  1495. $json["next"],
  1496. "videos",
  1497. $proxy
  1498. );
  1499. }
  1500. foreach($json["results"] as $video){
  1501. $thumb = [
  1502. "ratio" => null,
  1503. "url" => null
  1504. ];
  1505. foreach(["large", "medium", "small"] as $contender){
  1506. if(isset($video["images"][$contender])){
  1507. $thumb = [
  1508. "ratio" => "16:9",
  1509. "url" => $this->bingimg($video["images"][$contender])
  1510. ];
  1511. break;
  1512. }
  1513. }
  1514. $out["video"][] = [
  1515. "title" => $this->titledots($video["title"]),
  1516. "description" => $this->titledots($video["description"]),
  1517. "author" => [
  1518. "name" =>
  1519. (
  1520. isset($video["uploader"]) &&
  1521. $video["uploader"] != ""
  1522. ) ?
  1523. $video["uploader"] : null,
  1524. "url" => null,
  1525. "avatar" => null
  1526. ],
  1527. "date" =>
  1528. (
  1529. isset($video["published"]) &&
  1530. $video["published"] != ""
  1531. ) ?
  1532. strtotime($video["published"]) : null,
  1533. "duration" =>
  1534. (
  1535. isset($video["duration"]) &&
  1536. $video["duration"] != ""
  1537. ) ?
  1538. $this->hms2int($video["duration"]) : null,
  1539. "views" =>
  1540. isset($video["statistics"]["viewCount"]) ?
  1541. (int)$video["statistics"]["viewCount"] : null,
  1542. "thumb" => $thumb,
  1543. "url" => $this->unshiturl($video["content"])
  1544. ];
  1545. }
  1546. return $out;
  1547. }
  1548. public function news($get){
  1549. if($get["npt"]){
  1550. [$js_link, $proxy] = $this->backend->get($get["npt"], "news");
  1551. }else{
  1552. if(strlen($get["s"]) === 0){
  1553. throw new Exception("Search term is empty!");
  1554. }
  1555. $proxy = $this->backend->get_ip();
  1556. $get_filters = [
  1557. "q" => $get["s"],
  1558. "iar" => "news",
  1559. "ia" => "news"
  1560. ];
  1561. if($get["date"] != "any"){
  1562. $date = $get["date"];
  1563. $get_filters["df"] = $date;
  1564. }else{
  1565. $date = "";
  1566. }
  1567. switch($get["nsfw"]){
  1568. case "yes": $get_filters["kp"] = "-2"; break;
  1569. case "maybe": $get_filters["kp"] = "-1"; break;
  1570. case "no": $get_filters["kp"] = "1"; break;
  1571. }
  1572. try{
  1573. $html =
  1574. $this->get(
  1575. $proxy,
  1576. "https://duckduckgo.com/",
  1577. $get_filters,
  1578. ddg::req_web
  1579. );
  1580. }catch(Exception $error){
  1581. throw new Exception("Failed to fetch search page");
  1582. }
  1583. preg_match(
  1584. '/vqd="([0-9-]+)"/',
  1585. $html,
  1586. $vqd
  1587. );
  1588. if(!isset($vqd[1])){
  1589. throw new Exception("Failed to grep VQD token");
  1590. }
  1591. $js_link =
  1592. "news.js?" .
  1593. http_build_query([
  1594. "l" => $get["country"],
  1595. "o" => "json",
  1596. "noamp" => "1",
  1597. "m" => "30",
  1598. "q" => $get["s"],
  1599. "vqd" => $vqd[1],
  1600. "p" => $get_filters["kp"],
  1601. "df" => $date,
  1602. "u" => "bing"
  1603. ]);
  1604. }
  1605. try{
  1606. $json =
  1607. $this->get(
  1608. $proxy,
  1609. "https://duckduckgo.com/" . $js_link,
  1610. [],
  1611. ddg::req_xhr
  1612. );
  1613. }catch(Exception $error){
  1614. throw new Exception("Failed to fetch JSON");
  1615. }
  1616. $json = json_decode($json, true);
  1617. if($json === null){
  1618. throw new Exception("Failed to decode JSON");
  1619. }
  1620. $out = [
  1621. "status" => "ok",
  1622. "npt" => null,
  1623. "news" => []
  1624. ];
  1625. if(!isset($json["results"])){
  1626. return $out;
  1627. }
  1628. // get NPT
  1629. if(
  1630. isset($json["next"]) &&
  1631. $json["next"] !== null
  1632. ){
  1633. $out["npt"] =
  1634. $this->backend->store(
  1635. $json["next"],
  1636. "news",
  1637. $proxy
  1638. );
  1639. }
  1640. foreach($json["results"] as $news){
  1641. if(
  1642. isset($news["image"]) &&
  1643. $news["image"] != ""
  1644. ){
  1645. $thumb = [
  1646. "ratio" => "16:9",
  1647. "url" => $news["image"]
  1648. ];
  1649. }else{
  1650. $thumb = [
  1651. "ratio" => null,
  1652. "url" => null
  1653. ];
  1654. }
  1655. $out["news"][] = [
  1656. "title" => $news["title"],
  1657. "author" =>
  1658. (
  1659. isset($news["source"]) &&
  1660. $news["source"] != ""
  1661. ) ?
  1662. $news["source"] : null,
  1663. "description" =>
  1664. (
  1665. isset($news["excerpt"]) &&
  1666. $news["excerpt"] != ""
  1667. ) ?
  1668. $this->fuckhtml
  1669. ->getTextContent(
  1670. $news["excerpt"]
  1671. ) : null,
  1672. "date" =>
  1673. isset($news["date"]) ?
  1674. (int)$news["date"] : null,
  1675. "thumb" => $thumb,
  1676. "url" => $this->unshiturl($news["url"])
  1677. ];
  1678. }
  1679. return $out;
  1680. }
  1681. private function parse_rich_text($html){
  1682. $description = [];
  1683. // pre-process the html, remove useless elements
  1684. $html =
  1685. strip_tags(
  1686. $html,
  1687. [
  1688. "h1", "h2", "h3", "h4", "h5", "h6", "h7",
  1689. "pre", "code"
  1690. ]
  1691. );
  1692. $html =
  1693. preg_replace(
  1694. '/<(\/?)pre *[^>]*>\s*<\/?code *[^>]*>/i',
  1695. '<$1pre>',
  1696. $html
  1697. );
  1698. $this->fuckhtml->load($html);
  1699. $tags =
  1700. $this->fuckhtml
  1701. ->getElementsByTagName(
  1702. "*"
  1703. );
  1704. if(count($tags) === 0){
  1705. $description[] = [
  1706. "type" => "text",
  1707. "value" =>
  1708. trim(
  1709. $this->fuckhtml
  1710. ->getTextContent(
  1711. $html,
  1712. true,
  1713. false
  1714. )
  1715. )
  1716. ];
  1717. }else{
  1718. $start = 0;
  1719. $was_code_block = true;
  1720. foreach($tags as $tag){
  1721. $text =
  1722. $this->fuckhtml
  1723. ->getTextContent(
  1724. substr(
  1725. $html,
  1726. $start,
  1727. $tag["startPos"] - $start
  1728. ),
  1729. true,
  1730. false
  1731. );
  1732. if($was_code_block){
  1733. $text = ltrim($text);
  1734. $was_code_block = false;
  1735. }
  1736. $description[] = [
  1737. "type" => "text",
  1738. "value" => $text
  1739. ];
  1740. switch($tag["tagName"]){
  1741. case "pre":
  1742. $append = "code";
  1743. $was_code_block = true;
  1744. $c = count($description) - 1;
  1745. $description[$c]["value"] =
  1746. rtrim($description[$c]["value"]);
  1747. break;
  1748. case "code":
  1749. $append = "inline_code";
  1750. $c = count($description) - 1;
  1751. $description[$c]["value"] =
  1752. rtrim($description[$c]["value"]) . " ";
  1753. break;
  1754. case "h1":
  1755. case "h2":
  1756. case "h3":
  1757. case "h4":
  1758. case "h5":
  1759. case "h6":
  1760. case "h7":
  1761. $append = "title";
  1762. $c = count($description) - 1;
  1763. $description[$c]["value"] =
  1764. rtrim($description[$c]["value"]);
  1765. break;
  1766. }
  1767. $description[] = [
  1768. "type" => $append,
  1769. "value" =>
  1770. trim(
  1771. $this->fuckhtml
  1772. ->getTextContent(
  1773. $tag,
  1774. true,
  1775. false
  1776. )
  1777. )
  1778. ];
  1779. $start = $tag["endPos"];
  1780. }
  1781. // shit out remainder
  1782. $description[] = [
  1783. "type" => "text",
  1784. "value" =>
  1785. trim(
  1786. $this->fuckhtml
  1787. ->getTextContent(
  1788. substr(
  1789. $html,
  1790. $start
  1791. ),
  1792. true,
  1793. false
  1794. )
  1795. )
  1796. ];
  1797. }
  1798. return $description;
  1799. }
  1800. private function titledots($title){
  1801. $substr = substr($title, -3);
  1802. if(
  1803. $substr == "..." ||
  1804. $substr == "…"
  1805. ){
  1806. return trim(substr($title, 0, -3));
  1807. }
  1808. return trim($title);
  1809. }
  1810. private function hms2int($time){
  1811. $parts = explode(":", $time, 3);
  1812. $time = 0;
  1813. if(count($parts) === 3){
  1814. // hours
  1815. $time = $time + ((int)$parts[0] * 3600);
  1816. array_shift($parts);
  1817. }
  1818. if(count($parts) === 2){
  1819. // minutes
  1820. $time = $time + ((int)$parts[0] * 60);
  1821. array_shift($parts);
  1822. }
  1823. // seconds
  1824. $time = $time + (int)$parts[0];
  1825. return $time;
  1826. }
  1827. private function unshiturl($url){
  1828. // check for domains w/out first short subdomain (ex: www.)
  1829. $domain = parse_url($url, PHP_URL_HOST);
  1830. $subdomain = preg_replace(
  1831. '/^[A-z0-9]{1,3}\./',
  1832. "",
  1833. $domain
  1834. );
  1835. switch($subdomain){
  1836. case "ebay.com.au":
  1837. case "ebay.at":
  1838. case "ebay.ca":
  1839. case "ebay.fr":
  1840. case "ebay.de":
  1841. case "ebay.com.hk":
  1842. case "ebay.ie":
  1843. case "ebay.it":
  1844. case "ebay.com.my":
  1845. case "ebay.nl":
  1846. case "ebay.ph":
  1847. case "ebay.pl":
  1848. case "ebay.com.sg":
  1849. case "ebay.es":
  1850. case "ebay.ch":
  1851. case "ebay.co.uk":
  1852. case "cafr.ebay.ca":
  1853. case "ebay.com":
  1854. case "community.ebay.com":
  1855. case "pages.ebay.com":
  1856. // remove ebay tracking elements
  1857. $old_params = parse_url($url, PHP_URL_QUERY);
  1858. parse_str($old_params, $params);
  1859. if(isset($params["mkevt"])){ unset($params["mkevt"]); }
  1860. if(isset($params["mkcid"])){ unset($params["mkcid"]); }
  1861. if(isset($params["mkrid"])){ unset($params["mkrid"]); }
  1862. if(isset($params["campid"])){ unset($params["campid"]); }
  1863. if(isset($params["customid"])){ unset($params["customid"]); }
  1864. if(isset($params["toolid"])){ unset($params["toolid"]); }
  1865. if(isset($params["_sop"])){ unset($params["_sop"]); }
  1866. if(isset($params["_dcat"])){ unset($params["_dcat"]); }
  1867. if(isset($params["epid"])){ unset($params["epid"]); }
  1868. if(isset($params["epid"])){ unset($params["oid"]); }
  1869. $params = http_build_query($params);
  1870. if(strlen($params) === 0){
  1871. $replace = "\?";
  1872. }else{
  1873. $replace = "";
  1874. }
  1875. $url = preg_replace(
  1876. "/" . $replace . preg_quote($old_params, "/") . "$/",
  1877. $params,
  1878. $url
  1879. );
  1880. break;
  1881. }
  1882. return $url;
  1883. }
  1884. private function bingimg($url){
  1885. $image = parse_url($url);
  1886. $id = null;
  1887. if(isset($image["query"])){
  1888. parse_str($image["query"], $str);
  1889. if(isset($str["id"])){
  1890. $id = $str["id"];
  1891. }
  1892. }
  1893. if($id === null){
  1894. $id = explode("/th/id/", $image["path"], 2);
  1895. if(count($id) !== 2){
  1896. // malformed
  1897. return $url;
  1898. }
  1899. $id = $id[1];
  1900. }
  1901. return "https://" . $image["host"] . "/th?id=" . rawurlencode($id);
  1902. }
  1903. private function bingratio($width, $height){
  1904. $ratio = [
  1905. 474 / $width,
  1906. 474 / $height
  1907. ];
  1908. if($ratio[0] < $ratio[1]){
  1909. $ratio = $ratio[0];
  1910. }else{
  1911. $ratio = $ratio[1];
  1912. }
  1913. return [
  1914. floor($width * $ratio),
  1915. floor($height * $ratio)
  1916. ];
  1917. }
  1918. }