ddg.php 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230
  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. //$json = 'DDG.duckbar.add_array([{"data":[{"Abstract":"<p> If you are interested in finding out whether a variable has been declared regardless of its value, then using the <code>in</code> operator is the safest way to go. Consider this example: </p>\n\n<pre><code>// global scope\nvar theFu; // theFu has been declared, but its value is undefined\ntypeof theFu; // &quot;undefined&quot;\n</code></pre>\n\n<p> But this may not be the intended result for some cases, since the variable or property was declared but just not initialized. Use the <code>in</code> operator for a more robust <b>check</b>. </p>\n\n<pre><code>&quot;theFu&quot; in window; // true\n&quot;theFoo&quot; in window; // false\n</code></pre>\n\n<p> If you are interested in knowing whether the variable hasn\'t been declared or has the value <code>undefined</code>, then use the <code>typeof</code> operator, which is guaranteed to return a string: </p>\n\n<pre><code>if (typeof myVar !== &#x27;undefined&#x27;)\n</code></pre>\n\n<p> Direct comparisons against <code>undefined</code> are troublesome as <code>undefined</code> can be overwritten. </p>\n\n<pre><code>window.undefined = &quot;foo&quot;;\n&quot;foo&quot; == undefined // true\n</code></pre>\n\n<p> As @CMS pointed out, this has been patched in ECMAScript 5th ed., and <code>undefined</code> is non-writable. </p>\n\n<p> <code>if (window.myVar)</code> will also include these falsy values, so it\'s not very robust: </p>\n\n<pre>\nfalse\n0\n\"\"\nNaN\nnull\nundefined\n</pre>\n\n<p> Thanks to @CMS for pointing out that your third case - <code>if (myVariable)</code> can also throw an error in two cases. The first is when the variable hasn\'t been defined which throws a <code>ReferenceError</code>. </p>\n\n<pre><code>// abc was never declared.\nif (abc) {\n // ReferenceError: abc is not defined\n} \n</code></pre>\n\n<p> The other case is when the variable has been defined, but has a getter function which throws an error when invoked. For example, </p>\n\n<pre><code>// or it&#x27;s a property that can throw an error\nObject.defineProperty(window, &quot;myVariable&quot;, { \n get: function() { throw new Error(&quot;W00t?&quot;); }, \n set: undefined \n});\nif (myVariable) {\n // Error: W00t?\n}\n</code></pre>\n <p>--<a href=\"http://stackoverflow.com/users/165737/ddg\">Anurag</a></p>","AbstractSource":"Stack Overflow","AbstractURL":"http://stackoverflow.com/questions/3390396/ddg#3390426","Heading":"How can I check for undefined in JavaScript","data":[{"accepted":1,"creation_date":"2010-08-02T17:58:18.717","parent_score":3053,"post_links":{"10098816":1,"14572415":1,"1485840":3,"15722425":2,"16142957":1,"17082855":2,"17101585":1,"17297203":1,"18475309":1,"1984721":2,"20502070":1,"20529817":1,"20680223":1,"20824716":1,"20869585":1,"20891039":2,"21188382":2,"21805507":2,"21871775":1,"22481003":2,"22992780":1,"23303729":1,"23481605":1,"24640628":1,"24978423":1,"25093101":1,"26120577":1,"2631001":1,"26487804":1,"26816006":1,"27509":3,"2778901":1,"28535341":1,"29235071":1,"29274374":1,"2985771":3,"30212179":1,"32295428":1,"36038043":1,"37297791":2,"37980559":1,"37981604":1,"38825185":1,"3985661":1,"42025958":1,"42326845":1,"44039387":2,"44309845":1,"44451111":1,"45623767":1,"46349615":1,"46670713":1,"47061118":1,"47765100":1,"48791268":1,"49743198":1,"50672434":1,"51109296":1,"51844419":2,"52102855":1,"53087022":1,"53294206":1,"53309649":1,"55790409":2,"55851196":1,"57923236":2,"5879319":1,"59069809":1,"59573769":1,"59605060":2,"60498918":1,"60862972":2,"61417067":1,"63456991":1,"68305469":1,"68327992":1,"68941436":1,"71710480":1,"71734417":2,"75102037":2,"858181":1,"8675839":1,"9225436":1,"9817488":1},"tags":["|javascript|undefined|"]}],"meta":{"attribution":null,"blockgroup":null,"created_date":"2016-08-24","description":"Programming answers","designer":null,"dev_date":"2015-04-14","dev_milestone":"live","developer":[{"name":"zachthompson","type":"github","url":"https://github.com/zachthompson"}],"example_query":"python merge dicts","id":"stack_overflow","idField":"url","is_stackexchange":1,"js_callback_name":"stack_overflow","live_date":"2015-04-14","maintainer":{"github":"ddg"},"name":"Stack Overflow","perl_module":"DDG::Longtail::StackOverflow","producer":"jdorw","production_state":"offline","repo":"longtail","signal_from":"stack_overflow","src_domain":"stackoverflow.com","src_id":null,"src_name":"Stack Overflow","src_url":" ","status":"live","tab":" ","topic":["programming"],"unsafe":0},"signal":"low","title":"How can I check for undefined in JavaScript"}],"duckbar_topic":"qa","from":"nlp_qa","meta":{"attribution":null,"blockgroup":null,"created_date":"2016-08-24","description":"Programming answers","designer":null,"dev_date":"2015-04-14","dev_milestone":"live","developer":[{"name":"zachthompson","type":"github","url":"https://github.com/zachthompson"}],"example_query":"python merge dicts","id":"stack_overflow","idField":"url","is_stackexchange":1,"js_callback_name":"stack_overflow","live_date":"2015-04-14","maintainer":{"github":"ddg"},"name":"Stack Overflow","perl_module":"DDG::Longtail::StackOverflow","producer":"jdorw","production_state":"offline","repo":"longtail","signal_from":"stack_overflow","src_domain":"stackoverflow.com","src_id":null,"src_name":"Stack Overflow","src_url":" ","status":"live","tab":" ","topic":["programming"],"unsafe":0},"signal":"low","templates":{"detail":"nlp_detail","item":"nlp_item","item_detail":"qa_detail","wrap_detail":"base_detail"}}]);DDH.stack_overflow=DDH.stack_overflow||{};DDH.stack_overflow.meta={"attribution":null,"blockgroup":null,"created_date":"2016-08-24","description":"Programming answers","designer":null,"dev_date":"2015-04-14","dev_milestone":"live","developer":[{"name":"zachthompson","type":"github","url":"https://github.com/zachthompson"}],"example_query":"python merge dicts","id":"stack_overflow","idField":"url","is_stackexchange":1,"js_callback_name":"stack_overflow","live_date":"2015-04-14","maintainer":{"github":"ddg"},"name":"Stack Overflow","perl_module":"DDG::Longtail::StackOverflow","producer":"jdorw","production_state":"offline","repo":"longtail","signal_from":"stack_overflow","src_domain":"stackoverflow.com","src_id":null,"src_name":"Stack Overflow","src_url":" ","status":"live","tab":" ","topic":["programming"],"unsafe":0};';
  1090. //$json = 'DDG.duckbar.add_array([{"data":[{"Abstract":"<p> You can use the <code>convert</code> <b>command</b>: </p>\n<pre>\nconvert input.jpg -rotate <i>&lt;angle in degrees&gt;</i> out.jpg\n</pre>\n<p> To <b>rotate</b> 90 degrees clockwise: </p>\n<pre><code>convert input.jpg -rotate 90 out.jpg\n</code></pre>\n<p> To save the file with the same name: </p>\n<pre><code>convert file.jpg -rotate 90 file.jpg\n</code></pre>\n<p> To <b>rotate</b> all files: </p>\n<pre><code>for photo in *.jpg ; do convert $photo -rotate 90 $photo ; done\n</code></pre>\n<hr />\n<p> Alternatively, you can also use the <a href=\"https://imagemagick.org/script/mogrify.php\" rel=\"noreferrer\"><code>mogrify</code></a> <b>command</b> <b>line</b> tools (<b>the</b> best tool) recommended by <a href=\"https://unix.stackexchange.com/users/22142/don-crissti\">@don-crissti</a><b>:</b> </p>\n<pre><code>mogrify -rotate 90 *.jpg\n</code></pre>\n <p>--<a href=\"http://unix.stackexchange.com/users/153195/ddg\">GAD3R</a><b></p></b>","AbstractSource":"Unix & Linux Stack Exchange","AbstractURL":"http://unix.stackexchange.com/questions/365592/ddg#365595","Heading":"How to rotate a set of pictures from the command line","data":[{"accepted":1,"creation_date":"2017-05-17T11:39:04.000","parent_score":62,"post_links":{"395845":2},"tags":["|command-line|imagemagick|gimp|"]}],"meta":{"attribution":null,"blockgroup":null,"created_date":null,"description":"Question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems","designer":null,"dev_date":"2015-04-14","dev_milestone":"live","developer":[{"name":"DDG Team","type":"ddg","url":"http://www.duckduckhack.com"}],"example_query":"use DD to migrate data from an old drive to a new drive","id":"unix","idField":"url","is_stackexchange":1,"js_callback_name":"unix","live_date":"2015-04-14","maintainer":{"github":"duckduckgo"},"name":"Unix & Linux Stack Exchange","perl_module":"DDG::Longtail::Unix","producer":null,"production_state":"offline","repo":"longtail","signal_from":"unix","src_domain":"unix.stackexchange.com","src_id":null,"src_name":"Unix StackExchange","src_url":"unix.stackexchange.com","status":"live","tab":null,"topic":["sysadmin"],"unsafe":0},"signal":"low","title":"How to rotate a set of pictures from the command line"}],"duckbar_topic":"qa","from":"nlp_qa","meta":{"attribution":null,"blockgroup":null,"created_date":null,"description":"Question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems","designer":null,"dev_date":"2015-04-14","dev_milestone":"live","developer":[{"name":"DDG Team","type":"ddg","url":"http://www.duckduckhack.com"}],"example_query":"use DD to migrate data from an old drive to a new drive","id":"unix","idField":"url","is_stackexchange":1,"js_callback_name":"unix","live_date":"2015-04-14","maintainer":{"github":"duckduckgo"},"name":"Unix & Linux Stack Exchange","perl_module":"DDG::Longtail::Unix","producer":null,"production_state":"offline","repo":"longtail","signal_from":"unix","src_domain":"unix.stackexchange.com","src_id":null,"src_name":"Unix StackExchange","src_url":"unix.stackexchange.com","status":"live","tab":null,"topic":["sysadmin"],"unsafe":0},"signal":"low","templates":{"detail":"nlp_detail","item":"nlp_item","item_detail":"qa_detail","wrap_detail":"base_detail"}}]);DDH.unix=DDH.unix||{};DDH.unix.meta={"attribution":null,"blockgroup":null,"created_date":null,"description":"Question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems","designer":null,"dev_date":"2015-04-14","dev_milestone":"live","developer":[{"name":"DDG Team","type":"ddg","url":"http://www.duckduckhack.com"}],"example_query":"use DD to migrate data from an old drive to a new drive","id":"unix","idField":"url","is_stackexchange":1,"js_callback_name":"unix","live_date":"2015-04-14","maintainer":{"github":"duckduckgo"},"name":"Unix & Linux Stack Exchange","perl_module":"DDG::Longtail::Unix","producer":null,"production_state":"offline","repo":"longtail","signal_from":"unix","src_domain":"unix.stackexchange.com","src_id":null,"src_name":"Unix StackExchange","src_url":"unix.stackexchange.com","status":"live","tab":null,"topic":["sysadmin"],"unsafe":0};';
  1091. if(
  1092. preg_match(
  1093. '/^\/a\.js.*src_id=stack_overflow/',
  1094. $potential_endpoint
  1095. )
  1096. ){
  1097. // found stackoverflow answer
  1098. try{
  1099. $json =
  1100. $this->get(
  1101. $proxy,
  1102. "https://duckduckgo.com" . $potential_endpoint,
  1103. [],
  1104. ddg::req_xhr
  1105. );
  1106. }catch(Exception $e){
  1107. // fail gracefully
  1108. return $out;
  1109. }
  1110. $json = explode("DDG.duckbar.add_array(", $json, 2);
  1111. if(count($json) === 2){
  1112. $json =
  1113. json_decode(
  1114. $this->fuckhtml
  1115. ->extract_json(
  1116. $json[1]
  1117. ),
  1118. true
  1119. );
  1120. if(
  1121. $json !== null &&
  1122. isset($json[0]["data"])
  1123. ){
  1124. $json = $json[0]["data"];
  1125. foreach($json as $answer){
  1126. if(isset($answer["Heading"])){
  1127. $title = $answer["Heading"];
  1128. }elseif(isset($answer["title"])){
  1129. $title = $answer["title"];
  1130. }else{
  1131. $title = null;
  1132. }
  1133. if(
  1134. $title !== null &&
  1135. isset($answer["Abstract"])
  1136. ){
  1137. // got some data
  1138. $description = [];
  1139. $html = &$answer["Abstract"];
  1140. // pre-process the html, remove useless elements
  1141. $html =
  1142. strip_tags(
  1143. $html,
  1144. [
  1145. "h1", "h2", "h3", "h4", "h5", "h6", "h7",
  1146. "pre", "code"
  1147. ]
  1148. );
  1149. $html =
  1150. preg_replace(
  1151. '/<(\/?)pre *[^>]*>\s*<\/?code *[^>]*>/i',
  1152. '<$1pre>',
  1153. $html
  1154. );
  1155. $this->fuckhtml->load($html);
  1156. $tags =
  1157. $this->fuckhtml
  1158. ->getElementsByTagName(
  1159. "*"
  1160. );
  1161. if(count($tags) === 0){
  1162. $description = [
  1163. "type" => "text",
  1164. "value" =>
  1165. trim(
  1166. $this->fuckhtml
  1167. ->getTextContent(
  1168. substr(
  1169. $html,
  1170. $start,
  1171. $tag["startPos"] - $start
  1172. ),
  1173. true,
  1174. false
  1175. )
  1176. )
  1177. ];
  1178. }else{
  1179. $start = 0;
  1180. $was_code_block = true;
  1181. foreach($tags as $tag){
  1182. $text =
  1183. $this->fuckhtml
  1184. ->getTextContent(
  1185. substr(
  1186. $html,
  1187. $start,
  1188. $tag["startPos"] - $start
  1189. ),
  1190. true,
  1191. false
  1192. );
  1193. if($was_code_block){
  1194. $text = ltrim($text);
  1195. $was_code_block = false;
  1196. }
  1197. $description[] = [
  1198. "type" => "text",
  1199. "value" => $text
  1200. ];
  1201. switch($tag["tagName"]){
  1202. case "pre":
  1203. $append = "code";
  1204. $was_code_block = true;
  1205. $c = count($description) - 1;
  1206. $description[$c]["value"] =
  1207. rtrim($description[$c]["value"]);
  1208. break;
  1209. case "code":
  1210. $append = "inline_code";
  1211. $c = count($description) - 1;
  1212. $description[$c]["value"] =
  1213. rtrim($description[$c]["value"]) . " ";
  1214. break;
  1215. case "h1":
  1216. case "h2":
  1217. case "h3":
  1218. case "h4":
  1219. case "h5":
  1220. case "h6":
  1221. case "h7":
  1222. $append = "title";
  1223. $c = count($description) - 1;
  1224. $description[$c]["value"] =
  1225. rtrim($description[$c]["value"]);
  1226. break;
  1227. }
  1228. $description[] = [
  1229. "type" => $append,
  1230. "value" =>
  1231. trim(
  1232. $this->fuckhtml
  1233. ->getTextContent(
  1234. $tag,
  1235. true,
  1236. false
  1237. )
  1238. )
  1239. ];
  1240. $start = $tag["endPos"];
  1241. }
  1242. // shit out remainder
  1243. $description[] = [
  1244. "type" => "text",
  1245. "value" =>
  1246. trim(
  1247. $this->fuckhtml
  1248. ->getTextContent(
  1249. substr(
  1250. $html,
  1251. $start
  1252. ),
  1253. true,
  1254. false
  1255. )
  1256. )
  1257. ];
  1258. }
  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 titledots($title){
  1682. $substr = substr($title, -3);
  1683. if(
  1684. $substr == "..." ||
  1685. $substr == "…"
  1686. ){
  1687. return trim(substr($title, 0, -3));
  1688. }
  1689. return trim($title);
  1690. }
  1691. private function hms2int($time){
  1692. $parts = explode(":", $time, 3);
  1693. $time = 0;
  1694. if(count($parts) === 3){
  1695. // hours
  1696. $time = $time + ((int)$parts[0] * 3600);
  1697. array_shift($parts);
  1698. }
  1699. if(count($parts) === 2){
  1700. // minutes
  1701. $time = $time + ((int)$parts[0] * 60);
  1702. array_shift($parts);
  1703. }
  1704. // seconds
  1705. $time = $time + (int)$parts[0];
  1706. return $time;
  1707. }
  1708. private function unshiturl($url){
  1709. // check for domains w/out first short subdomain (ex: www.)
  1710. $domain = parse_url($url, PHP_URL_HOST);
  1711. $subdomain = preg_replace(
  1712. '/^[A-z0-9]{1,3}\./',
  1713. "",
  1714. $domain
  1715. );
  1716. switch($subdomain){
  1717. case "ebay.com.au":
  1718. case "ebay.at":
  1719. case "ebay.ca":
  1720. case "ebay.fr":
  1721. case "ebay.de":
  1722. case "ebay.com.hk":
  1723. case "ebay.ie":
  1724. case "ebay.it":
  1725. case "ebay.com.my":
  1726. case "ebay.nl":
  1727. case "ebay.ph":
  1728. case "ebay.pl":
  1729. case "ebay.com.sg":
  1730. case "ebay.es":
  1731. case "ebay.ch":
  1732. case "ebay.co.uk":
  1733. case "cafr.ebay.ca":
  1734. case "ebay.com":
  1735. case "community.ebay.com":
  1736. case "pages.ebay.com":
  1737. // remove ebay tracking elements
  1738. $old_params = parse_url($url, PHP_URL_QUERY);
  1739. parse_str($old_params, $params);
  1740. if(isset($params["mkevt"])){ unset($params["mkevt"]); }
  1741. if(isset($params["mkcid"])){ unset($params["mkcid"]); }
  1742. if(isset($params["mkrid"])){ unset($params["mkrid"]); }
  1743. if(isset($params["campid"])){ unset($params["campid"]); }
  1744. if(isset($params["customid"])){ unset($params["customid"]); }
  1745. if(isset($params["toolid"])){ unset($params["toolid"]); }
  1746. if(isset($params["_sop"])){ unset($params["_sop"]); }
  1747. if(isset($params["_dcat"])){ unset($params["_dcat"]); }
  1748. if(isset($params["epid"])){ unset($params["epid"]); }
  1749. if(isset($params["epid"])){ unset($params["oid"]); }
  1750. $params = http_build_query($params);
  1751. if(strlen($params) === 0){
  1752. $replace = "\?";
  1753. }else{
  1754. $replace = "";
  1755. }
  1756. $url = preg_replace(
  1757. "/" . $replace . preg_quote($old_params, "/") . "$/",
  1758. $params,
  1759. $url
  1760. );
  1761. break;
  1762. }
  1763. return $url;
  1764. }
  1765. private function bingimg($url){
  1766. $image = parse_url($url);
  1767. $id = null;
  1768. if(isset($image["query"])){
  1769. parse_str($image["query"], $str);
  1770. if(isset($str["id"])){
  1771. $id = $str["id"];
  1772. }
  1773. }
  1774. if($id === null){
  1775. $id = explode("/th/id/", $image["path"], 2);
  1776. if(count($id) !== 2){
  1777. // malformed
  1778. return $url;
  1779. }
  1780. $id = $id[1];
  1781. }
  1782. return "https://" . $image["host"] . "/th?id=" . rawurlencode($id);
  1783. }
  1784. private function bingratio($width, $height){
  1785. $ratio = [
  1786. 474 / $width,
  1787. 474 / $height
  1788. ];
  1789. if($ratio[0] < $ratio[1]){
  1790. $ratio = $ratio[0];
  1791. }else{
  1792. $ratio = $ratio[1];
  1793. }
  1794. return [
  1795. floor($width * $ratio),
  1796. floor($height * $ratio)
  1797. ];
  1798. }
  1799. }