ddg.php 53 KB

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