diff options
author | lolcat <will@lolcat.ca> | 2025-08-11 01:55:15 +0000 |
---|---|---|
committer | lolcat <will@lolcat.ca> | 2025-08-11 01:55:15 +0000 |
commit | cdf958d29333d448f4521f4d2faa2592b58e9b27 (patch) | |
tree | 528f2a0ffa789a6f4279d9f54a4a2aaf391f390f | |
download | shittyweb-search-cdf958d29333d448f4521f4d2faa2592b58e9b27.tar.gz shittyweb-search-cdf958d29333d448f4521f4d2faa2592b58e9b27.tar.bz2 shittyweb-search-cdf958d29333d448f4521f4d2faa2592b58e9b27.zip |
fix wikipedia crashgrafted
155 files changed, 41563 insertions, 0 deletions
diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..6b8710a --- /dev/null +++ b/.dockerignore @@ -0,0 +1 @@ +.git diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..134e1b2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,28 @@ +lib/test.html +lib/postdata.json +lib/nextpage.json +scraper/brave.html +scraper/yandex.json +scraper/marginalia.json +banner_og/ +scraper/mojeek.html +scraper/google.html +scraper/google-img.html +scraper/google-video.html +scraper/google-news.html +scraper/google-img-nextpage.html +scraper/brave-image.html +scraper/brave-video.html +scraper/facebook.html +scraper/facebook-nextpage.json +scraper/yandex-video.json +scraper/yandex.html +scraper/soundcloud.json +scraper/mp3-pm.html +banner/* +data/captcha/birds/ +data/captcha/fumo_plushies/ +data/captcha/minecraft/ +!banner/*default* +scraper/curlie.html +icons/* diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..e1017d8 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,17 @@ +FROM alpine:3.21 +WORKDIR /var/www/html/4get + +RUN apk update && apk upgrade +RUN apk add php apache2-ssl php84-fileinfo php84-openssl php84-iconv php84-common php84-dom php84-sodium php84-curl curl php84-pecl-apcu php84-apache2 imagemagick php84-pecl-imagick php84-mbstring imagemagick-webp imagemagick-jpeg + +COPY . . + +RUN chmod 777 /var/www/html/4get/icons + +EXPOSE 80 +EXPOSE 443 + +ENV FOURGET_PROTO=http + +ENTRYPOINT ["./docker/docker-entrypoint.sh"] +CMD ["start"]
\ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..a68df3b --- /dev/null +++ b/README.md @@ -0,0 +1,61 @@ +## <a href="https://4get.ca/donate">Donate to the project here!</a> + +# 4get search +**4get** is a proxy search engine that doesn't suck. + +## About 4get +https://4get.ca/about + +## Official instance +https://4get.ca , or visit the official instance list: https://4get.ca/instances + +_NOT to be confused with 4get.ch, 4get.lol and friends! I **don't** host these._ + +## Totally unbiased comparison between alternatives + +| | 4get | searx(ng) | libreY | araa | hearch.co | +|----------------------------|-------------------------|-----------|-------------|-----------|-------------------| +| RAM usage | 200-400mb~ | 2GB~ | 200-400mb~ | 2GB~ | idk | +| Does it suck | no (debunked by snopes) | yes | yes | a little | better than searx | +| Does it work | ye | sometimes | sometimes | sometimes | yes | + +## Features +1. Rotating proxies on a per-scraper basis +2. Search filters, which SearxNG lacks for the most part +3. Bot protection that *actually* filters out the bots (when configured) +4. Interface doesn't require javascript +5. Favicon fetcher with caching support & image proxy +6. Bunch of other shits + +tl;dr 4get is the best way to browse for shit. + +# Supported websites + +| Web | Images | Videos | News | Music | Autocompleter | +|------------|--------------|--------------|------------|------------|---------------| +| DuckDuckGo | DuckDuckGo | YouTube | DuckDuckGo | Soundcloud | Brave | +| Brave | Brave | Sepia Search | Brave | | DuckDuckGo | +| Yandex | Yandex | DuckDuckGo | Google | | Yandex | +| Google | Google | Brave | Startpage | | Google | +| Startpage | Startpage | Yandex | Qwant | | Startpage | +| Qwant | Qwant | Google | Mojeek | | Kagi | +| Ghostery | Yep | Startpage | Baidu | | Qwant | +| Yep | Baidu | Qwant | | | Ghostery | +| Greppr | Pinterest | Baidu | | | Yep | +| Crowdview | 500px | Coc Coc | | | Marginalia | +| Mwmbl | VSCO | | | | YouTube | +| Mojeek | Imgur | | | | Soundcloud | +| Baidu | FindThatMeme | | | | | +| Coc Coc | | | | | | +| Marginalia | | | | | | +| wiby | | | | | | +| Curlie | | | | | | + +# Installation +Refer to the <a href="https://git.lolcat.ca/lolcat/4get/src/branch/master/docs/">documentation index</a>. I recommend following the <a href="https://git.lolcat.ca/lolcat/4get/src/branch/master/docs/apache2.md">apache2 guide</a>. + +## Contact +Shit breaks all the time but I repair it all the time too. Email me here: <b>will (at) lolcat.ca</b> or create an issue. + +## License +AGPL diff --git a/about.php b/about.php new file mode 100644 index 0000000..b0bb65c --- /dev/null +++ b/about.php @@ -0,0 +1,39 @@ +<?php + +include "data/config.php"; +include "lib/frontend.php"; +$frontend = new frontend(); + +echo + $frontend->load( + "header_nofilters.html", + [ + "title" => "About", + "class" => " class=\"about\"" + ] + ); + +$left = + explode( + "\n", + file_get_contents("template/about.html") + ); + +$out = ""; + +foreach($left as $line){ + + $out .= trim($line); +} + +echo + $frontend->load( + "search.html", + [ + "timetaken" => null, + "class" => "", + "right-left" => "", + "right-right" => "", + "left" => $out + ] + ); diff --git a/ami4get.php b/ami4get.php new file mode 100644 index 0000000..5bb9273 --- /dev/null +++ b/ami4get.php @@ -0,0 +1,27 @@ +<?php + +header("Content-Type: application/json"); +header("Access-Control-Allow-Origin: *"); + +include "data/config.php"; + +$real_requests = apcu_fetch("real_requests"); +$bot_requests = apcu_fetch("captcha_gen"); + +echo json_encode( + [ + "status" => "ok", + "service" => "4get", + "server" => [ + "name" => config::SERVER_NAME, + "description" => config::SERVER_LONG_DESCRIPTION, + "bot_protection" => config::BOT_PROTECTION, + "real_requests" => $real_requests === false ? 0 : $real_requests, + "bot_requests" => $bot_requests === false ? 0 : $bot_requests, + "api_enabled" => config::API_ENABLED, + "alt_addresses" => config::ALT_ADDRESSES, + "version" => config::VERSION + ], + "instances" => config::INSTANCES + ] +); @@ -0,0 +1,357 @@ + 44 + 4444444 44 + 44444444 44444 444 + 44444444 444444 444444444 + 44444 44444444 444444444 + 444444444 4444444 + 4444444444 444444 + 4444444444444 + 444444444444444444 + 444444444444444 + 44444444 + 4444 + 44 + + + Welcome to the 4get API documentation + + ++ Terms of use + Do NOT misuse the API. Misuses can include... :: + + 1. Serp SEO scanning + 2. Intensive scraping + 3. Any other activity that isn't triggered by a human + 4. Illegal activities in Canada + 5. Constant "test" queries while developping your program + (please cache the API responses!) + + + Examples of good uses of the API :: + + 1. A chatroom bot that presents users with search results + 2. Personal use + 3. Any other activity that is initiated by a human + + + If you wish to engage in the activities listed under "misuses", feel + free to download the source code of the project and running 4get + under your own terms. Please respect the terms of use listed here so + that this website may be available to all in the far future. + + P.s fuck whoever botted my site for months on end, choke on my dick + lol!!!! + + Get your instance running here :: + https://git.lolcat.ca/lolcat/4get + + Thanks! + + ++ Passes + Depending of the instance, you may need to provide a "pass" token + in the cookies of your request. These can be obtained from solving + a captcha which will allow you to make 100 requests in the next 24 + hours. In the future, you will be able to ask the serber maintainer + for a "pass" which will allow you to bypass the captcha requirement. + + The captcha doesn't need javascript to work. + + ++ Decode the data + All payloads returned by the API are encoded in the JSON format. If + you don't know how to tackle the problem, maybe programming is not + for you. + + All of the endpoints use the GET method. + + ++ Check if an API call was successful + All API responses come with an array index named "status". If the + status is something else than the string "ok", something went wrong. + You can supply the content of the "status" string back to your + application to inform the user of what went wrong. + + The HTTP code will be 429 if your pass is invalid. It is set to 200 + otherwise. + + ++ Get the next page of results + All API responses come with an array index named "npt". To get the + next page of results, you must make another API call with &npt. + + Example :: + + + First API call + /api/v1/web?s=higurashi + + + Second API call + /api/v1/web?npt=ddg1._rJ2hWmYSjpI2hsXWmYajJx < ... > + + You shouldn't specify the search term, only the &npt parameter + suffices. + + The first part of the token before the dot (ddg1) refers to an + array position on the serber's memory. The second part is an + encryption key used to decode the data at that position. This way, + it is impossible to supply invalid pagination data and it is + impossible for a 4get operator to peek at the private data of the + user after a request has been made. + + The tokens will expire as soon as they are used or after a 15 + minutes inactivity period, whichever comes first. + + ++ Beware of null values! + Most fields in the API responses can return "null". You don't need + to worry about unset values. + + ++ API Parameters + To construct a valid request, you can use the 4get web interface + to craft a valid request, and replace "/web" with "/api/v1/web". + + ++ "date" and "time" parameters + "date" always refer to a calendar date. + "time" always refer to the duration of some media. + + They are both integers that uses seconds as its unit. The "date" + parameter specifies the number of seconds that passed since January + 1st 1970. + + + ______ __ _ __ + / ____/___ ____/ /___ ____ (_)___ / /______ + / __/ / __ \/ __ / __ \/ __ \/ / __ \/ __/ ___/ + / /___/ / / / /_/ / /_/ / /_/ / / / / / /_(__ ) + /_____/_/ /_/\__,_/ .___/\____/_/_/ /_/\__/____/ + /_/ + ++ /ami4get + Tells you basic information about the 4get instance. CORS requests + are allowed on this endpoint. + + ++ /api/v1/web + + &extendedsearch + When using the ddg(DuckDuckGo) scraper, you may make use of the + &extendedsearch parameter. If you need rich answer data from + additional sources like StackOverflow, music lyrics sites, etc., + you need to specify the value of (string)"true". + + The default value is "false" for API calls. + + + + Parse the "spelling" + The array index named "spelling" contains 3 indexes :: + + spelling: + type: "including" + using: "4chan" + correction: '"4cha"' + + + The "type" may be any of these 3 values. When rendering the + autocorrect text inside your application, it should look like + what follows right after the parameter value :: + + no_correction <Empty> + including Including results for %using%. Did you mean + %correction%? + + not_many Not many results for %using%. Did you mean + %correction%? + + + As of right now, the "spelling" is only available on + "/api/v1/web". + + + + Parse the "answer" + The array index named "answer" may contain a list of multiple + answers. The array index "description" contains a linear list of + nodes that can help you construct rich formatted data inside of + your application. The structure is similar to the one below: + + answer: + 0: + title: "Higurashi" + description: + 0: + type: "text" + value: "Higurashi is a great show!" + 1: + type: "quote" + value: "Source: my ass" + + + Each "description" node contains an array index named "type". + Here is a list of them: + + text + + title + italic + + quote + + code + inline_code + link + + image + + audio + + + Each individual node prepended with a "+" should be prepended by + a newline when constructing the rendered description object. + + There are some nodes that differ from the type-value format. + Please parse them accordingly :: + + + link + type: "link" + url: "https://lolcat.ca" + value: "Visit my website!" + + + + image + type: "image" + url: "https://lolcat.ca/static/pixels.png" + + + + audio + type: "audio" + url: "https://lolcat.ca/static/whatever.mp3" + + + The array index named "table" is an associative array. You can + loop over the data using this PHP code, for example :: + + foreach($table as $website_name => $url){ // ... + + + The rest of the JSON is pretty self explanatory. + + ++ /api/v1/images + All images are contained within "image". The structure looks like + below :: + + image: + 0: + title: "My awesome Higurashi image" + source: + 0: + url: "https://lolcat.ca/static/profile_pix.png" + width: 400 + height: 400 + 1: + url: "https://lolcat.ca/static/pixels.png" + width: 640 + height: 640 + 2: + url: "https://tse1.mm.bing.net/th?id=OIP.VBM3BQg + euf0-xScO1bl1UgHaGG" + width: 194 + height: 160 + + + The last image of the "source" array is always the thumbnail, and is + a good fallback to use when other sources fail to load. There can be + more than 1 source; this is especially true when using the Yandex + scraper, but beware of captcha rate limits. + + ++ /api/v1/videos + The "time" parameter for videos may be set to "_LIVE". For live + streams, the amount of people currently watching is passed in + "views". + + ++ /api/v1/news + Just make a request to "/api/v1/news?s=elon+musk". The payload + has nothing special about it and is very self explanatory, just like + the endpoint above. + + ++ /api/v1/music + Each entry under "song" contains a array index called "stream" that + looks like this :: + + endpoint: sc + url: https://api-v2.soundcloud <...> + + + When the endpoint is something else than "linear", you MUST use + the specified endpoint. Otherwise, you are free to handle that + json+m3u8 crap yourself. If the endpoint is equal to "linear", the + URL should return a valid HTTP audio stream. To access the endpoint, + you must add the following prefix in your request, like so: + + https://4get.ca/audio/<endpoint>?s=<url> + + ++ /favicon + Get the favicon for a website. The only parameter is "s", and must + include the protocol for fetching in case the favicon is not cached + yet. + + Example :: + + /favicon?s=https://lolcat.ca + + + If we had to revert to using Google's favicon cache, it will throw + an error in the X-Error header field. If Google's favicon cache + also failed to return an image, or if you're too retarded to specify + a valid domain name, a default placeholder image will be returned + alongside the "404" HTTP error code. + + ++ /proxy + Get a proxied image. Useful if you don't want to leak your user's IP + address. The parameters are "i" for the image link and "s" for the + size. + + Acceptable "s" parameters: + + portrait 90x160 + landscape 160x90 + square 90x90 + thumb 236x180 + cover 207x270 + original <Original resolution> + + You can also ommit the "s" parameter if you wish to view the + original image. When an error occurs, an "X-Error" header field + is set. + + ++ /audio/linear + Get a proxied audio file. Does not support "Range" headers, as it's + only used to proxy small files (hence why it's called linear DUH) + + The parameter is "s" for the audio link. + + ++ /audio/sc + Get a proxied audio file for SoundCloud. Does not support downloads + trough WGET or CURL, since it returns 30kb~160kb "206 Partial + Content" parts, due to technical limitations that comes with + converting m3u8 playlists to seekable audio files. If you use this + endpoint, you must support these 206 codes and also handle the + initial 302 HTTP redirect. I used this method as I didn't want to + store information about your request needlessly. This method also + allows noJS users to access the files. + + The parameter is "s" for the SoundCloud JSON m3u8 abomination. It + does not support "normal" SoundCloud URLs at this time. + + ++ /audio/spotify + Get a proxied Spotify audio file. Accepts a track ID for the "s" + parameter. Will only allow you to fetch the 30 second preview since + I don't feel like fucking with cookies and accounts every fucking + living moment of my life. You must handle the initial 302 redirect + to the /audio/linear endpoint. + + ++ Appendix + If you have any questions or need clarifications, please send an + email my way to will at lolcat.ca diff --git a/api/index.php b/api/index.php new file mode 100644 index 0000000..dae86ab --- /dev/null +++ b/api/index.php @@ -0,0 +1,10 @@ +<?php + +header("Content-Type: application/json"); +http_response_code(404); + +echo json_encode( + [ + "status" => "Unknown endpoint" + ] +); diff --git a/api/v1/ac.php b/api/v1/ac.php new file mode 100644 index 0000000..50d3095 --- /dev/null +++ b/api/v1/ac.php @@ -0,0 +1,243 @@ +<?php + +include "../../data/config.php"; +new autocomplete(); + +class autocomplete{ + + public function __construct(){ + + header("Content-Type: application/json"); + + $this->scrapers = [ + "brave" => "https://search.brave.com/api/suggest?q={searchTerms}", + "ddg" => "https://duckduckgo.com/ac/?q={searchTerms}&type=list", + "yandex" => "https://suggest.yandex.com/suggest-ff.cgi?part={searchTerms}&uil=en&v=3&sn=5&lr=21276&yu=4861394161661655015", + "google" => "https://www.google.com/complete/search?client=mobile-gws-lite&q={searchTerms}", + "qwant" => "https://api.qwant.com/v3/suggest/?q={searchTerms}&client=opensearch", + "yep" => "https://api.yep.com/ac/?query={searchTerms}", + "marginalia" => "https://search.marginalia.nu/suggest/?partial={searchTerms}", + "yt" => "https://suggestqueries-clients6.youtube.com/complete/search?client=youtube&q={searchTerms}", + "sc" => "", + "startpage" => "https://www.startpage.com/suggestions?q={searchTerms}&format=opensearch&segment=startpage.defaultffx&lui=english", + "kagi" => "https://kagi.com/api/autosuggest?q={searchTerms}", + "ghostery" => "https://ghosterysearch.com/suggest?q={searchTerms}" + ]; + + /* + Sanitize input + */ + if(!isset($_GET["s"])){ + + $this->do404("Missing search(s) parameter"); + } + + if(is_string($_GET["s"]) === false){ + + $this->do404("Invalid search(s) parameter"); + } + + if(strlen($_GET["s"]) > 500){ + + $this->do404("Search(s) exceeds the 500 char length"); + } + + /* + Get $scraper + */ + if(!isset($_GET["scraper"])){ + + if(isset($_COOKIE["scraper_ac"])){ + + $scraper = $_COOKIE["scraper_ac"]; + }else{ + + $scraper = "brave"; // default option + } + }else{ + + $scraper = $_GET["scraper"]; + } + + if($scraper == "disabled"){ + + // this shouldnt happen, but let's handle it anyways + $this->doempty(); + } + + // make sure it exists + if(!isset($this->scrapers[$scraper])){ + + $scraper = "brave"; // default option + } + + // return results + switch($scraper){ + + case "google": + case "yt": + // handle google cause they want to be a special snowflake :( + $js = $this->get($this->scrapers[$scraper], $_GET["s"]); + + preg_match( + '/\((\[.*\])\)/', + $js, + $js + ); + + if(!isset($js[1])){ + + $this->doempty(); + } + + $js = json_decode($js[1]); + $json = []; + + foreach($js[1] as $item){ + + $json[] = htmlspecialchars_decode(strip_tags($item[0])); + } + + echo json_encode( + [ + $_GET["s"], + $json + ], + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE + ); + break; + + case "sc": + // soundcloud + chdir("../../"); + include "scraper/sc.php"; + $sc = new sc(); + + $token = $sc->get_token("raw_ip::::"); + + $js = $this->get( + "https://api-v2.soundcloud.com/search/queries?q={searchTerms}&client_id=" . $token . "&limit=10&offset=0&linked_partitioning=1&app_version=1693487844&app_locale=en", + $_GET["s"] + ); + + $js = json_decode($js, true); + + if(!isset($js["collection"])){ + + $this->doempty(); + } + + $json = []; + foreach($js["collection"] as $item){ + + $json[] = $item["query"]; + } + + echo json_encode( + [ + $_GET["s"], + $json + ], + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE + ); + break; + + case "marginalia": + $json = $this->get($this->scrapers[$scraper], $_GET["s"]); + + $json = json_decode($json, true); + if($json === null){ + + + $this->doempty(); + } + + echo json_encode( + [ + $_GET["s"], + $json + ], + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE + ); + break; + + default: + // if it respects the openSearch protocol + $json = json_decode($this->get($this->scrapers[$scraper], $_GET["s"]), true); + + echo json_encode( + [ + $_GET["s"], + $json[1] // ensure it contains valid key 0 + ], + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE + ); + break; + } + } + + private function get($url, $query){ + + try{ + $curlproc = curl_init(); + + $url = str_replace("{searchTerms}", urlencode($query), $url); + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/116.0", + "Accept: application/json, text/javascript, */*; q=0.01", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Connection: keep-alive", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-site"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + + }catch(Exception $error){ + + do404("Curl error: " . $error->getMessage()); + } + } + + private function do404($error){ + + echo json_encode( + ["error" => $error], + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE + ); + die(); + } + + private function doempty(){ + + echo json_encode( + [ + $_GET["s"], + [] + ], + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE + ); + die(); + } +} diff --git a/api/v1/images.php b/api/v1/images.php new file mode 100644 index 0000000..de2c5a9 --- /dev/null +++ b/api/v1/images.php @@ -0,0 +1,39 @@ +<?php + +chdir("../../"); +header("Content-Type: application/json"); + +include "data/config.php"; +if(config::API_ENABLED === false){ + + echo json_encode(["status" => "The server administrator disabled the API!"]); + return; +} + +include "lib/frontend.php"; +$frontend = new frontend(); + +/* + Captcha +*/ +include "lib/bot_protection.php"; +$null = null; +new bot_protection($null, $null, $null, "images", false); + +[$scraper, $filters] = $frontend->getscraperfilters( + "images", + isset($_GET["scraper"]) ? $_GET["scraper"] : null +); + +$get = $frontend->parsegetfilters($_GET, $filters); + +try{ + echo json_encode( + $scraper->image($get), + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE + ); + +}catch(Exception $e){ + + echo json_encode(["status" => $e->getMessage()]); +} diff --git a/api/v1/index.php b/api/v1/index.php new file mode 100644 index 0000000..dae86ab --- /dev/null +++ b/api/v1/index.php @@ -0,0 +1,10 @@ +<?php + +header("Content-Type: application/json"); +http_response_code(404); + +echo json_encode( + [ + "status" => "Unknown endpoint" + ] +); diff --git a/api/v1/music.php b/api/v1/music.php new file mode 100644 index 0000000..58985e3 --- /dev/null +++ b/api/v1/music.php @@ -0,0 +1,39 @@ +<?php + +chdir("../../"); +header("Content-Type: application/json"); + +include "data/config.php"; +if(config::API_ENABLED === false){ + + echo json_encode(["status" => "The server administrator disabled the API!"]); + return; +} + +include "lib/frontend.php"; +$frontend = new frontend(); + +/* + Captcha +*/ +include "lib/bot_protection.php"; +$null = null; +new bot_protection($null, $null, $null, "music", false); + +[$scraper, $filters] = $frontend->getscraperfilters( + "music", + isset($_GET["scraper"]) ? $_GET["scraper"] : null +); + +$get = $frontend->parsegetfilters($_GET, $filters); + +try{ + echo json_encode( + $scraper->music($get), + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE + ); + +}catch(Exception $e){ + + echo json_encode(["status" => $e->getMessage()]); +} diff --git a/api/v1/news.php b/api/v1/news.php new file mode 100644 index 0000000..ab38781 --- /dev/null +++ b/api/v1/news.php @@ -0,0 +1,39 @@ +<?php + +chdir("../../"); +header("Content-Type: application/json"); + +include "data/config.php"; +if(config::API_ENABLED === false){ + + echo json_encode(["status" => "The server administrator disabled the API!"]); + return; +} + +include "lib/frontend.php"; +$frontend = new frontend(); + +/* + Captcha +*/ +include "lib/bot_protection.php"; +$null = null; +new bot_protection($null, $null, $null, "news", false); + +[$scraper, $filters] = $frontend->getscraperfilters( + "news", + isset($_GET["scraper"]) ? $_GET["scraper"] : null +); + +$get = $frontend->parsegetfilters($_GET, $filters); + +try{ + echo json_encode( + $scraper->news($get), + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE + ); + +}catch(Exception $e){ + + echo json_encode(["status" => $e->getMessage()]); +} diff --git a/api/v1/videos.php b/api/v1/videos.php new file mode 100644 index 0000000..1d23780 --- /dev/null +++ b/api/v1/videos.php @@ -0,0 +1,39 @@ +<?php + +chdir("../../"); +header("Content-Type: application/json"); + +include "data/config.php"; +if(config::API_ENABLED === false){ + + echo json_encode(["status" => "The server administrator disabled the API!"]); + return; +} + +include "lib/frontend.php"; +$frontend = new frontend(); + +/* + Captcha +*/ +include "lib/bot_protection.php"; +$null = null; +new bot_protection($null, $null, $null, "videos", false); + +[$scraper, $filters] = $frontend->getscraperfilters( + "videos", + isset($_GET["scraper"]) ? $_GET["scraper"] : null +); + +$get = $frontend->parsegetfilters($_GET, $filters); + +try{ + echo json_encode( + $scraper->video($get), + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE + ); + +}catch(Exception $e){ + + echo json_encode(["status" => $e->getMessage()]); +} diff --git a/api/v1/web.php b/api/v1/web.php new file mode 100644 index 0000000..6a9c030 --- /dev/null +++ b/api/v1/web.php @@ -0,0 +1,52 @@ +<?php + +chdir("../../"); +header("Content-Type: application/json"); + +include "data/config.php"; +if(config::API_ENABLED === false){ + + echo json_encode(["status" => "The server administrator disabled the API!"]); + return; +} + +include "lib/frontend.php"; +$frontend = new frontend(); + +/* + Captcha +*/ +include "lib/bot_protection.php"; +$null = null; +new bot_protection($null, $null, $null, "web", false); + +[$scraper, $filters] = $frontend->getscraperfilters( + "web", + isset($_GET["scraper"]) ? $_GET["scraper"] : null +); + +$get = $frontend->parsegetfilters($_GET, $filters); + +if( + isset($_GET["extendedsearch"]) && + $_GET["extendedsearch"] == "yes" +){ + + $get["extendedsearch"] = "yes"; +}else{ + + $get["extendedsearch"] = "no"; +} + +try{ + + echo + json_encode( + $scraper->web($get), + JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE + ); + +}catch(Exception $e){ + + echo json_encode(["status" => $e->getMessage()]); +} diff --git a/audio/linear.php b/audio/linear.php new file mode 100644 index 0000000..b6a848f --- /dev/null +++ b/audio/linear.php @@ -0,0 +1,20 @@ +<?php + +if(!isset($_GET["s"])){ + + http_response_code(404); + header("X-Error: No SOUND(s) provided!"); + die(); +} + +include "../data/config.php"; +include "../lib/curlproxy.php"; +$proxy = new proxy(); + +try{ + + $proxy->stream_linear_audio($_GET["s"]); +}catch(Exception $error){ + + header("X-Error: " . $error->getMessage()); +} diff --git a/audio/sc.php b/audio/sc.php new file mode 100644 index 0000000..6dfe66e --- /dev/null +++ b/audio/sc.php @@ -0,0 +1,224 @@ +<?php + +new sc_audio(); + +class sc_audio{ + + public function __construct(){ + + include "../data/config.php"; + include "../lib/curlproxy.php"; + $this->proxy = new proxy(); + + if(isset($_GET["u"])){ + + /* + we're now proxying audio + */ + $viewkey = $_GET["u"]; + + if(!isset($_GET["r"])){ + + $this->do404("Ranges(r) are missing"); + } + + $ranges = explode(",", $_GET["r"]); + + // sanitize ranges + foreach($ranges as &$range){ + + if(!is_numeric($range)){ + + $this->do404("Invalid range specified"); + } + + $range = (int)$range; + } + + // sort ranges (just to make sure) + sort($ranges); + + // convert ranges to pairs + $last = -1; + foreach($ranges as &$r){ + + $tmp = $r; + $r = [$last + 1, $r]; + + $last = $tmp; + } + + $browser_headers = getallheaders(); + + // get the requested range from client + $client_range = 0; + foreach($browser_headers as $key => $value){ + + if(strtolower($key) == "range"){ + + preg_match( + '/bytes=([0-9]+)/', + $value, + $client_regex + ); + + if(isset($client_regex[1])){ + + $client_range = (int)$client_regex[1]; + }else{ + + $client_range = 0; + } + break; + } + } + + if( + $client_range < 0 || + $client_range > $ranges[count($ranges) - 1][1] + ){ + + // range is not satisfiable + http_response_code(416); + header("Content-Type: text/plain"); + die(); + } + + $rng = null; + for($i=0; $i<count($ranges); $i++){ + + if($ranges[$i][0] <= $client_range){ + + $rng = $ranges[$i]; + } + } + + // proxy data! + http_response_code(206); // partial content + header("Accept-Ranges: bytes"); + header("Content-Range: bytes {$rng[0]}-{$rng[1]}/" . ($ranges[count($ranges) - 1][1] + 1)); + + $viewkey = + preg_replace( + '/\/media\/([0-9]+)\/[0-9]+\/[0-9]+/', + '/media/$1/' . $rng[0] . '/' . $rng[1], + $viewkey + ); + + try{ + + $this->proxy->stream_linear_audio( + $viewkey + ); + }catch(Exception $error){ + + $this->do404("Could not read stream"); + } + + die(); + } + + /* + redirect user to correct resource + we need to scrape and store the byte positions in the result URL + */ + if(!isset($_GET["s"])){ + + $this->do404("The URL(s) parameter is missing"); + } + + $viewkey = $_GET["s"]; + + if( + preg_match( + '/soundcloud\.com$/', + parse_url($viewkey, PHP_URL_HOST) + ) === false + ){ + + $this->do404("This endpoint can only be used for soundcloud streams"); + } + + try{ + + $json = $this->proxy->get($viewkey)["body"]; + }catch(Exception $error){ + + $this->do404("Curl error: " . $error->getMessage()); + } + + $json = json_decode($json, true); + + if(!isset($json["url"])){ + + $this->do404("Could not get URL from JSON"); + } + + $viewkey = $json["url"]; + + $m3u8 = $this->proxy->get($viewkey)["body"]; + + $m3u8 = explode("\n", $m3u8); + + $lineout = null; + $streampos_arr = []; + foreach($m3u8 as $line){ + + $line = trim($line); + if($line[0] == "#"){ + + continue; + } + + if($lineout === null){ + $lineout = $line; + } + + preg_match( + '/\/media\/[0-9]+\/([0-9]+)\/([0-9]+)/', + $line, + $matches + ); + + if(isset($matches[0])){ + + $streampos_arr[] = [ + (int)$matches[1], + (int)$matches[2] + ]; + } + } + + if($lineout === null){ + + $this->do404("Could not get stream URL"); + } + + $lineout = + preg_replace( + '/\/media\/([0-9]+)\/[0-9]+\/[0-9]+/', + '/media/$1/0/0', + $lineout + ); + + $streampos = []; + + foreach($streampos_arr as $pos){ + + $streampos[] = $pos[1]; + } + + $streampos = implode(",", $streampos); + + header("Location: /audio/sc?u=" . urlencode($lineout) . "&r=$streampos"); + header("Accept-Ranges: bytes"); + } + + private function do404($error){ + + http_response_code(404); + header("Content-Type: text/plain"); + header("X-Error: $error"); + die(); + } +} diff --git a/audio/seekable.php b/audio/seekable.php new file mode 100644 index 0000000..b6a848f --- /dev/null +++ b/audio/seekable.php @@ -0,0 +1,20 @@ +<?php + +if(!isset($_GET["s"])){ + + http_response_code(404); + header("X-Error: No SOUND(s) provided!"); + die(); +} + +include "../data/config.php"; +include "../lib/curlproxy.php"; +$proxy = new proxy(); + +try{ + + $proxy->stream_linear_audio($_GET["s"]); +}catch(Exception $error){ + + header("X-Error: " . $error->getMessage()); +} diff --git a/audio/spotify.php b/audio/spotify.php new file mode 100644 index 0000000..dc8fae6 --- /dev/null +++ b/audio/spotify.php @@ -0,0 +1,214 @@ +<?php + +include "../data/config.php"; +new spotify(); + +class spotify{ + + public function __construct(){ + + include "../lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + + if( + !isset($_GET["s"]) || + !preg_match( + '/^(track|episode)\.([A-Za-z0-9]{22})$/', + $_GET["s"], + $matches + ) + ){ + + $this->do404("The track ID(s) parameter is missing or invalid"); + } + + try{ + + if($matches[1] == "episode"){ + + $uri = "show"; + }else{ + + $uri = $matches[1]; + } + + $embed = + $this->get("https://embed.spotify.com/{$uri}/" . $matches[2]); + }catch(Exception $error){ + + $this->do404("Failed to fetch embed data"); + } + + $this->fuckhtml->load($embed); + + $json = + $this->fuckhtml + ->getElementById( + "__NEXT_DATA__", + "script" + ); + + if($json === null){ + + $this->do404("Failed to extract JSON"); + } + + $json = + json_decode($json["innerHTML"], true); + + if($json === null){ + + $this->do404("Failed to decode JSON"); + } + + switch($matches[1]){ + + case "track": + if( + isset( + $json + ["props"] + ["pageProps"] + ["state"] + ["data"] + ["entity"] + ["audioPreview"] + ["url"] + ) + ){ + + header("Content-type: audio/mpeg"); + header( + "Location: /audio/linear?s=" . + urlencode( + $json + ["props"] + ["pageProps"] + ["state"] + ["data"] + ["entity"] + ["audioPreview"] + ["url"] + ) + ); + }else{ + + $this->do404("Could not extract playback URL"); + } + break; + + case "episode": + if( + isset( + $json + ["props"] + ["pageProps"] + ["state"] + ["data"] + ["entity"] + ["id"] + ) + ){ + + try{ + $json = + $this->get( + "https://spclient.wg.spotify.com/soundfinder/v1/unauth/episode/" . + $json + ["props"] + ["pageProps"] + ["state"] + ["data"] + ["entity"] + ["id"] . + "/com.widevine.alpha" + ); + }catch(Exception $error){ + + $this->do404("Failed to fetch audio resource"); + } + + $json = json_decode($json, true); + + if($json === null){ + + $this->do404("Failed to decode audio resource JSON"); + } + + if( + isset($json["passthrough"]) && + $json["passthrough"] == "ALLOWED" && + isset($json["passthroughUrl"]) + ){ + + header( + "Location:" . + "/audio/linear.php?s=" . + urlencode( + str_replace( + "http://", + "https://", + $json["passthroughUrl"] + ) + ) + ); + }else{ + + $this->do404("Failed to find passthroughUrl"); + } + + }else{ + + $this->do404("Failed to find episode ID"); + } + break; + } + } + + private function get($url){ + + $headers = [ + "User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1" + ]; + + $curlproc = curl_init(); + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + private function do404($error){ + + http_response_code(404); + header("Content-Type: text/plain"); + header("X-Error: $error"); + die(); + } +} diff --git a/banner/4get-default.png b/banner/4get-default.png Binary files differnew file mode 100644 index 0000000..c075175 --- /dev/null +++ b/banner/4get-default.png diff --git a/captcha.php b/captcha.php new file mode 100755 index 0000000..286a277 --- /dev/null +++ b/captcha.php @@ -0,0 +1,203 @@ +<?php + +if( + isset($_GET["v"]) === false || + is_array($_GET["v"]) === true || + preg_match( + '/^c[0-9]+\.[A-Za-z0-9_]{20}$/', + $_GET["v"] + ) === 0 +){ + + http_response_code(401); + header("Content-Type: text/plain"); + echo "Fuck my feathered cloaca"; + die(); +} + +//header("Content-Type: image/jpeg"); +include "data/config.php"; + +if(config::BOT_PROTECTION !== 1){ + + header("Content-Type: text/plain"); + echo "The IQ test is disabled"; + die(); +} + +$grid = apcu_fetch($_GET["v"]); + +if($grid !== false){ + + // captcha already generated + http_response_code(304); // not modified + die(); +} + +header("Content-Type: image/jpeg"); +header("Last-Modified: Thu, 01 Oct 1970 00:00:00 GMT"); + +// ** generate captcha data +// get the positions for the answers +// will return between 3 and 6 answer positions +$range = range(0, 15); +$answer_pos = []; + +array_splice($range, 0, 1); + +$picks = random_int(3, 6); + +for($i=0; $i<$picks; $i++){ + + $answer_pos_tmp = + array_splice( + $range, + random_int( + 0, + 14 - $i + ), + 1 + ); + + $answer_pos[] = $answer_pos_tmp[0]; +} + +// choose a dataset +$c = count(config::CAPTCHA_DATASET); +$choosen = config::CAPTCHA_DATASET[random_int(0, $c - 1)]; +$choices = []; + +for($i=0; $i<$c; $i++){ + + if(config::CAPTCHA_DATASET[$i][0] == $choosen[0]){ + + continue; + } + + $choices[] = config::CAPTCHA_DATASET[$i]; +} + +// generate grid data +$grid = []; + +for($i=0; $i<16; $i++){ + + if(in_array($i, $answer_pos)){ + + $grid[] = $choosen; + }else{ + + $grid[] = $choices[random_int(0, count($choices) - 1)]; + } +} + +// store grid data for form validation on captcha_gen.php +apcu_store( + $_GET["v"], + $answer_pos, + 60 // we give user 1 minute to solve +); + +// generate image +if(random_int(0,1) === 0){ + + $theme = [ + "bg" => "#ebdbb2", + "fg" => "#1d2021" + ]; +}else{ + + $theme = [ + "bg" => "#1d2021", + "fg" => "#ebdbb2" + ]; +} + +$im = new Imagick(); +$im->newImage(400, 427, $theme["bg"]); +$im->setImageBackgroundColor($theme["bg"]); +$im->setImageFormat("jpg"); + +$noise = [ + imagick::NOISE_GAUSSIAN, + imagick::NOISE_LAPLACIAN +]; + +$distort = [ + imagick::DISTORTION_AFFINE, + imagick::DISTORTION_SHEPARDS +]; + +$i = 0; +for($y=0; $y<4; $y++){ + + for($x=0; $x<4; $x++){ + + $tmp = new Imagick("./data/captcha/" . $grid[$i][0] . "/" . random_int(1, $grid[$i][1]) . ".png"); + + // convert transparency correctly + $tmp->setImageBackgroundColor("black"); + $tmp->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE); + + // randomly mirror + if(random_int(0,1) === 1){ + + $tmp->flopImage(); + } + + // distort $tmp + $tmp->distortImage( + $distort[random_int(0,1)], + [ + 0, 0, + random_int(-15, 15), random_int(-15, 15), + + 100, 0, + random_int(80, 120), random_int(-15, 15), + + 100, 100, + random_int(80, 120), random_int(80, 120), + + 0, 100, + random_int(-15, 15), random_int(80, 120) + ], + false + ); + + $tmp->addNoiseImage($noise[random_int(0, 1)]); + + // append image + $im->compositeImage($tmp->getImage(), Imagick::COMPOSITE_DEFAULT, $x * 100, ($y * 100) + 27); + + $i++; + } +} + +// add text +$draw = new ImagickDraw(); +$draw->setFontSize(20); +$draw->setFillColor($theme["fg"]); +//$draw->setTextAntialias(false); +$draw->setFont("./data/fonts/captcha.ttf"); + +$text = "Pick " . $picks . " images of " . str_replace("_", " ", $choosen[0]); + +$pos = 200 - ($im->queryFontMetrics($draw, $text)["textWidth"] / 2); + +for($i=0; $i<strlen($text); $i++){ + + $im->annotateImage( + $draw, + $pos, + 20, + random_int(-15, 15), + $text[$i] + ); + + $pos += $im->queryFontMetrics($draw, $text[$i])["textWidth"]; + +} + +$im->setFormat("jpeg"); +$im->setImageCompressionQuality(90); +echo $im->getImageBlob(); diff --git a/data/config.php b/data/config.php new file mode 100644 index 0000000..2fd47aa --- /dev/null +++ b/data/config.php @@ -0,0 +1,178 @@ +<?php +class config{ + // Welcome to the 4get configuration file + // When updating your instance, please make sure this file isn't missing + // any parameters. + + // 4get version. Please keep this updated + const VERSION = 8; + + // Will be shown pretty much everywhere. + const SERVER_NAME = "4get"; + + // Will be shown in <meta> tag on home page + const SERVER_SHORT_DESCRIPTION = "4get is a proxy search engine that doesn't suck."; + + // Will be shown in server list ping (null for no description) + const SERVER_LONG_DESCRIPTION = null; + + // Add your own themes in "static/themes". Set to "Dark" for default theme. + // Eg. To use "static/themes/Cream.css", specify "Cream". + const DEFAULT_THEME = "Dark"; + + // Enable the API? + const API_ENABLED = true; + + // + // BOT PROTECTION + // + + // 0 = disabled, 1 = ask for image captcha, @TODO: 2 = invite only (users needs a pass) + // VERY useful against a targetted attack + const BOT_PROTECTION = 0; + + // if BOT_PROTECTION is set to 1, specify the available datasets here + // images should be named from 1.png to X.png, and be 100x100 in size + // Eg. data/captcha/birds/1.png up to 2263.png + const CAPTCHA_DATASET = [ + // example: + //["birds", 2263], + //["fumo_plushies", 1006], + //["minecraft", 848] + ]; + + // If this regex expression matches on the user agent, it blocks the request + // Not useful at all against a targetted attack + const HEADER_REGEX = '/bot|wget|curl|python-requests|scrapy|go-http-client|ruby|yahoo|spider|qwant/i'; + + // Block clients who present any of the following headers in their request (SPECIFY IN !!lowercase!!) + // Eg: ["x-forwarded-for", "x-via", "forwarded-for", "via"]; + // Useful for blocking *some* proxies used for botting + const FILTERED_HEADER_KEYS = [ + //"x-forwarded-for", + //"x-cluster-client-ip", + //"x-client-ip", + //"x-real-ip", + //"client-ip", + //"real-ip", + //"forwarded-for", + //"forwarded-for-ip", + //"forwarded", + //"proxy-connection", + //"remote-addr", + //"via" + ]; + + // Block SSL ciphers used by CLI tools used for botting + // Basically a primitive version of Cloudflare's browser integrity check + // ** If curl can still access the site (with spoofed headers), please make sure you use the new apache2 config ** + // https://git.lolcat.ca/lolcat/4get/docs/apache2.md + const DISALLOWED_SSL = [ + // "TLS_AES_256_GCM_SHA384" // used by WGET and CURL + ]; + + // Maximal number of searches per captcha key/pass issued. Counter gets + // reset on every APCU cache clear (should happen once a day). + // Only useful when BOT_PROTECTION is NOT set to 0 + const MAX_SEARCHES = 100; + + // List of domains that point to your servers. Include your tor/i2p + // addresses here! Must be a valid URL. Won't affect links placed on + // the homepage. + const ALT_ADDRESSES = [ + //"https://4get.alt-tld", + //"http://4getwebfrq5zr4sxugk6htxvawqehxtdgjrbcn2oslllcol2vepa23yd.onion" + ]; + + // Known 4get instances. MUST use the https protocol if your instance uses + // it. Is used to generate a distributed list of instances. + // To appear in the list of an instance, contact the host and if everyone added + // eachother your serber should appear everywhere. + const INSTANCES = [ + "https://4get.ca", + "https://4get.zzls.xyz", + "https://4getus.zzls.xyz", + "https://4get.silly.computer", + "https://4get.konakona.moe", + "https://4get.lvkaszus.pl", + "https://4g.ggtyler.dev", + "https://4get.perennialte.ch", + "https://4get.sijh.net", + "https://4get.hbubli.cc", + "https://4get.plunked.party", + "https://4get.etenie.pl", + "https://4get.lunar.icu", + "https://4get.dcs0.hu", + "https://4get.kizuki.lol", + "https://4get.psily.garden", + "https://search.milivojevic.in.rs", + "https://4get.snine.nl", + "https://4get.datura.network", + "https://4get.neco.lol", + "https://4get.lol", + "https://4get.ch", + "https://4get.edmateo.site", + "https://4get.sudovanilla.org", + "https://search.mint.lgbt" + ]; + + // Default user agent to use for scraper requests. Sometimes ignored to get specific webpages + // Changing this might break things. + const USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:141.0) Gecko/20100101 Firefox/141.0"; + + // Proxy pool assignments for each scraper + // false = Use server's raw IP + // string = will load a proxy list from data/proxies + // Eg. "onion" will load data/proxies/onion.txt + const PROXY_DDG = false; // duckduckgo + const PROXY_BRAVE = false; + const PROXY_FB = false; // facebook + const PROXY_GOOGLE = false; + const PROXY_GOOGLE_API = false; + const PROXY_GOOGLE_CSE = false; + const PROXY_STARTPAGE = false; + const PROXY_QWANT = false; + const PROXY_BAIDU = false; + const PROXY_COCCOC = false; + const PROXY_GHOSTERY = false; + const PROXY_MARGINALIA = false; + const PROXY_MOJEEK = false; + const PROXY_SC = false; // soundcloud + const PROXY_SPOTIFY = false; + const PROXY_SOLOFIELD = false; + const PROXY_WIBY = false; + const PROXY_CURLIE = false; + const PROXY_YT = false; // youtube + const PROXY_SEPIASEARCH = false; + const PROXY_ODYSEE = false; + const PROXY_VIMEO = false; + const PROXY_YEP = false; + const PROXY_PINTEREST = false; + const PROXY_SANKAKUCOMPLEX = false; + const PROXY_FLICKR = false; + const PROXY_FIVEHPX = false; + const PROXY_VSCO = false; + const PROXY_SEZNAM = false; + const PROXY_NAVER = false; + const PROXY_GREPPR = false; + const PROXY_CROWDVIEW = false; + const PROXY_MWMBL = false; + const PROXY_FTM = false; // findthatmeme + const PROXY_IMGUR = false; + const PROXY_CARA = false; + const PROXY_YANDEX_W = false; // yandex web + const PROXY_YANDEX_I = false; // yandex images + const PROXY_YANDEX_V = false; // yandex videos + + // + // Scraper-specific parameters + // + + // GOOGLE CSE & GOOGLE API + const GOOGLE_CX_ENDPOINT = "d4e68b99b876541f0"; + + // MARGINALIA + // Use "null" to default out to HTML scraping OR specify a string to + // use the API (Eg: "public"). API has less filters. + const MARGINALIA_API_KEY = null; +} diff --git a/data/fonts/captcha.ttf b/data/fonts/captcha.ttf Binary files differnew file mode 100644 index 0000000..13f5dc7 --- /dev/null +++ b/data/fonts/captcha.ttf diff --git a/data/proxies/.gitignore b/data/proxies/.gitignore new file mode 100644 index 0000000..68f8e48 --- /dev/null +++ b/data/proxies/.gitignore @@ -0,0 +1,3 @@ +* +!.gitignore +!onion.txt diff --git a/data/proxies/onion.txt b/data/proxies/onion.txt new file mode 100644 index 0000000..28ab436 --- /dev/null +++ b/data/proxies/onion.txt @@ -0,0 +1,13 @@ +# Specify proxies by following this format:
+# <protocol>:<address>:<port>:<username>:<password>
+#
+# Examples:
+# https:1.3.3.7:6969:abcd:efg
+# socks4:1.2.3.4:8080::
+# raw_ip::::
+#
+# Available protocols:
+# raw_ip, http, https, socks4, socks5, socks4a, socks5_hostname
+
+# Local tor proxy
+socks5:localhost:9050::
diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..3797294 --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,20 @@ +# example docker-compose.yaml +version: "3.7" + +services: + fourget: + image: luuul/4get:latest + restart: unless-stopped + environment: + - FOURGET_PROTO=http + - FOURGET_SERVER_NAME=4get.ca + - FOURGET_INSTANCES=https://4get.ca + + ports: + - "80:80" + - "443:443" + + # volumes: + # - /etc/letsencrypt/live/domain.tld:/etc/4get/certs # mount ssl + # - ./banners:/var/www/html/4get/banner # mount custom banners + # - ./captcha:/var/www/html/4get/data/captcha # mount captcha images diff --git a/docker/apache/http/conf.d/ssl.conf b/docker/apache/http/conf.d/ssl.conf new file mode 100644 index 0000000..1357f56 --- /dev/null +++ b/docker/apache/http/conf.d/ssl.conf @@ -0,0 +1 @@ +# intentionally blank diff --git a/docker/apache/http/httpd.conf b/docker/apache/http/httpd.conf new file mode 100644 index 0000000..f496ba5 --- /dev/null +++ b/docker/apache/http/httpd.conf @@ -0,0 +1,97 @@ +Listen 80
+ServerTokens OS
+ServerRoot /var/www
+ServerSignature On
+ServerName localhost
+
+DocumentRoot "/var/www/html/4get"
+
+LogLevel warn
+CustomLog /dev/null common
+ErrorLog /dev/null
+
+<Directory "/var/www/html/4get">
+ RewriteEngine On
+ RewriteCond %{THE_REQUEST} ^\w+\ /(.*)\.php(\?.*)?\ HTTP/
+ RewriteRule ^ http://%{HTTP_HOST}/%1 [R=301]
+ RewriteCond %{REQUEST_FILENAME}.php -f
+ RewriteRule .* $0.php
+ Options FollowSymLinks
+ AllowOverride None
+ Require all granted
+</Directory>
+
+# deny access to private resources
+<Directory "/var/www/html/4get/data">
+ Require all denied
+ <Files "*">
+ Require all denied
+ </Files>
+</Directory>
+
+LoadModule rewrite_module modules/mod_rewrite.so
+LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
+LoadModule authn_file_module modules/mod_authn_file.so
+LoadModule authn_core_module modules/mod_authn_core.so
+LoadModule authz_host_module modules/mod_authz_host.so
+LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
+LoadModule authz_user_module modules/mod_authz_user.so
+LoadModule authz_core_module modules/mod_authz_core.so
+LoadModule access_compat_module modules/mod_access_compat.so
+LoadModule auth_basic_module modules/mod_auth_basic.so
+LoadModule reqtimeout_module modules/mod_reqtimeout.so
+LoadModule filter_module modules/mod_filter.so
+LoadModule mime_module modules/mod_mime.so
+LoadModule log_config_module modules/mod_log_config.so
+LoadModule env_module modules/mod_env.so
+LoadModule headers_module modules/mod_headers.so
+LoadModule setenvif_module modules/mod_setenvif.so
+LoadModule version_module modules/mod_version.so
+LoadModule unixd_module modules/mod_unixd.so
+LoadModule status_module modules/mod_status.so
+LoadModule autoindex_module modules/mod_autoindex.so
+LoadModule dir_module modules/mod_dir.so
+LoadModule alias_module modules/mod_alias.so
+LoadModule negotiation_module modules/mod_negotiation.so
+
+<IfModule unixd_module>
+User apache
+Group apache
+</IfModule>
+
+
+
+<Directory />
+ AllowOverride none
+ Require all denied
+</Directory>
+
+
+
+
+<IfModule dir_module>
+ DirectoryIndex index.html
+</IfModule>
+
+<Files ".ht*">
+ Require all denied
+</Files>
+
+
+
+<IfModule headers_module>
+ RequestHeader unset Proxy early
+</IfModule>
+
+<IfModule mime_module>
+ TypesConfig /etc/apache2/mime.types
+ AddType application/x-compress .Z
+ AddType application/x-gzip .gz .tgz
+</IfModule>
+
+<IfModule mime_magic_module>
+ MIMEMagicFile /etc/apache2/magic
+</IfModule>
+
+IncludeOptional /etc/apache2/conf.d/*.conf
+
diff --git a/docker/apache/https/conf.d/ssl.conf b/docker/apache/https/conf.d/ssl.conf new file mode 100644 index 0000000..7b0dd15 --- /dev/null +++ b/docker/apache/https/conf.d/ssl.conf @@ -0,0 +1,19 @@ +LoadModule ssl_module modules/mod_ssl.so +LoadModule socache_shmcb_module modules/mod_socache_shmcb.so + +SSLRandomSeed startup file:/dev/urandom 512 +SSLRandomSeed connect builtin + +Listen 443 + +SSLCipherSuite HIGH:MEDIUM:!MD5:!RC4:!3DES:!ADH +SSLProxyCipherSuite HIGH:MEDIUM:!MD5:!RC4:!3DES:!ADH +SSLHonorCipherOrder on + +SSLProtocol all -SSLv3 +SSLProxyProtocol all -SSLv3 + +SSLPassPhraseDialog builtin + +SSLSessionCache "shmcb:/var/cache/mod_ssl/scache(512000)" +SSLSessionCacheTimeout 300 diff --git a/docker/apache/https/httpd.conf b/docker/apache/https/httpd.conf new file mode 100644 index 0000000..ca5edf5 --- /dev/null +++ b/docker/apache/https/httpd.conf @@ -0,0 +1,102 @@ +ServerTokens OS
+ServerRoot /var/www
+ServerSignature On
+ServerName localhost
+
+DocumentRoot "/var/www/html/4get"
+
+LogLevel warn
+CustomLog /dev/null common
+ErrorLog /dev/null
+
+<VirtualHost *:443>
+ SSLEngine on
+ SSLCertificateFile /etc/4get/certs/fullchain.pem
+ SSLCertificateKeyFile /etc/4get/certs/privkey.pem
+</VirtualHost>
+
+<Directory "/var/www/html/4get">
+ RewriteEngine On
+ RewriteCond %{THE_REQUEST} ^\w+\ /(.*)\.php(\?.*)?\ HTTP/
+ RewriteRule ^ http://%{HTTP_HOST}/%1 [R=301]
+ RewriteCond %{REQUEST_FILENAME}.php -f
+ RewriteRule .* $0.php
+ Options FollowSymLinks
+ AllowOverride None
+ Require all granted
+</Directory>
+
+# deny access to private resources
+<Directory "/var/www/html/4get/data">
+ Require all denied
+ <Files "*">
+ Require all denied
+ </Files>
+</Directory>
+
+LoadModule rewrite_module modules/mod_rewrite.so
+LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
+LoadModule authn_file_module modules/mod_authn_file.so
+LoadModule authn_core_module modules/mod_authn_core.so
+LoadModule authz_host_module modules/mod_authz_host.so
+LoadModule authz_groupfile_module modules/mod_authz_groupfile.so
+LoadModule authz_user_module modules/mod_authz_user.so
+LoadModule authz_core_module modules/mod_authz_core.so
+LoadModule access_compat_module modules/mod_access_compat.so
+LoadModule auth_basic_module modules/mod_auth_basic.so
+LoadModule reqtimeout_module modules/mod_reqtimeout.so
+LoadModule filter_module modules/mod_filter.so
+LoadModule mime_module modules/mod_mime.so
+LoadModule log_config_module modules/mod_log_config.so
+LoadModule env_module modules/mod_env.so
+LoadModule headers_module modules/mod_headers.so
+LoadModule setenvif_module modules/mod_setenvif.so
+LoadModule version_module modules/mod_version.so
+LoadModule unixd_module modules/mod_unixd.so
+LoadModule status_module modules/mod_status.so
+LoadModule autoindex_module modules/mod_autoindex.so
+LoadModule dir_module modules/mod_dir.so
+LoadModule alias_module modules/mod_alias.so
+LoadModule negotiation_module modules/mod_negotiation.so
+
+<IfModule unixd_module>
+User apache
+Group apache
+</IfModule>
+
+
+
+<Directory />
+ AllowOverride none
+ Require all denied
+</Directory>
+
+
+
+
+<IfModule dir_module>
+ DirectoryIndex index.html
+</IfModule>
+
+<Files ".ht*">
+ Require all denied
+</Files>
+
+
+
+<IfModule headers_module>
+ RequestHeader unset Proxy early
+</IfModule>
+
+<IfModule mime_module>
+ TypesConfig /etc/apache2/mime.types
+ AddType application/x-compress .Z
+ AddType application/x-gzip .gz .tgz
+</IfModule>
+
+<IfModule mime_magic_module>
+ MIMEMagicFile /etc/apache2/magic
+</IfModule>
+
+IncludeOptional /etc/apache2/conf.d/*.conf
+
diff --git a/docker/docker-entrypoint.sh b/docker/docker-entrypoint.sh new file mode 100755 index 0000000..53e7654 --- /dev/null +++ b/docker/docker-entrypoint.sh @@ -0,0 +1,34 @@ +#!/bin/sh +set -e + +# remove quotes from variable if present +FOURGET_PROTO="${FOURGET_PROTO%\"}" +FOURGET_PROTO="${FOURGET_PROTO#\"}" + +# make lowercase +FOURGET_PROTO=`echo $FOURGET_PROTO | awk '{print tolower($0)}'` + +FOURGET_SRC='/var/www/html/4get' + +mkdir -p /etc/apache2 + +if [ "$FOURGET_PROTO" = "https" ]; then + echo "Using https configuration" + cp -r ${FOURGET_SRC}/docker/apache/https/httpd.conf /etc/apache2 + cp -r ${FOURGET_SRC}/docker/apache/https/conf.d/* /etc/apache2/conf.d + +else + echo "Using http configuration" + cp -r ${FOURGET_SRC}/docker/apache/http/httpd.conf /etc/apache2 + cp -r ${FOURGET_SRC}/docker/apache/http/conf.d/* /etc/apache2/conf.d +fi + +php ./docker/gen_config.php + +if [ "$@" = "start" ]; then + echo "4get is running" + exec httpd -DFOREGROUND +else + exec "$@" +fi + diff --git a/docker/gen_config.php b/docker/gen_config.php new file mode 100644 index 0000000..b9e7730 --- /dev/null +++ b/docker/gen_config.php @@ -0,0 +1,90 @@ + <?php + +include "/var/www/html/4get/data/config.php"; + +$refl = new ReflectionClass('config'); +$from_config = ($refl->getConstants()); +$from_env = array(); + +$env = getenv(); +$fourget_env = array_filter($env, function($v, $k) { + return str_starts_with($k, "FOURGET"); +}, ARRAY_FILTER_USE_BOTH); + +foreach($fourget_env as $key => $val) { + $target_key = preg_replace('/^FOURGET_/', '', $key); + $from_env[$target_key] = trim($val, '\'"'); +}; + +$merged_config = array_merge($from_config, $from_env); + +function type_to_string($n) { + $type = gettype($n); + if ($type === "NULL") { + return "null"; + } + if ($type === "boolean") { + return $n ? 'true' : 'false'; + } + if ($type === "string") { + if(is_numeric($n)) { + return $n; + } + return "\"$n\""; + } + if ($type === "array") { + return json_encode($n, JSON_UNESCAPED_SLASHES); + } + return $n; +} + + +function detect_captcha_dirs() { + $captcha_dir = "/var/www/html/4get/data/captcha/"; + $categories = (array_map(function ($n) { + return explode("/", $n)[7]; + }, glob($captcha_dir . "*"))); + + + $result = array_map(function($category) { + return [$category, count(glob("/var/www/html/4get/data/captcha/" . $category . "/*" ))]; + }, $categories); + + return $result; +} + + +$special_keys = ["PROTO", "CAPTCHA_DATASET"]; + +$output = "<?php\n // This file was generated by docker/gen_config.php\n"; + +$output = $output . "class config {\n"; +foreach(($merged_config) as $key => $val){ + if(!in_array($key, $special_keys)) { + $stored_value = $val; + // conversion between arrays and comma separated env value. + // Handle case when original type of field is array and there is a type mismatch when a comma separted string is passed, + // then split on comma if string (and not numeric, boolean, null, etc) + // + // except in the case where the inital value in default config is null or boolean. Assuming null and boolean + // in default config will be never be assigned an array + + if(gettype($from_config[$key]) != gettype($val) && !is_numeric($val) && !is_null($from_config[$key]) && gettype($from_config[$key]) != "boolean") { + $stored_value = explode(",", $val); + } + $output = $output . "\tconst " . $key . " = " . type_to_string($stored_value) . ";\n"; + + continue; + } + + + if($key === "CAPTCHA_DATASET") { + $output = $output . "\tconst " . $key . " = " . type_to_string(detect_captcha_dirs()) . ";\n"; + } +} + +$output = $output . "}\n"; +$output = $output . "?>"; + +file_put_contents("./data/config.php", $output); +?> diff --git a/docker/tor/Dockerfile b/docker/tor/Dockerfile new file mode 100644 index 0000000..9310f68 --- /dev/null +++ b/docker/tor/Dockerfile @@ -0,0 +1,18 @@ +FROM alpine:edge + +RUN apk add --no-cache curl tor + +EXPOSE 9050 + +HEALTHCHECK --interval=60s --timeout=15s --start-period=20s \ + CMD curl -x socks5h://127.0.0.1:9050 'https://check.torproject.org/api/ip' | grep -qm1 -E '"IsTor"\s*:\s*true' + + +# default owner is tor, but running as root to avoid docker volume mount issue +RUN chown -R root:root /var/lib/tor + +VOLUME ["/var/lib/tor/4get"] + +COPY ./torrc /etc/tor/torrc + +ENTRYPOINT ["/usr/bin/tor"] diff --git a/docker/tor/torrc b/docker/tor/torrc new file mode 100644 index 0000000..da32a7a --- /dev/null +++ b/docker/tor/torrc @@ -0,0 +1 @@ +SocksPort 0.0.0.0:9050 diff --git a/docs/apache2-example.md b/docs/apache2-example.md new file mode 100644 index 0000000..09f5c1d --- /dev/null +++ b/docs/apache2-example.md @@ -0,0 +1,195 @@ +# Sample Apache2 configuration +This is the apache2 configuration file used on the 4get.ca official instance, in hopes that it's useful to you! + +Looking for the apache2 guide? <a href="https://git.lolcat.ca/lolcat/4get/src/branch/master/docs/apache2.md">go here.</a>. + +```xml +<VirtualHost *:443> + ServerName www.4get.ca + + SSLEngine On + SSLCertificateFile /etc/letsencrypt/live/4get.ca/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/4get.ca/privkey.pem + SSLCertificateChainFile /etc/letsencrypt/live/4get.ca/chain.pem + + RedirectMatch 301 ^(.*)$ https://4get.ca$1 +</VirtualHost> + +<VirtualHost *:443> + ServerName 4get.ca + + ServerAdmin will@lolcat.ca + DocumentRoot /var/www/4get + + SSLEngine On + SSLOptions +StdEnvVars + + #ErrorLog ${APACHE_LOG_DIR}/error.log + + AddOutputFilterByType DEFLATE application/json + AddOutputFilterByType DEFLATE application/javascript + AddOutputFilterByType DEFLATE application/x-javascript + AddOutputFilterByType DEFLATE text/html + AddOutputFilterByType DEFLATE text/plain + AddOutputFilterByType DEFLATE text/css + + SSLCertificateFile /etc/letsencrypt/live/4get.ca/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/4get.ca/privkey.pem + SSLCertificateChainFile /etc/letsencrypt/live/4get.ca/chain.pem + + <Directory /var/www/4get> + Options -MultiViews + AllowOverride All + Require all granted + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^([^\.]+)$ $1.php [NC,L] + </Directory> + + # deny access to private resources + <Directory /var/www/4get/data/> + Order Deny,allow + Deny from all + </Directory> +</VirtualHost> + +<VirtualHost *:443> + ServerName www.lolcat.ca + + SSLEngine On + SSLCertificateFile /etc/letsencrypt/live/4get.ca/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/4get.ca/privkey.pem + SSLCertificateChainFile /etc/letsencrypt/live/4get.ca/chain.pem + + RedirectMatch 301 ^(.*)$ https://lolcat.ca$1 +</VirtualHost> + +<VirtualHost *:443> + ServerName lolcat.ca + + ServerAdmin will@lolcat.ca + DocumentRoot /var/www/lolcat + + SSLEngine On + SSLOptions +StdEnvVars + + #ErrorLog ${APACHE_LOG_DIR}/error.log + + AddOutputFilterByType DEFLATE application/json + AddOutputFilterByType DEFLATE application/javascript + AddOutputFilterByType DEFLATE application/x-javascript + AddOutputFilterByType DEFLATE text/html + AddOutputFilterByType DEFLATE text/plain + AddOutputFilterByType DEFLATE text/css + + SSLCertificateFile /etc/letsencrypt/live/4get.ca/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/4get.ca/privkey.pem + SSLCertificateChainFile /etc/letsencrypt/live/4get.ca/chain.pem + + <Directory /var/www/lolcat> + Options -MultiViews + AllowOverride All + Require all granted + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^([^\.]+)$ $1.php [NC,L] + </Directory> +</VirtualHost> + +<VirtualHost *:443> + ServerName www.nyym.co + + SSLEngine On + SSLCertificateFile /etc/letsencrypt/live/nyym.co/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/nyym.co/privkey.pem + SSLCertificateChainFile /etc/letsencrypt/live/nyym.co/chain.pem + + RedirectMatch 301 ^(.*)$ https://nyym.co$1 +</VirtualHost> + +<VirtualHost *:443> + ServerName nyym.co + + ServerAdmin will@lolcat.ca + DocumentRoot /var/www/nyym + + SSLEngine On + SSLOptions +StdEnvVars + + #ErrorLog ${APACHE_LOG_DIR}/error.log + + AddOutputFilterByType DEFLATE application/json + AddOutputFilterByType DEFLATE application/javascript + AddOutputFilterByType DEFLATE application/x-javascript + AddOutputFilterByType DEFLATE text/html + AddOutputFilterByType DEFLATE text/plain + AddOutputFilterByType DEFLATE text/css + + SSLCertificateFile /etc/letsencrypt/live/nyym.co/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/nyym.co/privkey.pem + SSLCertificateChainFile /etc/letsencrypt/live/nyym.co/chain.pem + + <Directory /var/www/nyym> + Options -MultiViews + AllowOverride All + Require all granted + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^([^\.]+)$ $1.php [NC,L] + </Directory> +</VirtualHost> + +<VirtualHost *:443> + ServerName git.lolcat.ca + + SSLEngine On + SSLOptions +StdEnvVars + + #ErrorLog ${APACHE_LOG_DIR}/error.log + + AddOutputFilterByType DEFLATE application/json + AddOutputFilterByType DEFLATE application/javascript + AddOutputFilterByType DEFLATE application/x-javascript + AddOutputFilterByType DEFLATE text/html + AddOutputFilterByType DEFLATE text/plain + AddOutputFilterByType DEFLATE text/css + + SSLCertificateFile /etc/letsencrypt/live/4get.ca/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/4get.ca/privkey.pem + SSLCertificateChainFile /etc/letsencrypt/live/4get.ca/chain.pem + + ProxyPreserveHost On + ProxyRequests off + AllowEncodedSlashes NoDecode + ProxyPass / http://localhost:3000/ nocanon +</VirtualHost> + +<VirtualHost *:443> + ServerName live.lolcat.ca + + ServerAdmin will@lolcat.ca + DocumentRoot /var/www/live + + SSLEngine On + SSLOptions +StdEnvVars + + #ErrorLog ${APACHE_LOG_DIR}/error.log + + AddOutputFilterByType DEFLATE application/json + AddOutputFilterByType DEFLATE application/javascript + AddOutputFilterByType DEFLATE application/x-javascript + AddOutputFilterByType DEFLATE text/html + AddOutputFilterByType DEFLATE text/plain + AddOutputFilterByType DEFLATE text/css + + SSLCertificateFile /etc/letsencrypt/live/4get.ca/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/4get.ca/privkey.pem + SSLCertificateChainFile /etc/letsencrypt/live/4get.ca/chain.pem +</VirtualHost> +``` diff --git a/docs/apache2.md b/docs/apache2.md new file mode 100644 index 0000000..1e79327 --- /dev/null +++ b/docs/apache2.md @@ -0,0 +1,216 @@ +# Install guide for Apache2 webserver +Welcome to the new and revamped 4get install manual for apache2. Even if you already have services running on an existing installation of apache2, you should still be able to adapt this guide to your needs. + +For starters, login as `root`. + +Then, install the following dependencies: +```sh +apt update +apt upgrade +apt install php-mbstring apache2 certbot php-imagick imagemagick php-curl curl php-apcu git libapache2-mod-php +``` + +Enable the required modules: +```sh +a2enmod ssl +a2enmod rewrite +``` + +And enable these optional ones, which might be useful to you later on. The `proxy` module is useful for setting up reverse proxies to services like gitea, and `headers` is useful to tweak global header values: +```sh +a2enmod proxy +a2enmod headers +``` + +Now, restart apache2: +```sh +service apache2 restart +``` + +Just for good measure, please check if your webserver is running. Access it through HTTP, not HTTPS. You should see the apache2 default landing page. + +## 000-default.conf +Now, edit the following file: `/etc/apache2/sites-available/000-default.conf`, remove everything and carefully add each rule specified here, while making sure to replace my domains with your own: + +1. The `VirtualHost` here instructs apache2 to redirect all **HTTP** traffic that specify an unknown `Host` header be redirected to a specific domain of your choice. Configuring this is not required but highly recommended. +```xml +<VirtualHost *:80> + # no domain = go to 4get.ca + RedirectMatch 301 ^(.*)$ https://4get.ca$1 +</VirtualHost> +``` + +2. This instruction tells apache2 to redirect all HTTP traffic on `Host` lolcat.ca to the HTTPS version of the site. You should add a rule like this for all of your services explicitly. +```xml +<VirtualHost *:80> + ServerName lolcat.ca + RedirectMatch 301 ^(.*)$ https://lolcat.ca$1 +</VirtualHost> +``` + +3. Subdomains won't be matched by the above rule, so I recommend you also add them to be more explicit: +```xml +<VirtualHost *:80> + ServerName www.lolcat.ca + RedirectMatch 301 ^(.*)$ https://lolcat.ca$1 +</VirtualHost> +``` + +... Etc, for every service you own. + +4. And finally, append this configuration if you wish to host a tor or i2p access point. This configuration should not be binded to SSL(443) as Let's Encrypt does not let you create certificates for onion sites: +```xml +<VirtualHost *:80> + # tor site + ServerName 4getwebfrq5zr4sxugk6htxvawqehxtdgjrbcn2oslllcol2vepa23yd.onion + + # compress + AddOutputFilterByType DEFLATE application/json + AddOutputFilterByType DEFLATE application/javascript + AddOutputFilterByType DEFLATE application/x-javascript + AddOutputFilterByType DEFLATE text/html + AddOutputFilterByType DEFLATE text/plain + AddOutputFilterByType DEFLATE text/css + + DocumentRoot /var/www/4get + + Options -MultiViews + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^([^\.]+)$ $1.php [NC,L] + + # deny access to private resources + <Directory /var/www/4get/data/> + Order Deny,allow + Deny from all + </Directory> +</VirtualHost> +``` +To make the above snippet work, please refer to our <a href="https://git.lolcat.ca/lolcat/4get/src/branch/master/docs/tor.md">tor site guide</a>. + +## default-ssl.conf +Now, edit the file `/etc/apache2/sites-available/default-ssl.conf`, remove everything and, again, add each rule while modifying the relevant fields: + +First, append the following redirect rule to point traffic from `www.4get.ca` to `4get.ca`: +```xml +<VirtualHost *:443> + ServerName www.4get.ca + + SSLEngine On + SSLCertificateFile /etc/letsencrypt/live/4get.ca/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/4get.ca/privkey.pem + SSLCertificateChainFile /etc/letsencrypt/live/4get.ca/chain.pem + + RedirectMatch 301 ^(.*)$ https://4get.ca$1 +</VirtualHost> +``` + +This ruleset tells apache2 where 4get is located (`/var/www/4get`), ensures that `4get.ca/settings` resolves to `4get.ca/settings.php` internally and that we deny access to `/data/*`, which may contain files you might want to keep private. `StdEnvVArs+` will make it so that PHP can view if the connection uses HTTPS, and which cipher was used. Useful for basic bot protection. + +Make sure to replace `4get.ca` with your own domain under the `SSLCertificate*` directives! +```xml +<VirtualHost *:443> + ServerName 4get.ca + + ServerAdmin will@lolcat.ca + DocumentRoot /var/www/4get + + SSLEngine On + SSLOptions +StdEnvVars + + #ErrorLog ${APACHE_LOG_DIR}/error.log + + AddOutputFilterByType DEFLATE application/json + AddOutputFilterByType DEFLATE application/javascript + AddOutputFilterByType DEFLATE application/x-javascript + AddOutputFilterByType DEFLATE text/html + AddOutputFilterByType DEFLATE text/plain + AddOutputFilterByType DEFLATE text/css + + SSLCertificateFile /etc/letsencrypt/live/4get.ca/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/4get.ca/privkey.pem + SSLCertificateChainFile /etc/letsencrypt/live/4get.ca/chain.pem + + <Directory /var/www/4get> + Options -MultiViews + AllowOverride All + Require all granted + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^([^\.]+)$ $1.php [NC,L] + </Directory> + + # deny access to private resources + <Directory /var/www/4get/data/> + Order Deny,allow + Deny from all + </Directory> +</VirtualHost> +``` + +By default, the first rule dictates where traffic should be redirected to in case the client specifies an unknown domain name. Don't forget your webserver's other rules! For a complete real-world example, please <a href="https://git.lolcat.ca/lolcat/4get/src/branch/master/docs/apache2-example.md">check out my real-world config file I use on 4get.ca</a>. + +## security.conf +If you enabled the `headers` module, you can head over to `/etc/apache2/conf-enabled/security.conf` and edit: +```sh +ServerTokens Prod # instead off Full +``` +and +```sh +ServerSignature Off #instead of On +``` +This will ensure that the `Server` header apache2 returns is minimal and doesn't leak information like your host system's OS or apache2 version. + +You can also uncomment `Header set X-Content-Type-Options: "nosniff"` and `Header set Content-Security-Policy "frame-ancestors 'self';"` respectively. + +## charset.conf +Head over to `/etc/apache2/conf-enabled/charset.conf` and uncomment `AddDefaultCharset UTF-8`. + +## other-vhost-access-log.conf +Since none of our configuration files contains any `CustomLog` directives, all we need to do to disable logging entirely is comment out the `CustomLog` directive located in `/etc/apache2/conf-enabled/other-vhost-access-log.conf`. Only error logs will remain if you configured them. + +## Symlink everything +Now comes the most important part of the setup. Run +```sh +ln -s /etc/apache2/sites-available/default-ssl.conf /etc/apache2/sites-enabled/default-ssl.conf +``` +Otherwise apache2 will ignore our SSL configuration. Handy, huh? + +# Setup SSL +Great, now we've configured the webserver, but we still don't have our security certificate. Let's generate one! + +First, stop `apache2`. +```sh +service apache2 stop +``` + +Now, run `certbot`, and specify all of your domains by prepending `-d` every time. Make sure the first domain you specify is your main domain, and the same domain you specified in the configuration above! We use ECDSA encryption here as it's better than RSA. +```sh +certbot certonly --standalone --key-type ecdsa -d 4get.ca -d www.4get.ca -d lolcat.ca -d www.lolcat.ca +``` + +Certbot should ask you a few questions, just play along. At the end of the setup, certbot should tell you about the location of the certificates. Double check to make sure they correspond to the paths we specified in `default-ssl.conf`. Your certificates should now update every 2-3 months automatically. + +After this is complete, create a directory in `/var/www/4get`. + +Now, start `apache2`. +```sh +service apache2 start +``` + +Congratulations! You now have a... 404 error on your webserver, if everything went well. Now's the time to make sure all of our redirect rules work! + +# Import the fun junk +Run these commands: +``` +cd /var/www/4get +git clone https://git.lolcat.ca/lolcat/4get +chmod 777 -R icons/ +``` + +... And try accessing your webserver. You should now have a working 4get instance! + +Please make sure to check out how to further <a href="https://git.lolcat.ca/lolcat/4get/src/branch/master/docs/configure.md">configure 4get</a> to your liking! diff --git a/docs/caddy.md b/docs/caddy.md new file mode 100644 index 0000000..90f438c --- /dev/null +++ b/docs/caddy.md @@ -0,0 +1,58 @@ +# Install guide for Caddy webserver + +1. Install dependencies: + +`sudo apt install caddy php8.2-dom php8.2-imagick imagemagick php8.2-curl curl php8.2-apcu git` + +2. Clone this repository where you want to host this from: + +`cd /var/www && sudo git clone https://git.konakona.moe/diowo/4get` + +3. Set permission on the `icons` directory inside `4get` + +`cd /var/www/4get/ && sudo chmod 777 -R icons/` + +4. Add an entry for 4get on your Caddyfile at `/etc/caddy/Caddyfile` + +```sh +4get.konakona.moe { + root * /var/www/4get + file_server + encode gzip + php_fastcgi unix//var/run/php/php8.2-fpm.sock { + index index.php + } + redir /{path}.php{query} 301 + try_files {path} {path}.php +} +``` + +Caddy deals with SSL certificates automatically so you don't have to mess with anything. Also if needed, a sample of my Caddyfile can be found [here](https://git.konakona.moe/diowo/misc/src/branch/master/etc/caddy/Caddyfile). + +5. Restart Caddy + +`sudo systemctl restart caddy` + +# Encryption setup +I'm schizoid (as you should) so I'm gonna setup 4096bit key encryption. To complete this step, you need a domain or subdomain in your possession. Make sure that the DNS shit for your domain has propagated properly before continuing, because certbot is a piece of shit that will error out the ass once you reach 5 attempts under an hour. + +## Encryption setup on Apache + +```sh +certbot --apache --rsa-key-size 4096 -d www.yourdomain.com -d yourdomain.com +``` +When it asks to choose a vhost, choose the option with "HTTPS" listed. Don't setup HTTPS for tor, we don't need it (it doesn't even work anyways with let's encrypt) + +Edit `000-default-le-ssl.conf` + +Add this at the end: +```xml +<Directory /var/www/html/4get> + RewriteEngine On + RewriteCond %{REQUEST_FILENAME}.php -f + RewriteRule (.*) $1.php [L] + Options Indexes FollowSymLinks + AllowOverride All + Require all granted +</Directory> +``` diff --git a/docs/configure.md b/docs/configure.md new file mode 100644 index 0000000..4c49eb7 --- /dev/null +++ b/docs/configure.md @@ -0,0 +1,93 @@ +# 4get configuation options + +Welcome! This guide assumes that you have a working 4get instance. This will help you configure your instance to the best it can be! + +# Files location +1. The main configuration file is located at `data/config.php` +2. The proxies are located in `data/proxies/*.txt` +3. The captcha imagesets are located in `data/captcha/your_image_set/*.png` +4. The captcha font is located in `data/fonts/captcha.ttf` + +# Cloudflare bypass (TLS check) +>These instructions have been updated to work with Debian 13 Trixie. + +**Note: this only allows you to bypass the browser integrity checks. Captchas & javascript challenges will not be bypassed by this program!** + +Configuring this lets you fetch images sitting behind Cloudflare and allows you to scrape the **Yep** search engine. + +To come up with this set of instructions, I used [this guide](https://github.com/lwthiker/curl-impersonate/blob/main/INSTALL.md#native-build) as a reference, but trust me you probably want to stick to what's written on this page. + +First, compile curl-impersonate (the firefox flavor). +```sh +git clone https://github.com/lwthiker/curl-impersonate/ +cd curl-impersonate +sudo apt install build-essential pkg-config cmake ninja-build curl autoconf automake libtool python3-pip libnss3 libnss3-dev +mkdir build +cd build +../configure +make firefox-build +sudo make firefox-install +sudo ldconfig +``` + +Now, after compiling, you should have a `libcurl-impersonate-ff.so` sitting somewhere. Mine is located at `/usr/local/lib/libcurl-impersonate-ff.so`. Do some patch fuckery: + +```sh +sudo su +LD_PRELOAD=/usr/local/lib/libcurl-impersonate-ff.so +CURL_IMPERSONATE=firefox117 +patchelf --set-soname libcurl.so.4 /usr/local/lib/libcurl-impersonate-ff.so +ldconfig +``` + +From here, you will have a broken curl: +```sh +root@fuckedmachine:/# curl --version +curl: /usr/local/lib/libcurl.so.4: no version information available (required by curl) +curl: symbol lookup error: curl: undefined symbol: curl_global_trace, version CURL_OPENSSL_4 +``` + +Or not... During testing, I've seen that sometimes curl still works for some reason. What really matters is the output of this command: +``` +root@fuckedmachine:/# php -r 'print_r(curl_version());' | grep ssl_version + [ssl_version_number] => 0 + [ssl_version] => NSS/3.92 +``` + +It **MUST** say NSS, otherwise it didn't work. There's also the option of using the [forked project](https://github.com/lexiforest/curl-impersonate), but that garbage doesn't support NSS. I'm kind of against impersonating chrome cause you never know when Google is gonna add more fingerprinting bullshit. + +Appendix: If you want a functioning `curl` command line utility again in case it doesn't work anymore, you can do the following hack: + +``` +sudo apt remove curl +sudo ln -s /usr/local/bin/curl-impersonate-ff /usr/bin/curl +``` + +# Robots.txt +Make sure you configure this right to optimize your search engine presence! Head over to `/robots.txt` and change the 4get.ca domain to your own domain. + +# Server listing +To be listed on https://4get.ca/instances , you must contact *any* of the people in the server list and ask them to add you to their list of instances in their configuration. The instance list is distributed, and I don't have control over it. + +If you see spammy entries in your instances list, simply remove the instance from your list that pushes the offending entries. + +# Proxies +4get supports rotating proxies for scrapers! Configuring one is really easy. + +1. Head over to the **proxies** folder. Give it any name you want, like `myproxy`, but make sure it has the `txt` extension. +2. Add your proxies to the file. Examples: + ```conf + # format -> <protocol>:<address>:<port>:<username>:<password> + # protocol list: + # raw_ip, http, https, socks4, socks5, socks4a, socks5_hostname + socks5:1.1.1.1:juicy:cloaca00 + http:1.3.3.7:: + raw_ip:::: + ``` +3. Go to the **main configuration file**. Then, find which website you want to setup a proxy for. +4. Modify the value `false` with `"myproxy"`, with quotes included and the semicolon at the end. + +Done! The scraper you chose should now be using the rotating proxies. When asking for the next page of results, it will use the same proxy to avoid detection! + +## Important! +If you ever test out a `socks5` proxy locally on your machine and find out it works but doesn't on your server, try supplying the `socks5_hostname` protocol instead. Hopefully this tip can save you 3 hours of your life! diff --git a/docs/docker.md b/docs/docker.md new file mode 100644 index 0000000..6a94197 --- /dev/null +++ b/docs/docker.md @@ -0,0 +1,152 @@ +#### Install guide for Docker + +When using docker container any environment variables prefixed with `FOURGET_` will be added to the generated config located at `/var/www/html/4get/data/config.php` + +When lists of data is expected in [data/config.php](../data/config.php), such as `INSTANCES`, you can pass in a comma separated string via environment variable. + +Example: +`FOURGET_INSTANCES="https://4get.ca,https://domain.tld"` + +#### Special environment variables + +| Name | value | Example | +| - | - | - | +| FOURGET_PROTO | "http" or "https" | "https" | + + +#### Important directories + +| Mountpoint | Description | +| - | - | +| /etc/4get/certs | SSL certificate directory | +| /var/www/html/4get/banner | Custom Banners directory | +| /var/www/html/4get/data/captcha | Captcha dataset | + + +the certificate directory `/etc/4get/certs` expects files named `fullchain.pem` and `privkey.pem` + +The captcha dataset should have a subdirectory for each category. In each category, images should be named from 1.png to X.png, and be 100x100 in size. + +example directory structure: + +``` +captcha/ + birds/ + 1.png + 2.png + 3.png + anime/ + 1.png + 2.png +``` + +For more information on configuration view [data/config.php](../data/config.php) + +#### Usage + +You can start 4get with + +``` +docker run -d -p 80:80 -e FOURGET_SERVER_NAME="4get.ca" -e FOURGET_PROTO="http" luuul/4get:latest +``` + +...Or with SSL: + +``` +docker run -d -p 443:443 -e FOURGET_SERVER_NAME="4get.ca" -e FOURGET_PROTO="https" -v /etc/letsencrypt/live/domain.tld:/etc/4get/certs luuul/4get:latest +``` + + +#### With Docker Compose + +Replace relevant values and start with `docker compose up -d` + +##### HTTP + +``` +# docker-compose.yaml +version: "3.7" + +services: + fourget: + image: luuul/4get:latest + restart: unless-stopped + environment: + - FOURGET_PROTO=http + - FOURGET_SERVER_NAME=4get.ca + + ports: + - "80:80" +``` + +##### HTTPS + +``` +# docker-compose.yaml +version: "3.7" + +services: + fourget: + image: luuul/4get:latest + restart: unless-stopped + environment: + - FOURGET_PROTO=https + - FOURGET_SERVER_NAME=4get.ca + + ports: + - "80:80" + - "443:443" + + volumes: + - /etc/letsencrypt/live/domain.tld:/etc/4get/certs +``` + +##### Captcha Enabled + +Set `FOURGET_BOT_PROTECTION=1` and mount a directory containing captcha files to `/var/www/html/4get/data/captcha` + + +``` +# docker-compose.yaml +version: "3.7" + +services: + fourget: + image: luuul/4get:latest + restart: unless-stopped + environment: + - FOURGET_PROTO=http + - FOURGET_SERVER_NAME=4get.ca + - FOURGET_BOT_PROTECTION=1 + + ports: + - "80:80" + + volumes: + - ./captcha:/var/www/html/4get/data/captcha +``` + +##### Custom Banners + +``` +# docker-compose.yaml +version: "3.7" + +services: + fourget: + image: luuul/4get:latest + restart: unless-stopped + environment: + - FOURGET_PROTO=http + - FOURGET_SERVER_NAME=4get.ca + + ports: + - "80:80" + + volumes: + - ./banners:/var/www/html/4get/banner +``` + +##### Tor + +You can route incoming and outgoing requests through tor by following [docker tor documentation](./docker_tor.md) diff --git a/docs/docker_tor.md b/docs/docker_tor.md new file mode 100644 index 0000000..21ae698 --- /dev/null +++ b/docs/docker_tor.md @@ -0,0 +1,174 @@ +#### Overview + +This guide will walk you through using 4get in docker with tor running in +another container. This guide covers how to make outgoing and incoming traffic +go through tor. + + +##### Starting tor + +This guide will use `luuul/tor` which is a simple image that installs and starts +tor in an alpine container SocksPort set to 0.0.0.0:9050 + +For additional configuration you can mount your own `torrc` file to `/etc/tor/torrc` +Remember to set `SocksPort 0.0.0.0:9050` otherwise communication between containers won't work. + +You will see this warning `Other people on the Internet might find your computer and use it as an open proxy. Please don't allow this unless you have a good reason.` + +This setting is in the torrc of this `luuul/tor` image. If you mount your own torrc then that will be read instead. + +If you use `SocksPort 0.0.0.0:9050` anywhere make sure it is inaccessible to outside world. +As long as you don't publish this port (-p or --publish) it shouldn't be accessible to outside world. + + +Tor always starts a socks5 proxy on port 9050 by default. + + +##### Route outgoing requests over tor + +create a folder named `proxies` and create a file in that folder named `onion.txt` +this folder will be mounted to `/var/www/html/4get/data/proxies/` + +directory structure + +``` +proxies/ + onion.txt +``` + +put the following content into `onion.txt` +More information about this file available in [proxy documentation](./configure.md#Proxies). + +``` +# proxies/onion.txt +# Note: "tor" is the service name of luuul/tor in docker-compose.yaml +socks5:tor:9050:: +``` + +create a file named `docker-compose.yaml` with the following content +This docker compose file will run `luuul/tor` and `luuul/4get` and configure 4get to load `proxies/onion.txt` for outgoing requests. + +If you mount your own torrc make sure you include `SocksPort 0.0.0.0:9050` +Read the warning in [starting tor](./docker_tor.md#Starting-tor)! + +``` +# docker-compose.yaml +version: "3.7" + +services: + tor: + image: luuul/tor:latest + restart: unless-stopped + # Warning: Do not publish port 9050 + + fourget: + image: luuul/4get:latest + restart: unless-stopped + environment: + - FOURGET_PROTO=http + - FOURGET_SERVER_NAME=4get.ca + # loads proxies/onion.txt + - FOURGET_PROXY_DDG="onion" + - FOURGET_PROXY_BRAVE="onion" + - FOURGET_PROXY_FB="onion" + - FOURGET_PROXY_GOOGLE="onion" + - FOURGET_PROXY_QWANT="onion" + - FOURGET_PROXY_MARGINALIA="onion" + - FOURGET_PROXY_MOJEEK="onion" + - FOURGET_PROXY_SC="onion" + - FOURGET_PROXY_SPOTIFY="onion" + - FOURGET_PROXY_WIBY="onion" + - FOURGET_PROXY_CURLIE="onion" + - FOURGET_PROXY_YT="onion" + - FOURGET_PROXY_YEP="onion" + - FOURGET_PROXY_PINTEREST="onion" + - FOURGET_PROXY_SEZNAM="onion" + - FOURGET_PROXY_NAVER="onion" + - FOURGET_PROXY_GREPPR="onion" + - FOURGET_PROXY_CROWDVIEW="onion" + - FOURGET_PROXY_MWMBL="onion" + - FOURGET_PROXY_FTM="onion" + - FOURGET_PROXY_IMGUR="onion" + - FOURGET_PROXY_YANDEX_W="onion" + - FOURGET_PROXY_YANDEX_I="onion" + - FOURGET_PROXY_YANDEX_V="onion" + + ports: + - "80:80" + + depends_on: + - tor + + volumes: + - ./proxies/:/var/www/html/4get/data/proxies/ +``` + +You can now start both containers with `docker compose up -d` + + +#### Route incoming requests over tor + +This will create a hidden service that will be accessible via an onion link. + +1. create a file named `torrc` with the following content + +``` +# torrc +User root + +HiddenServiceDir /var/lib/tor/4get/ +HiddenServicePort 80 fourget:80 + +``` + +2. create a folder named "4get" which will contain your hidden service keys. + +Make sure it has permission `600` otherwise you will get an error + +> Permissions on directory /var/lib/tor/4get/ are too permissive. + +you can change permissions with + +``` +chmod 600 4get +``` + +3. Create a folder named "data" that will contain your DataDirectory + + +4. create a `docker-compose.yaml` with the following content + +``` +# docker-compose.yaml +version: "3.7" + +services: + fourget: + image: luuul/4get:latest + restart: unless-stopped + environment: + - FOURGET_PROTO=http + - FOURGET_SERVER_NAME=4get.ca + + depends_on: + - tor + + tor: + image: luuul/tor:latest + restart: unless-stopped + + volumes: + - ./torrc:/etc/tor/torrc + - ./4get:/var/lib/tor/4get + - ./data:/root/.tor +``` + +5. You can now start both with `docker compose up -d` + +6. print onion hostname with + +``` +docker exec `docker ps -qf ancestor=luuul/tor:latest` sh -c "cat /var/lib/tor/4get/hostname" +``` + +or `cat ./4get/hostname` diff --git a/docs/nginx.md b/docs/nginx.md new file mode 100644 index 0000000..82fc434 --- /dev/null +++ b/docs/nginx.md @@ -0,0 +1,194 @@ +<h1 align=center>Installation of 4get in NGINX</h1> + +<div align=right> + +> NOTE: As the previous version stated, it is better to follow the <a href="https://git.lolcat.ca/lolcat/4get/src/branch/master/docs/apache2.md">Apache2 guide</a> instead of the Nginx one. + +> NOTE: This is going to guess that you're using either a <abbr title="(Arch Linux, Artix Linux, Endeavouros, etc...) ">Arch-based system</abbr> or a <abbr title="(Debian, Ubuntu, Devuan, etc...)">Debian-based system</abbr>, although you can still follow it with minor issues. + +</div> + +1. Login as root. +2. Upgrade your system: + * On Arch-based, run `pacman -Syu`. + * On Debian-based, run `apt update`, then `apt upgrade`. +3. Install the following dependencies: + * `git`: So you can clone <a href="https://git.lolcat.ca/lolcat/4get">this</a> repository. + * `nginx`: So you can run Nginx. + * `php-fpm`: This is what allows Nginx to run *(and show)* PHP files. + * `php-imagick`, `imagemagick`: Image manipulation. + * `php-apcu`: Caching module. + * `php-curl`, `curl`: Transferring data with URLs. + * `php-mbstring`: String utils. + * `certbot`, `certbot-nginx`: ACME client. Used to create SSL certificates. + * In Arch-based distributions: + * `pacman -S nginx certbot php-imagick certbot-nginx imagemagick curl php-apcu git` + * In Debian-based distributions: + * `apt install php-mbstring nginx certbot-nginx certbot php-imagick imagemagick php-curl curl php-apcu git` + +<div align=right> + +> IMPORTANT: `php-curl`, `php-mbstring` might be a Debian-only package, but this needs further fact checking. + +> IMPORTANT: If having issues with `php-apcu` or `libsodium`, go to [^1]. + +</div> + +4. `cd` to `/etc/nginx` and make the `conf.d/` directory if it doesn't exist: + * Again, this guesses you're logged in as root. + ```sh + cd /etc/nginx + ls -l conf.d/ # If ls shows conf.d, then it means it exists. + # If it does not, run: + mkdir conf.d + ``` +5. Make a file inside `conf.d/` called `4get.conf` and place the following content: + * First run `touch conf.d/4get.conf` then `nano conf.d/4get.conf` to open the nano editor: *(Install it if it is not, or use another editor.)* + ```sh + server { + access_log /dev/null; # Search log file. Do you really need to? + error_log /dev/null; # Error log file. + + # Change this if you have 4get in another folder. + root /var/www/4get; + # Change 'yourdomain' to your domain. + server_name www.yourdomain.com yourdomain.com; + # Port to listen to. + listen 80; + + location @php { + try_files $uri.php $uri/index.php =404; + # Change the unix socket address if it's different for you. + fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; + fastcgi_index index.php; + # Change this to `fastcgi_params` if you use a debian based distribution. + include fastcgi.conf; + fastcgi_intercept_errors on; + } + + location / { + try_files $uri @php; + } + + location ~* ^(.*)\.php$ { + return 301 $1; + } + + } + ``` + * The above is a very basic configuration and thus will need tweaking to your personal needs. It should still work as-is, though. A 'real world' example is present in [^2]. + * After saving the file, check that the `nginx.conf` file inside the main directory includes files inside `conf.d/`: + * It should be inside the the http block: *(The following is an example! Don't just Copy and Paste it!)* + ```sh + http { + include mime.types; + include conf.d/*.conf; + types_hash_max_size 4096; + # ... + } + ``` + * Now, test your configuration with `nginx -t`, if it says that everything is good, restart *(or start)* the Nginx daemon: + * This depends on the init manager, most distributions use `systemd`, but it's better practice to include most. + ```sh + # systemd + systemctl stop nginx + systemctl start nginxt + # or + systemctl restart nginx + + # openrc + rc-service nginx stop + rc-service nginx start + # or + rc-service nginx restart + + # runit + sv down nginx + sv up nginx + # or + sv restart nginx + + # s6 + s6-rc -d change nginx + s6-rc -u change nginx + # or + s6-svc -r /run/service/nginx + + # dinit + dinitctl stop nginx + dinitctl start nginx + # or + dinitctl restart nginx + ``` +6. Clone the repository to `/var/www`: + * `git clone --depth 1 https://git.lolcat.ca/lolcat/4get 4get` - It clones the repository with the depth of one commit *(so it takes less time to download)* and saves the cloned repository as '4get'. +7. That should be it! There are some extra steps you can take, but it really just depends on you. + +<h2 align=center>Encryption setup</h2> + +1. Generate a certificate for the domain you're using with: + * Note that `certbot-nginx` is needed. + ```sh + certbot --nginx --key-type ecdsa -d www.yourdomain.com -d yourdomain.com + ``` +2. After that, certbot will deploy the certificate automatically to your 4get conf file; It should be ready to use from there. + +<h2 align=center>Tor Setup</h2> + +<div align=right> + +> IMPORTANT: Tor onion addresses are very long compared to traditional domains, so, Before doing anything, edit `nginx.conf` and increase <abbr title="This setting in your Nginx configuration controls the internal data structure used to manage multiple server names (hostnames) associated with your web server. Each hostname requires a certain amount of memory within this structure. If the size is insufficient, Nginx will encounter errors."><code>server_names_hash_bucket_size</code></abbr> to your needs. + +</div> + +1. `cd` to `/etc/nginx` *(if you haven't)* and open your `nginx.conf` file. +2. Find the line containing `# server_names_hash_bucket_size 64;` inside said file. +3. Uncomment the line and adjust the value; start with 64, but if you encounter issues, incrementally increase it *(e.g., 128, 256)* until it accommodates your configuration. +4. Open *(or duplicate the configuration)* and edit it: + * Example configuration, again: + ```sh + server { + access_log /dev/null; # Search log file. Do you really need to? + error_log /dev/null; # Error log file. + + # Change this if you have 4get in another folder. + root /var/www/4get; + # Change 'onionadress.onion' to your onion link. + server_name onionadress.onion; + # Port to listen to. + listen 80; + + location @php { + try_files $uri.php $uri/index.php =404; + # Change the unix socket address if it's different for you. + fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock; + fastcgi_index index.php; + # Change this to `fastcgi_params` if you use a debian based distribution. + include fastcgi.conf; + fastcgi_intercept_errors on; + } + + location / { + try_files $uri @php; + } + + location ~* ^(.*)\.php$ { + return 301 $1; + } + + } + ``` + A real world example is present in [^2]. +5. Once done, check the configuration with `nginx -t`. If everything's fine and dandy, refer to <a href="https://git.lolcat.ca/lolcat/4get/src/branch/master/docs/tor.md">the Tor guide</a> to setup your onion site. + +<h2 align=center>Other important things</h2> + +1. <a href="https://git.lolcat.ca/lolcat/4get/src/branch/master/docs/configure.md">Configuration guide</a>: Things to do after setup. +2. <a href="https://git.lolcat.ca/lolcat/4get/src/branch/master/docs/apache2.md">Apache2 guide</a>: Fallback to this if you couldn't get something to work, or you don't know something. + +<h2 align=center>Known issues</h2> + +1. https://git.lolcat.ca/lolcat/4get/issues + +[^1]: lolcat/4get#40, If having issues with `libsodium`, or `php-apcu`. +[^2]: <a href="https://git.nadeko.net/Fijxu/etc-configs/src/branch/selfhost/nginx/conf.d/4get.conf">git.nadeko.net</a> nadeko.net's 4get instance configuration.
\ No newline at end of file diff --git a/docs/tor.md b/docs/tor.md new file mode 100644 index 0000000..b29ac3d --- /dev/null +++ b/docs/tor.md @@ -0,0 +1,16 @@ +# Tor setup +This guide assumes that there is already a configured webserver sitting on port 80 waiting for localhost connections. The <a href="https://git.lolcat.ca/lolcat/4get/src/branch/master/docs/apache2.md">apache2 guide</a> guides you through this. + +1. Login as `root`. +2. Install `tor`. +3. Edit `/etc/tor/torrc` +4. Go to the line that contains `HiddenServiceDir` and `HiddenServicePort`, uncomment those 2 lines and set them like this: + ``` + HiddenServiceDir /var/lib/tor/4get + HiddenServicePort 80 127.0.0.1:80 + ``` +5. Restart the tor service using `service tor restart` +6. Wait for a while... +7. Run `cat /var/lib/tor/4get/hostname`. That is your onion address! + +# Specify your own tor address diff --git a/donate.php b/donate.php new file mode 100644 index 0000000..1ae2cac --- /dev/null +++ b/donate.php @@ -0,0 +1,39 @@ +<?php + +include "data/config.php"; +include "lib/frontend.php"; +$frontend = new frontend(); + +echo + $frontend->load( + "header_nofilters.html", + [ + "title" => "Donate to the project", + "class" => " class=\"about\"" + ] + ); + +$left = + explode( + "\n", + file_get_contents("template/donate.html") + ); + +$out = ""; + +foreach($left as $line){ + + $out .= trim($line); +} + +echo + $frontend->load( + "search.html", + [ + "timetaken" => null, + "class" => "", + "right-left" => "", + "right-right" => "", + "left" => $out + ] + ); diff --git a/favicon.ico b/favicon.ico Binary files differnew file mode 100644 index 0000000..a54beb0 --- /dev/null +++ b/favicon.ico diff --git a/favicon.php b/favicon.php new file mode 100644 index 0000000..0694a12 --- /dev/null +++ b/favicon.php @@ -0,0 +1,368 @@ +<?php + +if(!isset($_GET["s"])){ + + header("X-Error: Missing parameter (s)ite"); + die(); +} + +include "data/config.php"; +new favicon($_GET["s"]); + +class favicon{ + + public function __construct($url){ + + header("Content-Type: image/png"); + + if( + preg_match( + '/^https?:\/\/[A-Za-z0-9.-]+$/', + $url + ) === 0 + ){ + + header("X-Error: Only provide the protocol and domain"); + $this->defaulticon(); + } + + $filename = str_replace(["https://", "http://"], "", $url); + header("Content-Disposition: inline; filename=\"{$filename}.png\""); + + include "lib/curlproxy.php"; + $this->proxy = new proxy(false); + + $this->filename = parse_url($url, PHP_URL_HOST); + + /* + Check if we have the favicon stored locally + */ + if(file_exists("icons/" . $filename . ".png")){ + + $handle = fopen("icons/" . $filename . ".png", "r"); + echo fread($handle, filesize("icons/" . $filename . ".png")); + fclose($handle); + return; + } + + /* + Scrape html + */ + try{ + + $payload = $this->proxy->get($url, $this->proxy::req_web, true); + + }catch(Exception $error){ + + header("X-Error: Could not fetch HTML (" . $error->getMessage() . ")"); + $this->favicon404(); + } + //$payload["body"] = '<link rel="manifest" id="MANIFEST_LINK" href="/data/manifest/" crossorigin="use-credentials" />'; + + // get link tags + preg_match_all( + '/< *link +(.*)[\/]?>/Uixs', + $payload["body"], + $linktags + ); + + /* + Get relevant tags + */ + + $linktags = $linktags[1]; + $attributes = []; + + /* + header("Content-Type: text/plain"); + print_r($linktags); + print_r($payload); + die();*/ + + for($i=0; $i<count($linktags); $i++){ + + // get attributes + preg_match_all( + '/([A-Za-z0-9]+) *= *("[^"]*"|[^" ]+)/s', + $linktags[$i], + $tags + ); + + for($k=0; $k<count($tags[1]); $k++){ + + $attributes[$i][] = [ + "name" => $tags[1][$k], + "value" => trim($tags[2][$k], "\" \n\r\t\v\x00") + ]; + } + } + + unset($payload); + unset($linktags); + + $href = []; + + // filter out the tags we want + foreach($attributes as &$group){ + + $tmp_href = null; + $tmp_rel = null; + $badtype = false; + + foreach($group as &$attribute){ + + switch($attribute["name"]){ + + case "rel": + + $attribute["value"] = strtolower($attribute["value"]); + + if( + ( + $attribute["value"] == "icon" || + $attribute["value"] == "manifest" || + $attribute["value"] == "shortcut icon" || + $attribute["value"] == "apple-touch-icon" || + $attribute["value"] == "mask-icon" + ) === false + ){ + + break; + } + + $tmp_rel = $attribute["value"]; + break; + + case "type": + $attribute["value"] = explode("/", $attribute["value"], 2); + + if(strtolower($attribute["value"][0]) != "image"){ + + $badtype = true; + break; + } + break; + + case "href": + + // must not contain invalid characters + // must be bigger than 1 + if( + filter_var($attribute["value"], FILTER_SANITIZE_URL) == $attribute["value"] && + strlen($attribute["value"]) > 0 + ){ + + $tmp_href = $attribute["value"]; + break; + } + break; + } + } + + if( + $badtype === false && + $tmp_rel !== null && + $tmp_href !== null + ){ + + $href[$tmp_rel] = $tmp_href; + } + } + + /* + Priority list + */ + /* + header("Content-Type: text/plain"); + print_r($href); + die();*/ + + if(isset($href["icon"])){ $href = $href["icon"]; } + elseif(isset($href["apple-touch-icon"])){ $href = $href["apple-touch-icon"]; } + elseif(isset($href["manifest"])){ + + // attempt to parse manifest, but fallback to [] + $href = $this->parsemanifest($href["manifest"], $url); + } + + if(is_array($href)){ + + if(isset($href["mask-icon"])){ $href = $href["mask-icon"]; } + elseif(isset($href["shortcut icon"])){ $href = $href["shortcut icon"]; } + else{ + + $href = "/favicon.ico"; + } + } + + $href = $this->proxy->getabsoluteurl($href, $url); + /* + header("Content-type: text/plain"); + echo $href; + die();*/ + + + /* + Download the favicon + */ + //$href = "https://git.lolcat.ca/assets/img/logo.svg"; + + try{ + $payload = + $this->proxy->get( + $href, + $this->proxy::req_image, + true, + $url + ); + + }catch(Exception $error){ + + header("X-Error: Could not fetch the favicon (" . $error->getMessage() . ")"); + $this->favicon404(); + } + + /* + Parse the file format + */ + $image = null; + $format = $this->proxy->getimageformat($payload, $image); + + /* + Convert the image + */ + try{ + + /* + @todo: fix issues with avif+transparency + maybe using GD as fallback? + */ + if($format !== false){ + $image->setFormat($format); + } + + $image->setBackgroundColor(new ImagickPixel("transparent")); + $image->readImageBlob($payload["body"]); + $image->resizeImage(16, 16, imagick::FILTER_LANCZOS, 1); + $image->setFormat("png"); + + $image = $image->getImageBlob(); + + // save favicon + $handle = fopen("icons/" . $this->filename . ".png", "w"); + fwrite($handle, $image, strlen($image)); + fclose($handle); + + echo $image; + + }catch(ImagickException $error){ + + header("X-Error: Could not convert the favicon: (" . $error->getMessage() . ")"); + $this->favicon404(); + } + + return; + } + + private function parsemanifest($href, $url){ + + if( + // check if base64-encoded JSON manifest + preg_match( + '/^data:application\/json;base64,([A-Za-z0-9=]*)$/', + $href, + $json + ) + ){ + + $json = base64_decode($json[1]); + + if($json === false){ + + // could not decode the manifest regex + return []; + } + + }else{ + + try{ + $json = + $this->proxy->get( + $this->proxy->getabsoluteurl($href, $url), + $this->proxy::req_web, + false, + $url + ); + + $json = $json["body"]; + + }catch(Exception $error){ + + // could not fetch the manifest + return []; + } + } + + $json = json_decode($json, true); + + if($json === null){ + + // manifest did not return valid json + return []; + } + + if( + isset($json["start_url"]) && + $this->proxy->validateurl($json["start_url"]) + ){ + + $url = $json["start_url"]; + } + + if(!isset($json["icons"][0]["src"])){ + + // manifest does not contain a path to the favicon + return []; + } + + // horay, return the favicon path + return $json["icons"][0]["src"]; + } + + private function favicon404(){ + + // fallback to google favicons + // ... probably blocked by cuckflare + try{ + + $image = + $this->proxy->get( + "https://t0.gstatic.com/faviconV2?client=SOCIAL&type=FAVICON&fallback_opts=TYPE,SIZE,URL&url=http://{$this->filename}&size=16", + $this->proxy::req_image + ); + }catch(Exception $error){ + + $this->defaulticon(); + } + + // write favicon from google + $handle = fopen("icons/" . $this->filename . ".png", "w"); + fwrite($handle, $image["body"], strlen($image["body"])); + fclose($handle); + + echo $image["body"]; + die(); + } + + private function defaulticon(){ + + // give 404 and fuck off + http_response_code(404); + + $handle = fopen("lib/favicon404.png", "r"); + echo fread($handle, filesize("lib/favicon404.png")); + fclose($handle); + + die(); + } +} diff --git a/icons/lolcat.ca.png b/icons/lolcat.ca.png Binary files differnew file mode 100644 index 0000000..bf47a44 --- /dev/null +++ b/icons/lolcat.ca.png diff --git a/images.php b/images.php new file mode 100644 index 0000000..99fc9d6 --- /dev/null +++ b/images.php @@ -0,0 +1,77 @@ +<?php + +/* + Initialize random shit +*/ +include "data/config.php"; + +include "lib/frontend.php"; +$frontend = new frontend(); + +[$scraper, $filters] = $frontend->getscraperfilters("images"); + +$get = $frontend->parsegetfilters($_GET, $filters); + +/* + Captcha +*/ +include "lib/bot_protection.php"; +new bot_protection($frontend, $get, $filters, "images", true); + +$payload = [ + "timetaken" => microtime(true), + "images" => "", + "nextpage" => "" +]; + +try{ + $results = $scraper->image($get); + +}catch(Exception $error){ + + $frontend->drawscrapererror($error->getMessage(), $get, "images", $payload["timetaken"]); +} + +if(count($results["image"]) === 0){ + + $payload["images"] = + '<div class="infobox">' . + "<h1>Nobody here but us chickens!</h1>" . + 'Have you tried:' . + '<ul>' . + '<li>Using a different scraper</li>' . + '<li>Using fewer keywords</li>' . + '<li>Defining broader filters (Is NSFW turned off?)</li>' . + '</ul>' . + '</div>'; +} + +foreach($results["image"] as $image){ + + $payload["images"] .= + '<div class="image-wrapper" title="' . htmlspecialchars($image["title"]) .'" data-json="' . htmlspecialchars(json_encode($image["source"])) . '">' . + '<div class="image">' . + '<a href="' . htmlspecialchars($image["source"][0]["url"]) . '" rel="noreferrer nofollow" class="thumb">' . + '<img src="' . $frontend->htmlimage($image["source"][count($image["source"]) - 1]["url"], "thumb") . '" alt="thumbnail">'; + + if($image["source"][0]["width"] !== null){ + $payload["images"] .= '<div class="duration">' . $image["source"][0]["width"] . 'x' . $image["source"][0]["height"] . '</div>'; + } + + $payload["images"] .= + '</a>' . + '<a href="' . htmlspecialchars($image["url"]) . '" rel="noreferrer nofollow">' . + '<div class="title">' . htmlspecialchars(parse_url($image["url"], PHP_URL_HOST)) . '</div>' . + '<div class="description">' . $frontend->highlighttext($get["s"], $image["title"]) . '</div>' . + '</a>' . + '</div>' . + '</div>'; +} + +if($results["npt"] !== null){ + + $payload["nextpage"] = + '<a href="' . $frontend->htmlnextpage($get, $results["npt"], "images") . '" class="nextpage img">Next page ></a>'; +} + +echo $frontend->load("images.html", $payload); diff --git a/index.php b/index.php new file mode 100644 index 0000000..8eba2fc --- /dev/null +++ b/index.php @@ -0,0 +1,15 @@ +<?php + +include "data/config.php"; +include "lib/frontend.php"; +$frontend = new frontend(); + +$images = glob("banner/*"); + +echo $frontend->load( + "home.html", + [ + "server_short_description" => htmlspecialchars(config::SERVER_SHORT_DESCRIPTION), + "banner" => $images[rand(0, count($images) - 1)] + ] +); diff --git a/instances.php b/instances.php new file mode 100644 index 0000000..b9db771 --- /dev/null +++ b/instances.php @@ -0,0 +1,55 @@ +<?php + +include "lib/frontend.php"; +$frontend = new frontend(); + +include "data/config.php"; + +$params = ""; +$first = true; +foreach($_GET as $key => $value){ + + if( + !is_string($value) || + $key == "target" + ){ + + continue; + } + + if($first === true){ + + $first = false; + $params = "?"; + }else{ + + $params .= "&"; + } + + $params .= urlencode($key) . "=" . urlencode($value); +} + +if( + !isset($_GET["target"]) || + !is_string($_GET["target"]) +){ + + $target = ""; +}else{ + + $target = "/" . urlencode($_GET["target"]); +} + +$instances = ""; +foreach(config::INSTANCES as $instance){ + + $instances .= '<tr><td class="expand"><a href="' . htmlspecialchars($instance) . $target . $params . '" target="_BLANK" rel="noreferer">' . htmlspecialchars($instance) . '</a></td></tr>'; +} + +echo + $frontend->load( + "instances.html", + [ + "instances_html" => $instances + ] + ); diff --git a/lib/anubis.php b/lib/anubis.php new file mode 100644 index 0000000..2bd6d90 --- /dev/null +++ b/lib/anubis.php @@ -0,0 +1,100 @@ +<?php + +// +// Reference +// https://github.com/TecharoHQ/anubis/blob/ecc716940e34ebe7249974f2789a99a2c7115e4e/web/js/proof-of-work.mjs +// + +class anubis{ + + public function __construct(){ + + include_once "fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function scrape($html){ + + $this->fuckhtml->load($html); + + $script = + $this->fuckhtml + ->getElementById( + "anubis_challenge", + "script" + ); + + if($script === false){ + + throw new Exception("Failed to scrape anubis challenge data"); + } + + $script = + json_decode( + $this->fuckhtml + ->getTextContent( + $script + ), + true + ); + + if($script === null){ + + throw new Exception("Failed to decode anubis challenge data"); + } + + if( + !isset($script["challenge"]) || + !isset($script["rules"]["difficulty"]) || + !is_int($script["rules"]["difficulty"]) || + !is_string($script["challenge"]) + ){ + + throw new Exception("Found invalid challenge data"); + } + + return $this->rape($script["challenge"], $script["rules"]["difficulty"]); + } + + private function is_valid_hash($hash, $difficulty){ + + for ($i=0; $i<$difficulty; $i++) { + + $index = (int)floor($i / 2); + $nibble = $i % 2; + + $byte = ord($hash[$index]); + $nibble = ($byte >> ($nibble === 0 ? 4 : 0)) & 0x0f; + + if($nibble !== 0){ + return false; + } + } + + return true; + } + + public function rape($data, $difficulty = 5){ + + $nonce = 0; + + while(true){ + + $hash_binary = hash("sha256", $data . $nonce, true); + + if($this->is_valid_hash($hash_binary, $difficulty)){ + + $hash_hex = bin2hex($hash_binary); + + return [ + "response" => $hash_hex, + //"data" => $data, + //"difficulty" => $difficulty, + "nonce" => $nonce + ]; + } + + $nonce++; + } + } +} diff --git a/lib/backend.php b/lib/backend.php new file mode 100644 index 0000000..66e78a1 --- /dev/null +++ b/lib/backend.php @@ -0,0 +1,178 @@ +<?php +class backend{ + + public function __construct($scraper){ + + $this->scraper = $scraper; + } + + /* + Proxy stuff + */ + public function get_ip(){ + + $pool = constant("config::PROXY_" . strtoupper($this->scraper)); + if($pool === false){ + + // we don't want a proxy, fuck off! + return 'raw_ip::::'; + } + + // indent + $proxy_index_raw = apcu_inc("p." . $this->scraper); + + $proxylist = file_get_contents("data/proxies/" . $pool . ".txt"); + $proxylist = explode("\n", $proxylist); + + // ignore empty or commented lines + $proxylist = array_filter($proxylist, function($entry){ + $entry = ltrim($entry); + return strlen($entry) > 0 && substr($entry, 0, 1) != "#"; + }); + + $proxylist = array_values($proxylist); + + return $proxylist[$proxy_index_raw % count($proxylist)]; + } + + // this function is also called directly on nextpage + public function assign_proxy(&$curlproc, string $ip){ + + // parse proxy line + [ + $type, + $address, + $port, + $username, + $password + ] = explode(":", $ip, 5); + + switch($type){ + + case "raw_ip": + return; + break; + + case "http": + case "https": + curl_setopt($curlproc, CURLOPT_PROXYTYPE, CURLPROXY_HTTP); + curl_setopt($curlproc, CURLOPT_PROXY, $type . "://" . $address . ":" . $port); + break; + + case "socks4": + curl_setopt($curlproc, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4); + curl_setopt($curlproc, CURLOPT_PROXY, $address . ":" . $port); + break; + + case "socks5": + curl_setopt($curlproc, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5); + curl_setopt($curlproc, CURLOPT_PROXY, $address . ":" . $port); + break; + + case "socks4a": + curl_setopt($curlproc, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4A); + curl_setopt($curlproc, CURLOPT_PROXY, $address . ":" . $port); + break; + + case "socks5_hostname": + case "socks5h": + case "socks5a": + curl_setopt($curlproc, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5_HOSTNAME); + curl_setopt($curlproc, CURLOPT_PROXY, $address . ":" . $port); + break; + } + + if($username != ""){ + + curl_setopt($curlproc, CURLOPT_PROXYUSERPWD, $username . ":" . $password); + } + } + + + + /* + Next page stuff + */ + public function store(string $payload, string $page, string $proxy){ + + $key = sodium_crypto_secretbox_keygen(); + $nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); + + $requestid = apcu_inc("requestid"); + + apcu_store( + $page[0] . "." . // first letter of page name + $this->scraper . // scraper name + $requestid, + [ + $nonce, + $proxy, + // compress and encrypt + sodium_crypto_secretbox( + gzdeflate($payload), + $nonce, + $key + ) + ], + 900 // cache information for 15 minutes + ); + + return + $this->scraper . $requestid . "." . + rtrim(strtr(base64_encode($key), '+/', '-_'), '='); + } + + public function get(string $npt, string $page){ + + $page = $page[0]; + $explode = explode(".", $npt, 2); + + if(count($explode) !== 2){ + + throw new Exception("Malformed nextPageToken!"); + } + + $apcu = $page . "." . $explode[0]; + $key = $explode[1]; + + $payload = apcu_fetch($apcu); + + if($payload === false){ + + throw new Exception("The next page token is invalid or has expired!"); + } + + $key = + base64_decode( + str_pad( + strtr($key, '-_', '+/'), + strlen($key) % 4, + '=', + STR_PAD_RIGHT + ) + ); + + // decrypt and decompress data + $payload[2] = + gzinflate( + sodium_crypto_secretbox_open( + $payload[2], // data + $payload[0], // nonce + $key + ) + ); + + if($payload[2] === false){ + + throw new Exception("The next page token is invalid or has expired!"); + } + + // remove the key after using successfully + apcu_delete($apcu); + + return [ + $payload[2], // data + $payload[1] // proxy + ]; + } +} diff --git a/lib/bingcache-todo-fix.php b/lib/bingcache-todo-fix.php new file mode 100644 index 0000000..a4acb5b --- /dev/null +++ b/lib/bingcache-todo-fix.php @@ -0,0 +1,144 @@ +<?php + +// https://www.bing.com/search?q=url%3Ahttps%3A%2F%2Flolcat.ca +// https://cc.bingj.com/cache.aspx?q=url%3ahttps%3a%2f%2flolcat.ca&d=4769685974291356&mkt=en-CA&setlang=en-US&w=tEsWuE7HW3Z5AIPQMVkDH4WaotS4LrK- +// <div class="b_attribution" u="0N|5119|4769685974291356|tEsWuE7HW3Z5AIPQMVkDH4WaotS4LrK-" tabindex="0"> + +new bingcache(); + +class bingcache{ + + public function __construct(){ + + if( + !isset($_GET["s"]) || + $this->validate_url($_GET["s"]) === false + ){ + + var_dump($this->validate_url($_GET["s"])); + $this->do404("Please provide a valid URL."); + } + + $url = $_GET["s"]; + + $curlproc = curl_init(); + + curl_setopt( + $curlproc, + CURLOPT_URL, + "https://www.bing.com/search?q=url%3A" . + urlencode($url) + ); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt( + $curlproc, + CURLOPT_HTTPHEADER, + ["User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:107.0) Gecko/20100101 Firefox/107.0", + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 5); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + $this->do404("Failed to connect to bing servers. Please try again later."); + } + + curl_close($curlproc); + + preg_match( + '/<div class="b_attribution" u="(.*)" tabindex="0">/', + $data, + $keys + ); + + print_r($keys); + + if(count($keys) === 0){ + + $this->do404("Bing has not archived this URL."); + } + + $keys = explode("|", $keys[1]); + $count = count($keys); + + //header("Location: https://cc.bingj.com/cache.aspx?d=" . $keys[$count - 2] . "&w=" . $keys[$count - 1]); + echo("Location: https://cc.bingj.com/cache.aspx?d=" . $keys[$count - 2] . "&w=" . $keys[$count - 1]); + } + + public function do404($text){ + + include "lib/frontend.php"; + $frontend = new frontend(); + + echo + $frontend->load( + "error.html", + [ + "title" => "Shit", + "text" => $text + ] + ); + + die(); + } + + public function validate_url($url){ + + $url_parts = parse_url($url); + + // check if required parts are there + if( + !isset($url_parts["scheme"]) || + !( + $url_parts["scheme"] == "http" || + $url_parts["scheme"] == "https" + ) || + !isset($url_parts["host"]) + ){ + return false; + } + + if( + // if its not an RFC-valid URL + !filter_var($url, FILTER_VALIDATE_URL) + ){ + return false; + } + + $ip = + str_replace( + ["[", "]"], // handle ipv6 + "", + $url_parts["host"] + ); + + // if its not an IP + if(!filter_var($ip, FILTER_VALIDATE_IP)){ + + // resolve domain's IP + $ip = gethostbyname($url_parts["host"] . "."); + } + + // check if its localhost + return filter_var( + $ip, + FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE + ); + } +} diff --git a/lib/bot_protection.php b/lib/bot_protection.php new file mode 100644 index 0000000..e3d51a8 --- /dev/null +++ b/lib/bot_protection.php @@ -0,0 +1,281 @@ +<?php + +class bot_protection{ + + public function __construct($frontend, $get, $filters, $page, $output){ + + // check if we want captcha + if(config::BOT_PROTECTION !== 1){ + + apcu_inc("real_requests"); + if($output === true){ + $frontend->loadheader( + $get, + $filters, + $page + ); + } + return; + } + + /* + Validate cookie, if it exists + */ + if(isset($_COOKIE["pass"])){ + + if( + // check if key is not malformed + preg_match( + '/^k[0-9]+\.[A-Za-z0-9_]{20}$/', + $_COOKIE["pass"] + ) && + // does key exist + apcu_exists($_COOKIE["pass"]) + ){ + + // exists, increment counter + $inc = apcu_inc($_COOKIE["pass"]); + + // we start counting from 1 + // when it has been incremented to 102, it has reached + // 100 reqs + if($inc >= config::MAX_SEARCHES + 2){ + + // reached limit, delete and give captcha + apcu_delete($_COOKIE["pass"]); + }else{ + + // the cookie is OK! dont die() and give results + apcu_inc("real_requests"); + + if($output === true){ + $frontend->loadheader( + $get, + $filters, + $page + ); + } + return; + } + } + } + + if($output === false){ + + http_response_code(401); // forbidden + echo json_encode([ + "status" => "The \"pass\" token in your cookies is missing or has expired!!" + ]); + die(); + } + + /* + Validate form data + */ + $lines = + explode( + "\r\n", + file_get_contents("php://input") + ); + + $invalid = false; + $answers = []; + $key = false; + $error = ""; + + foreach($lines as $line){ + + $line = explode("=", $line, 2); + + if(count($line) !== 2){ + + $invalid = true; + break; + } + + preg_match( + '/^c\[([0-9]+)\]$/', + $line[0], + $regex + ); + + if( + $line[1] != "on" || + !isset($regex[0][1]) + ){ + + // check if its the v key + if( + $line[0] == "v" && + preg_match( + '/^c[0-9]+\.[A-Za-z0-9_]{20}$/', + $line[1] + ) + ){ + + $key = apcu_fetch($line[1]); + apcu_delete($line[1]); + } + break; + } + + $regex = (int)$regex[1]; + + if( + $regex >= 16 || + $regex <= -1 + ){ + + $invalid = true; + break; + } + + $answers[] = $regex; + } + + if( + !$invalid && + $key !== false // has captcha been gen'd? + ){ + $check = count($key); + + // validate answer + for($i=0; $i<count($answers); $i++){ + + if(in_array($answers[$i], $key)){ + + $check--; + }else{ + + $check = -1; + break; + } + } + + if($check === 0){ + + // we passed the captcha + // set cookie + $inc = apcu_inc("cookie"); + + $key = "k" . $inc . "." . $this->randomchars(); + + apcu_inc($key, 1, $stupid, 86400); + + apcu_inc("real_requests"); + + setcookie( + "pass", + $key, + [ + "expires" => time() + 86400, // expires in 24 hours + "samesite" => "Lax", + "path" => "/" + ] + ); + + $frontend->loadheader( + $get, + $filters, + $page + ); + return; + + }else{ + + $error = "<div class=\"quote\">You were <a href=\"https://www.youtube.com/watch?v=e1d7fkQx2rk\" target=\"_BLANK\" rel=\"noreferrer nofollow\">kicked out of Mensa.</a> Please try again.</div>"; + } + } + + $key = "c" . apcu_inc("captcha_gen", 1) . "." . $this->randomchars(); + + $payload = [ + "timetaken" => microtime(true), + "class" => "", + "right-left" => "", + "right-right" => "", + "left" => + '<div class="infobox">' . + '<h1>IQ test</h1>' . + 'IQ test has been enabled due to bot abuse on the network.<br>' . + 'Solving this IQ test will let you make 100 searches today. I will add an invite system to bypass this soon...' . + $error . + '<form method="POST" enctype="text/plain" autocomplete="off">' . + '<div class="captcha-wrapper">' . + '<div class="captcha">' . + '<img src="captcha?v=' . $key . '" alt="Captcha image">' . + '<div class="captcha-controls">' . + '<input type="checkbox" name="c[0]" id="c0">' . + '<label for="c0"></label>' . + '<input type="checkbox" name="c[1]" id="c1">' . + '<label for="c1"></label>' . + '<input type="checkbox" name="c[2]" id="c2">' . + '<label for="c2"></label>' . + '<input type="checkbox" name="c[3]" id="c3">' . + '<label for="c3"></label>' . + '<input type="checkbox" name="c[4]" id="c4">' . + '<label for="c4"></label>' . + '<input type="checkbox" name="c[5]" id="c5">' . + '<label for="c5"></label>' . + '<input type="checkbox" name="c[6]" id="c6">' . + '<label for="c6"></label>' . + '<input type="checkbox" name="c[7]" id="c7">' . + '<label for="c7"></label>' . + '<input type="checkbox" name="c[8]" id="c8">' . + '<label for="c8"></label>' . + '<input type="checkbox" name="c[9]" id="c9">' . + '<label for="c9"></label>' . + '<input type="checkbox" name="c[10]" id="c10">' . + '<label for="c10"></label>' . + '<input type="checkbox" name="c[11]" id="c11">' . + '<label for="c11"></label>' . + '<input type="checkbox" name="c[12]" id="c12">' . + '<label for="c12"></label>' . + '<input type="checkbox" name="c[13]" id="c13">' . + '<label for="c13"></label>' . + '<input type="checkbox" name="c[14]" id="c14">' . + '<label for="c14"></label>' . + '<input type="checkbox" name="c[15]" id="c15">' . + '<label for="c15"></label>' . + '</div>' . + '</div>' . + '</div>' . + '<input type="hidden" name="v" value="' . $key . '">' . + '<input type="submit" value="Check IQ" class="captcha-submit">' . + '</form>' . + '</div>' + ]; + + $frontend->loadheader( + $get, + $filters, + $page + ); + + echo $frontend->load("search.html", $payload); + die(); + } + + private function randomchars(){ + + $chars = + array_merge( + range("A", "Z"), + range("a", "z"), + range(0, 9) + ); + + $chars[] = "_"; + + $c = count($chars) - 1; + + $key = ""; + + for($i=0; $i<20; $i++){ + + $key .= $chars[random_int(0, $c)]; + } + + return $key; + } +} diff --git a/lib/curlproxy.php b/lib/curlproxy.php new file mode 100644 index 0000000..313ab01 --- /dev/null +++ b/lib/curlproxy.php @@ -0,0 +1,660 @@ +<?php + +class proxy{ + + public const req_web = 0; + public const req_image = 1; + + public function __construct($cache = true){ + + $this->cache = $cache; + } + + public function do404(){ + + http_response_code(404); + header("Content-Type: image/png"); + + $handle = fopen("lib/img404.png", "r"); + echo fread($handle, filesize("lib/img404.png")); + fclose($handle); + + die(); + return; + } + + public function getabsoluteurl($path, $relative){ + + if($this->validateurl($path)){ + + return $path; + } + + if(substr($path, 0, 2) == "//"){ + + return "https:" . $path; + } + + $url = null; + + $relative = parse_url($relative); + $url = $relative["scheme"] . "://"; + + if( + isset($relative["user"]) && + isset($relative["pass"]) + ){ + + $url .= $relative["user"] . ":" . $relative["pass"] . "@"; + } + + $url .= $relative["host"]; + + if(isset($relative["path"])){ + + $relative["path"] = explode( + "/", + $relative["path"] + ); + + unset($relative["path"][count($relative["path"]) - 1]); + $relative["path"] = implode("/", $relative["path"]); + + $url .= $relative["path"]; + } + + if( + strlen($path) !== 0 && + $path[0] !== "/" + ){ + + $url .= "/"; + } + + $url .= $path; + + return $url; + } + + public function validateurl($url){ + + $url_parts = parse_url($url); + + // check if required parts are there + if( + !isset($url_parts["scheme"]) || + !( + $url_parts["scheme"] == "http" || + $url_parts["scheme"] == "https" + ) || + !isset($url_parts["host"]) + ){ + return false; + } + + $ip = + str_replace( + ["[", "]"], // handle ipv6 + "", + $url_parts["host"] + ); + + // if its not an IP + if(!filter_var($ip, FILTER_VALIDATE_IP)){ + + // resolve domain's IP + $ip = gethostbyname($url_parts["host"] . "."); + } + + // check if its localhost + if( + filter_var( + $ip, + FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE + ) === false + ){ + + return false; + } + + return true; + } + + public function get($url, $reqtype = self::req_web, $acceptallcodes = false, $referer = null, $redirectcount = 0){ + + if($redirectcount === 5){ + + throw new Exception("Too many redirects"); + } + + if($url == "https://i.imgur.com/removed.png"){ + + throw new Exception("Encountered imgur 404"); + } + + // sanitize URL + if($this->validateurl($url) === false){ + + throw new Exception("Invalid URL"); + } + + $this->clientcache(); + + $curl = curl_init(); + + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curl, CURLOPT_HEADER, 1); + + switch($reqtype){ + case self::req_web: + curl_setopt( + $curl, + CURLOPT_HTTPHEADER, + [ + "User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1" + ] + ); + break; + + case self::req_image: + + if($referer === null){ + $referer = explode("/", $url, 4); + array_pop($referer); + + $referer = implode("/", $referer); + } + + curl_setopt( + $curl, + CURLOPT_HTTPHEADER, + [ + "User-Agent: " . config::USER_AGENT, + "Accept: image/avif,image/webp,*/*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate", + "DNT: 1", + "Connection: keep-alive", + "Referer: {$referer}" + ] + ); + break; + } + + curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + + // limit size of payloads + curl_setopt($curl, CURLOPT_BUFFERSIZE, 1024); + curl_setopt($curl, CURLOPT_NOPROGRESS, false); + curl_setopt( + $curl, + CURLOPT_PROGRESSFUNCTION, + function($downloadsize, $downloaded, $uploadsize, $uploaded + ){ + + // if $downloaded exceeds 100MB, fuck off + return ($downloaded > 100000000) ? 1 : 0; + }); + + $body = curl_exec($curl); + + if(curl_errno($curl)){ + + throw new Exception(curl_error($curl)); + } + + curl_close($curl); + + $headers = []; + $http = null; + + while(true){ + + $header = explode("\n", $body, 2); + $body = $header[1]; + + if($http === null){ + + // http/1.1 200 ok + $header = explode("/", $header[0], 2); + $header = explode(" ", $header[1], 3); + + $http = [ + "version" => (float)$header[0], + "code" => (int)$header[1] + ]; + + continue; + } + + if(trim($header[0]) == ""){ + + // reached end of headers + break; + } + + $header = explode(":", $header[0], 2); + + // malformed headers + if(count($header) !== 2){ continue; } + + $headers[strtolower(trim($header[0]))] = trim($header[1]); + } + + // check http code + if( + $http["code"] >= 300 && + $http["code"] <= 309 + ){ + + // redirect + if(!isset($headers["location"])){ + + throw new Exception("Broken redirect"); + } + + $redirectcount++; + + return $this->get($this->getabsoluteurl($headers["location"], $url), $reqtype, $acceptallcodes, $referer, $redirectcount); + }else{ + if( + $acceptallcodes === false && + $http["code"] > 300 + ){ + + throw new Exception("Remote server returned an error code! ({$http["code"]})"); + } + } + + // check if data is okay + switch($reqtype){ + + case self::req_image: + + $format = false; + + if(isset($headers["content-type"])){ + + if(stripos($headers["content-type"], "text/html") !== false){ + + throw new Exception("Server returned html"); + } + + if( + preg_match( + '/image\/([^ ]+)/i', + $headers["content-type"], + $match + ) + ){ + + $format = strtolower($match[1]); + + if(substr(strtolower($format), 0, 2) == "x-"){ + + $format = substr($format, 2); + } + } + } + + return [ + "http" => $http, + "format" => $format, + "headers" => $headers, + "body" => $body + ]; + break; + + default: + + return [ + "http" => $http, + "headers" => $headers, + "body" => $body + ]; + break; + } + + return; + } + + public function stream_linear_image($url, $referer = null){ + + $this->stream($url, $referer, "image"); + } + + public function stream_linear_audio($url, $referer = null){ + + $this->stream($url, $referer, "audio"); + } + + private function stream($url, $referer, $format){ + + $this->clientcache(); + + $this->url = $url; + $this->format = $format; + + // sanitize URL + if($this->validateurl($url) === false){ + + throw new Exception("Invalid URL"); + } + + $curl = curl_init(); + + // set headers + if($referer === null){ + $referer = explode("/", $url, 4); + array_pop($referer); + + $referer = implode("/", $referer); + } + + switch($format){ + + case "image": + curl_setopt( + $curl, + CURLOPT_HTTPHEADER, + [ + "User-Agent: " . config::USER_AGENT, + "Accept: image/avif,image/webp,*/*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br", + "DNT: 1", + "Connection: keep-alive", + "Referer: {$referer}" + ] + ); + break; + + case "audio": + curl_setopt( + $curl, + CURLOPT_HTTPHEADER, + [ + "User-Agent: " . config::USER_AGENT, + "Accept: audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br", + "DNT: 1", + "Connection: keep-alive", + "Referer: {$referer}" + ] + ); + break; + } + + // follow redirects + curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true); + curl_setopt($curl, CURLOPT_MAXREDIRS, 5); + curl_setopt($curl, CURLOPT_AUTOREFERER, 5); + + // set url + curl_setopt($curl, CURLOPT_URL, $url); + curl_setopt($curl, CURLOPT_ENCODING, ""); // default encoding + + // timeout + disable ssl + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10); + curl_setopt($curl, CURLOPT_TIMEOUT, 30); + + curl_setopt( + $curl, + CURLOPT_WRITEFUNCTION, + function($c, $data){ + + if(curl_getinfo($c, CURLINFO_HTTP_CODE) !== 200){ + + throw new Exception("Serber returned a non-200 code"); + } + + echo $data; + return strlen($data); + } + ); + + $this->empty_header = false; + $this->cont = false; + $this->headers_tmp = []; + $this->headers = []; + curl_setopt( + $curl, + CURLOPT_HEADERFUNCTION, + function($c, $header){ + + $head = trim($header); + $len = strlen($head); + + if($len === 0){ + + $this->empty_header = true; + $this->headers_tmp = []; + }else{ + + $this->empty_header = false; + $this->headers_tmp[] = $head; + } + + foreach($this->headers_tmp as $h){ + + // parse headers + $h = explode(":", $h, 2); + + if(count($h) !== 2){ + + if(curl_getinfo($c, CURLINFO_HTTP_CODE) !== 200){ + + // not HTTP 200, probably a redirect + $this->cont = false; + }else{ + + $this->cont = true; + } + + // is HTTP 200, just ignore that line + continue; + } + + $this->headers[strtolower(trim($h[0]))] = trim($h[1]); + } + + if( + $this->cont && + $this->empty_header + ){ + + // get content type + if(isset($this->headers["content-type"])){ + + $octet_check = stripos($this->headers["content-type"], "octet-stream"); + + if( + stripos($this->headers["content-type"], $this->format) === false && + $octet_check === false + ){ + + throw new Exception("Resource reported invalid Content-Type"); + } + + }else{ + + throw new Exception("Resource is not an {$this->format} (no Content-Type)"); + } + + $filetype = explode("/", $this->headers["content-type"]); + + if(!isset($filetype[1])){ + + throw new Exception("Malformed Content-Type header"); + } + + if($octet_check !== false){ + + $filetype[1] = "jpeg"; + } + + header("Content-Type: {$this->format}/{$filetype[1]}"); + + // give payload size + if(isset($this->headers["content-length"])){ + + header("Content-Length: {$this->headers["content-length"]}"); + } + + // give filename + $this->getfilenameheader($this->headers, $this->url, $filetype[1]); + } + + return strlen($header); + } + ); + + curl_exec($curl); + + if(curl_errno($curl)){ + + throw new Exception(curl_error($curl)); + } + + curl_close($curl); + } + + public function getfilenameheader($headers, $url, $filetype = "jpg"){ + + // get filename from content-disposition header + if(isset($headers["content-disposition"])){ + + preg_match( + '/filename=([^;]+)/', + $headers["content-disposition"], + $filename + ); + + if(isset($filename[1])){ + + header("Content-Disposition: filename=\"" . trim($filename[1], "\"'") . "." . $filetype . "\""); + return; + } + } + + // get filename from URL + $filename = parse_url($url, PHP_URL_PATH); + + if($filename === null){ + + // everything failed! rename file to domain name + header("Content-Disposition: filename=\"" . parse_url($url, PHP_URL_HOST) . "." . $filetype . "\""); + return; + } + + // remove extension from filename + $filename = + explode( + ".", + basename($filename) + ); + + if(count($filename) > 1){ + array_pop($filename); + } + + $filename = implode(".", $filename); + + header("Content-Disposition: inline; filename=\"" . $filename . "." . $filetype . "\""); + return; + } + + public function getimageformat($payload, &$imagick){ + + $finfo = new finfo(FILEINFO_MIME_TYPE); + $format = $finfo->buffer($payload["body"]); + + if($format === false){ + + if($payload["format"] === false){ + + header("X-Error: Could not parse format"); + $this->favicon404(); + } + + $format = $payload["format"]; + }else{ + + $format_tmp = explode("/", $format, 2); + + if($format_tmp[0] == "image"){ + + $format_tmp = strtolower($format_tmp[1]); + + if(substr($format_tmp, 0, 2) == "x-"){ + + $format_tmp = substr($format_tmp, 2); + } + + $format = $format_tmp; + } + } + + switch($format){ + + case "tiff": $format = "gif"; break; + case "vnd.microsoft.icon": $format = "ico"; break; + case "icon": $format = "ico"; break; + case "svg+xml": $format = "svg"; break; + } + + $imagick = new Imagick(); + + if( + !in_array( + $format, + array_map("strtolower", $imagick->queryFormats()) + ) + ){ + + // format could not be found, but imagemagick can + // sometimes detect it? shit's fucked + $format = false; + } + + return $format; + } + + public function clientcache(){ + + if($this->cache === false){ + + return; + } + + header("Last-Modified: Thu, 01 Oct 1970 00:00:00 GMT"); + $headers = getallheaders(); + + if( + isset($headers["If-Modified-Since"]) || + isset($headers["If-Unmodified-Since"]) + ){ + + http_response_code(304); // 304: Not Modified + die(); + } + } +} diff --git a/lib/favicon404.png b/lib/favicon404.png Binary files differnew file mode 100644 index 0000000..fa8f4d1 --- /dev/null +++ b/lib/favicon404.png diff --git a/lib/frontend.php b/lib/frontend.php new file mode 100644 index 0000000..9f819ba --- /dev/null +++ b/lib/frontend.php @@ -0,0 +1,1356 @@ +<?php + +class frontend{ + + public function load($template, $replacements = []){ + + $replacements["server_name"] = htmlspecialchars(config::SERVER_NAME); + $replacements["version"] = config::VERSION; + + if(isset($_COOKIE["theme"])){ + + $theme = str_replace(["/". "."], "", $_COOKIE["theme"]); + + if( + $theme != "Dark" && + !is_file("static/themes/" . $theme . ".css") + ){ + + $theme = config::DEFAULT_THEME; + } + }else{ + + $theme = config::DEFAULT_THEME; + } + + if($theme != "Dark"){ + + $replacements["style"] = '<link rel="stylesheet" href="/static/themes/' . rawurlencode($theme) . '.css?v' . config::VERSION . '">'; + }else{ + + $replacements["style"] = ""; + } + + if(isset($_COOKIE["scraper_ac"])){ + + $replacements["ac"] = '?ac=' . htmlspecialchars($_COOKIE["scraper_ac"]); + }else{ + + $replacements["ac"] = ''; + } + + if( + isset($replacements["timetaken"]) && + $replacements["timetaken"] !== null + ){ + + $replacements["timetaken"] = '<div class="timetaken">Took ' . number_format(microtime(true) - $replacements["timetaken"], 2) . 's</div>'; + } + + $handle = fopen("template/{$template}", "r"); + $data = fread($handle, filesize("template/{$template}")); + fclose($handle); + + $data = explode("\n", $data); + $html = ""; + + for($i=0; $i<count($data); $i++){ + + $html .= trim($data[$i]); + } + + foreach($replacements as $key => $value){ + + $html = + str_replace( + "{%{$key}%}", + $value, + $html + ); + } + + return trim($html); + } + + public function loadheader(array $get, array $filters, string $page){ + + echo + $this->load("header.html", [ + "title" => trim(htmlspecialchars($get["s"]) . " ({$page})"), + "description" => ucfirst($page) . ' search results for "' . htmlspecialchars($get["s"]) . '"', + "index" => "no", + "search" => htmlspecialchars($get["s"]), + "tabs" => $this->generatehtmltabs($page, $get["s"]), + "filters" => $this->generatehtmlfilters($filters, $get) + ]); + + $headers_raw = getallheaders(); + $header_keys = []; + $user_agent = ""; + $bad_header = false; + + // block bots that present X-Forwarded-For, Via, etc + foreach($headers_raw as $headerkey => $headervalue){ + + $headerkey = strtolower($headerkey); + if($headerkey == "user-agent"){ + + $user_agent = $headervalue; + continue; + } + + // check header key + if(in_array($headerkey, config::FILTERED_HEADER_KEYS)){ + + $bad_header = true; + break; + } + } + + // SSL check + $bad_ssl = false; + if( + isset($_SERVER["https"]) && + $_SERVER["https"] == "on" && + isset($_SERVER["SSL_CIPHER"]) && + in_array($_SERVER["SSL_CIPHER"], config::FILTERED_HEADER_KEYS) + ){ + + $bad_ssl = true; + } + + if( + $bad_header === true || + $bad_ssl === true || + $user_agent == "" || + // user agent check + preg_match( + config::HEADER_REGEX, + $user_agent + ) + ){ + + // bot detected !! + apcu_inc("captcha_gen"); + + $this->drawerror( + "Tshh, blocked!", + 'Your browser, IP or IP range has been blocked from this 4get instance. If this is an error, please <a href="/about">contact the administrator</a>.' + ); + die(); + } + } + + public function drawerror($title, $error, $timetaken = null){ + + if($timetaken === null){ + + $timetaken = microtime(true); + } + + echo + $this->load("search.html", [ + "timetaken" => $timetaken, + "class" => "", + "right-left" => "", + "right-right" => "", + "left" => + '<div class="infobox">' . + '<h1>' . htmlspecialchars($title) . '</h1>' . + $error . + '</div>' + ]); + die(); + } + + public function drawscrapererror($error, $get, $target, $timetaken = null){ + + if($timetaken === null){ + + $timetaken = microtime(true); + } + + $this->drawerror( + "Shit", + 'This scraper returned an error:' . + '<div class="code">' . htmlspecialchars($error) . '</div>' . + 'Things you can try:' . + '<ul>' . + '<li>Use a different scraper</li>' . + '<li>Remove keywords that could cause errors</li>' . + '<li><a href="/instances?target=' . $target . "&" . $this->buildquery($get, false) . '">Try your search on another 4get instance</a></li>' . + '</ul><br>' . + 'If the error persists, please <a href="/about">contact the administrator</a>.', + $timetaken + ); + } + + public function drawtextresult($site, $greentext = null, $duration = null, $keywords, $tabindex = true, $customhtml = null){ + + $payload = + '<div class="text-result">'; + + // add favicon, link and archive links + $payload .= $this->drawlink($site["url"]); + + /* + Draw title + description + filetype + */ + $payload .= + '<a href="' . htmlspecialchars($site["url"]) . '" class="hover" rel="noreferrer nofollow"'; + + if($tabindex === false){ + + $payload .= ' tabindex="-1"'; + } + + $payload .= '>'; + + if($site["thumb"]["url"] !== null){ + + $payload .= + '<div class="thumb-wrap'; + + switch($site["thumb"]["ratio"]){ + + case "16:9": + $size = "landscape"; + break; + + case "9:16": + $payload .= " portrait"; + $size = "portrait"; + break; + + case "1:1": + $payload .= " square"; + $size = "square"; + break; + } + + $payload .= + '">' . + '<img class="thumb" src="' . $this->htmlimage($site["thumb"]["url"], $size) . '" alt="thumb">'; + + if($duration !== null){ + + $payload .= + '<div class="duration">' . + htmlspecialchars($duration) . + '</div>'; + } + + $payload .= + '</div>'; + } + + $payload .= + '<div class="title">'; + + if( + isset($site["type"]) && + $site["type"] != "web" + ){ + + $payload .= '<div class="type">' . strtoupper($site["type"]) . '</div>'; + } + + $payload .= + $this->highlighttext($keywords, $site["title"]) . + '</div>'; + + if($greentext !== null){ + + $payload .= + '<div class="greentext">' . + htmlspecialchars($greentext) . + '</div>'; + } + + if($site["description"] !== null){ + + $payload .= + '<div class="description">' . + $this->highlighttext($keywords, $site["description"]) . + '</div>'; + } + + $payload .= $customhtml; + + $payload .= '</a>'; + + /* + Sublinks + */ + if( + isset($site["sublink"]) && + !empty($site["sublink"]) + ){ + + usort($site["sublink"], function($a, $b){ + + return strlen($a["description"]) > strlen($b["description"]); + }); + + $payload .= + '<div class="sublinks">' . + '<table>'; + + $opentr = false; + for($i=0; $i<count($site["sublink"]); $i++){ + + if(($i % 2) === 0){ + + $opentr = true; + $payload .= '<tr>'; + }else{ + + $opentr = false; + } + + $payload .= + '<td>' . + '<a href="' . htmlspecialchars($site["sublink"][$i]["url"]) . '" rel="noreferrer nofollow">' . + '<div class="title">' . + htmlspecialchars($site["sublink"][$i]["title"]) . + '</div>'; + + if(!empty($site["sublink"][$i]["date"])){ + + $payload .= + '<div class="greentext">' . + date("jS M y @ g:ia", $site["sublink"][$i]["date"]) . + '</div>'; + } + + if(!empty($site["sublink"][$i]["description"])){ + + $payload .= + '<div class="description">' . + $this->highlighttext($keywords, $site["sublink"][$i]["description"]) . + '</div>'; + } + + $payload .= '</a></td>'; + + if($opentr === false){ + + $payload .= '</tr>'; + } + } + + if($opentr === true){ + + $payload .= '<td></td></tr>'; + } + + $payload .= '</table></div>'; + } + + if( + isset($site["table"]) && + !empty($site["table"]) + ){ + + $payload .= '<table class="info-table">'; + + foreach($site["table"] as $title => $value){ + + $payload .= + '<tr>' . + '<td>' . htmlspecialchars($title) . '</td>' . + '<td>' . htmlspecialchars($value) . '</td>' . + '</tr>'; + } + + $payload .= '</table>'; + } + + return $payload . '</div>'; + } + + public function highlighttext($keywords, $text){ + + $text = htmlspecialchars($text); + + $keywords = explode(" ", $keywords); + $regex = []; + + foreach($keywords as $word){ + + $regex[] = "\b" . preg_quote($word, "/") . "\b"; + } + + $regex = "/" . implode("|", $regex) . "/i"; + + return + preg_replace( + $regex, + '<b>${0}</b>', + $text + ); + } + + function highlightcode($text){ + + // https://www.php.net/highlight_string + ini_set("highlight.comment", "c-comment"); + ini_set("highlight.default", "c-default"); + ini_set("highlight.html", "c-default"); + ini_set("highlight.keyword", "c-keyword"); + ini_set("highlight.string", "c-string"); + + $text = + trim( + preg_replace( + '/<code [^>]+>/', + "", + str_replace( + [ + "<br />", + " ", + "<pre>", + "</pre>", + "</code>" + ], + [ + "\n", + " ", + "", + "", + "" + ], + explode( + "<?php", + highlight_string("<?php " . $text, true), + 2 + )[1] + ) + ) + ); + + // replace colors + $classes = ["c-comment", "c-default", "c-keyword", "c-string"]; + + foreach($classes as $class){ + + $text = str_replace('<span style="color: ' . $class . '">', '<span class="' . $class . '">', $text); + } + + return $text; + } + + public function drawlink($link){ + + /* + Add favicon + */ + $host = parse_url($link); + $esc = + explode( + ".", + $host["host"], + 2 + ); + + if( + count($esc) === 2 && + $esc[0] == "www" + ){ + + $esc = $esc[1]; + }else{ + + $esc = $esc[0]; + } + + $esc = substr($esc, 0, 2); + + $urlencode = urlencode($link); + + $payload = + '<div class="url">' . + '<button class="favicon" tabindex="-1">' . + '<img src="/favicon?s=' . htmlspecialchars($host["scheme"] . "://" . $host["host"]) . '" alt="' . htmlspecialchars($esc) . '">' . + //'<img src="/404.php" alt="' . htmlspecialchars($esc) . '">' . + '</button>' . + '<div class="favicon-dropdown">'; + + /* + Add archive links + */ + if( + $host["host"] == "boards.4chan.org" || + $host["host"] == "boards.4channel.org" + ){ + + $archives = []; + $path = explode("/", $host["path"]); + $count = count($path); + // /pol/thread/417568063/post-shitty-memes-if-you-want-to + + if($count !== 0){ + + $isboard = true; + + switch($path[1]){ + + case "con": + break; + + case "q": + $archives[] = "desuarchive.org"; + break; + + case "qa": + $archives[] = "desuarchive.org"; + break; + + case "qb": + $archives[] = "arch.b4k.co"; + break; + + case "trash": + $archives[] = "desuarchive.org"; + break; + + case "a": + $archives[] = "desuarchive.org"; + break; + + case "c": + $archives[] = "desuarchive.org"; + break; + + case "w": + break; + + case "m": + $archives[] = "desuarchive.org"; + break; + + case "cgl": + $archives[] = "desuarchive.org"; + $archives[] = "warosu.org"; + break; + + case "f": + $archives[] = "archive.4plebs.org"; + break; + + case "n": + break; + + case "jp": + $archives[] = "warosu.org"; + break; + + case "vt": + $archives[] = "warosu.org"; + break; + + case "v": + $archives[] = "arch.b4k.co"; + break; + + case "vg": + $archives[] = "arch.b4k.co"; + break; + + case "vm": + $archives[] = "arch.b4k.co"; + break; + + case "vmg": + $archives[] = "arch.b4k.co"; + break; + + case "vp": + $archives[] = "arch.b4k.co"; + break; + + case "vr": + $archives[] = "desuarchive.org"; + $archives[] = "warosu.org"; + break; + + case "vrpg": + $archives[] = "arch.b4k.co"; + break; + + case "vst": + $archives[] = "arch.b4k.co"; + break; + + case "co": + $archives[] = "desuarchive.org"; + break; + + case "g": + $archives[] = "desuarchive.org"; + $archives[] = "arch.b4k.co"; + break; + + case "tv": + $archives[] = "archive.4plebs.org"; + break; + + case "k": + $archives[] = "desuarchive.org"; + break; + + case "o": + $archives[] = "archive.4plebs.org"; + break; + + case "an": + $archives[] = "desuarchive.org"; + break; + + case "tg": + $archives[] = "desuarchive.org"; + $archives[] = "archive.4plebs.org"; + break; + + case "sp": + $archives[] = "archive.4plebs.org"; + break; + + case "xs": + $archives[] = "eientei.xyz"; + break; + + case "pw": + break; + + case "sci": + $archives[] = "warosu.org"; + $archives[] = "eientei.xyz"; + break; + + case "his": + $archives[] = "desuarchive.org"; + break; + + case "int": + $archives[] = "desuarchive.org"; + break; + + case "out": + break; + + case "toy": + break; + + case "i": + $archives[] = "archiveofsins.com"; + $archives[] = "eientei.xyz"; + break; + + case "po": + break; + + case "p": + break; + + case "ck": + $archives[] = "warosu.org"; + break; + + case "ic": + $archives[] = "warosu.org"; + break; + + case "wg": + break; + + case "lit": + $archives[] = "warosu.org"; + break; + + case "mu": + $archives[] = "desuarchive.org"; + break; + + case "fa": + $archives[] = "warosu.org"; + break; + + case "3": + $archives[] = "warosu.org"; + $archives[] = "eientei.xyz"; + break; + + case "gd": + break; + + case "diy": + $archives[] = "warosu.org"; + break; + + case "wsg": + $archives[] = "desuarchive.org"; + break; + + case "qst": + break; + + case "biz": + $archives[] = "warosu.org"; + break; + + case "trv": + $archives[] = "archive.4plebs.org"; + break; + + case "fit": + $archives[] = "desuarchive.org"; + break; + + case "x": + $archives[] = "archive.4plebs.org"; + break; + + case "adv": + $archives[] = "archive.4plebs.org"; + break; + + case "lgbt": + $archives[] = "archiveofsins.com"; + break; + + case "mlp": + $archives[] = "desuarchive.org"; + $archives[] = "arch.b4k.co"; + break; + + case "news": + break; + + case "wsr": + break; + + case "vip": + break; + + case "b": + $archives[] = "thebarchive.com"; + break; + + case "r9k": + $archives[] = "desuarchive.org"; + break; + + case "pol": + $archives[] = "archive.4plebs.org"; + break; + + case "bant": + $archives[] = "thebarchive.com"; + break; + + case "soc": + $archives[] = "archiveofsins.com"; + break; + + case "s4s": + $archives[] = "archive.4plebs.org"; + break; + + case "s": + $archives[] = "archiveofsins.com"; + break; + + case "hc": + $archives[] = "archiveofsins.com"; + break; + + case "hm": + $archives[] = "archiveofsins.com"; + break; + + case "h": + $archives[] = "archiveofsins.com"; + break; + + case "e": + break; + + case "u": + $archives[] = "archiveofsins.com"; + break; + + case "d": + $archives[] = "desuarchive.org"; + break; + + case "t": + $archives[] = "archiveofsins.com"; + break; + + case "hr": + $archives[] = "archive.4plebs.org"; + break; + + case "gif": + break; + + case "aco": + $archives[] = "desuarchive.org"; + break; + + case "r": + $archives[] = "archiveofsins.com"; + break; + + default: + $isboard = false; + break; + } + + if($isboard === true){ + + $archives[] = "archived.moe"; + } + + $trail = ""; + + if( + isset($path[2]) && + isset($path[3]) && + $path[2] == "thread" + ){ + + $trail .= "/" . $path[1] . "/thread/" . $path[3]; + }elseif($isboard){ + + $trail = "/" . $path[1] . "/"; + } + + for($i=0; $i<count($archives); $i++){ + + $payload .= + '<a href="https://' . $archives[$i] . $trail . '" class="list" target="_BLANK">' . + '<img src="/favicon?s=https://' . $archives[$i] . '" alt="' . $archives[$i][0] . $archives[$i][1] . '">' . + $archives[$i] . + '</a>'; + } + } + } + + $payload .= + '<a href="https://web.archive.org/web/' . $urlencode . '" class="list" target="_BLANK"><img src="/favicon?s=https://archive.org" alt="ar">Archive.org</a>' . + '<a href="https://archive.ph/newest/' . htmlspecialchars($link) . '" class="list" target="_BLANK"><img src="/favicon?s=https://archive.is" alt="ar">Archive.is</a>' . + '<a href="https://ghostarchive.org/search?term=' . $urlencode . '" class="list" target="_BLANK"><img src="/favicon?s=https://ghostarchive.org" alt="gh">Ghostarchive</a>' . + '<a href="https://arquivo.pt/wayback/' . htmlspecialchars($link) . '" class="list" target="_BLANK"><img src="/favicon?s=https://arquivo.pt" alt="ar">Arquivo.pt</a>' . + '<a href="https://www.bing.com/search?q=url%3A' . $urlencode . '" class="list" target="_BLANK"><img src="/favicon?s=https://bing.com" alt="bi">Bing cache</a>' . + '<a href="https://megalodon.jp/?url=' . $urlencode . '" class="list" target="_BLANK"><img src="/favicon?s=https://megalodon.jp" alt="me">Megalodon</a>' . + '</div>'; + + /* + Draw link + */ + $parts = explode("/", $link); + $clickurl = ""; + + // remove trailing / + $c = count($parts) - 1; + if($parts[$c] == ""){ + + $parts[$c - 1] = $parts[$c - 1] . "/"; + unset($parts[$c]); + } + + // merge https://site together + $parts = [ + $parts[0] . $parts[1] . '//' . $parts[2], + ...array_slice($parts, 3, count($parts) - 1) + ]; + + $c = count($parts); + for($i=0; $i<$c; $i++){ + + if($i !== 0){ $clickurl .= "/"; } + + $clickurl .= $parts[$i]; + + if($i === $c - 1){ + + $parts[$i] = rtrim($parts[$i], "/"); + } + + $payload .= + '<a class="part" href="' . htmlspecialchars($clickurl) . '" rel="noreferrer nofollow" tabindex="-1">' . + htmlspecialchars(urldecode($parts[$i])) . + '</a>'; + + if($i !== $c - 1){ + + $payload .= '<span class="separator"></span>'; + } + } + + return $payload . '</div>'; + } + + public function getscraperfilters($page){ + + $get_scraper = isset($_COOKIE["scraper_$page"]) ? $_COOKIE["scraper_$page"] : null; + + if( + isset($_GET["scraper"]) && + is_string($_GET["scraper"]) + ){ + + $get_scraper = $_GET["scraper"]; + }else{ + + if( + isset($_GET["npt"]) && + is_string($_GET["npt"]) + ){ + + $get_scraper = explode(".", $_GET["npt"], 2)[0]; + + $get_scraper = + preg_replace( + '/[0-9]+$/', + "", + $get_scraper + ); + } + } + + // add search field + $filters = + [ + "s" => [ + "option" => "_SEARCH" + ] + ]; + + // define default scrapers + switch($page){ + + case "web": + $filters["scraper"] = [ + "display" => "Scraper", + "option" => [ + "ddg" => "DuckDuckGo", + "brave" => "Brave", + "yandex" => "Yandex", + "google" => "Google", + //"google_api" => "Google API", + "google_cse" => "Google CSE", + "startpage" => "Startpage", + "qwant" => "Qwant", + "ghostery" => "Ghostery", + "yep" => "Yep", + "greppr" => "Greppr", + "crowdview" => "Crowdview", + "mwmbl" => "Mwmbl", + "mojeek" => "Mojeek", + "baidu" => "Baidu", + "coccoc" => "Cốc Cốc", + //"solofield" => "Solofield", + "marginalia" => "Marginalia", + "wiby" => "wiby", + "curlie" => "Curlie" + ] + ]; + break; + + case "images": + $filters["scraper"] = [ + "display" => "Scraper", + "option" => [ + "ddg" => "DuckDuckGo", + "yandex" => "Yandex", + "brave" => "Brave", + "google" => "Google", + "google_cse" => "Google CSE", + "startpage" => "Startpage", + "qwant" => "Qwant", + "yep" => "Yep", + "baidu" => "Baidu", + //"solofield" => "Solofield", + "pinterest" => "Pinterest", + "cara" => "Cara", + "flickr" => "Flickr", + "fivehpx" => "500px", + "vsco" => "VSCO", + "imgur" => "Imgur", + "ftm" => "FindThatMeme", + //"sankakucomplex" => "SankakuComplex" + ] + ]; + break; + + case "videos": + $filters["scraper"] = [ + "display" => "Scraper", + "option" => [ + "yt" => "YouTube", + "vimeo" => "Vimeo", + //"odysee" => "Odysee", + "sepiasearch" => "Sepia Search", + //"fb" => "Facebook videos", + "ddg" => "DuckDuckGo", + "brave" => "Brave", + "yandex" => "Yandex", + "google" => "Google", + "startpage" => "Startpage", + "qwant" => "Qwant", + "baidu" => "Baidu", + "coccoc" => "Cốc Cốc" + //"solofield" => "Solofield" + ] + ]; + break; + + case "news": + $filters["scraper"] = [ + "display" => "Scraper", + "option" => [ + "ddg" => "DuckDuckGo", + "brave" => "Brave", + "google" => "Google", + "startpage" => "Startpage", + "qwant" => "Qwant", + "yep" => "Yep", + "mojeek" => "Mojeek", + "baidu" => "Baidu" + ] + ]; + break; + + case "music": + $filters["scraper"] = [ + "display" => "Scraper", + "option" => [ + "sc" => "SoundCloud" + //"spotify" => "Spotify" + ] + ]; + break; + } + + // get scraper name from user input, or default out to preferred scraper + $scraper_out = null; + $first = true; + + foreach($filters["scraper"]["option"] as $scraper_name => $scraper_pretty){ + + if($first === true){ + + $first = $scraper_name; + } + + if($scraper_name == $get_scraper){ + + $scraper_out = $scraper_name; + } + } + + if($scraper_out === null){ + + $scraper_out = $first; + } + + include "scraper/$scraper_out.php"; + $lib = new $scraper_out(); + + // set scraper on $_GET + $_GET["scraper"] = $scraper_out; + + // set nsfw on $_GET + if( + isset($_COOKIE["nsfw"]) && + !isset($_GET["nsfw"]) + ){ + + $_GET["nsfw"] = $_COOKIE["nsfw"]; + } + + return + [ + $lib, + array_merge_recursive( + $filters, + $lib->getfilters($page) + ) + ]; + } + + public function parsegetfilters($parameters, $whitelist){ + + $sanitized = []; + + // add npt token + if( + isset($parameters["npt"]) && + is_string($parameters["npt"]) + ){ + + $sanitized["npt"] = $parameters["npt"]; + }else{ + + $sanitized["npt"] = false; + } + + // we're iterating over $whitelist, so + // you can't polluate $sanitized with useless + // parameters + foreach($whitelist as $parameter => $value){ + + if(isset($parameters[$parameter])){ + + if(!is_string($parameters[$parameter])){ + + $sanitized[$parameter] = null; + continue; + } + + // parameter is already set, use that value + $sanitized[$parameter] = $parameters[$parameter]; + }else{ + + // parameter is not set, add it + if(is_string($value["option"])){ + + // special field: set default value manually + switch($value["option"]){ + + case "_DATE": + // no date set + $sanitized[$parameter] = false; + break; + + case "_SEARCH": + // no search set + $sanitized[$parameter] = ""; + break; + } + + }else{ + + // set a default value + $sanitized[$parameter] = array_keys($value["option"])[0]; + } + } + + // sanitize input + if(is_array($value["option"])){ + if( + !in_array( + $sanitized[$parameter], + $keys = array_keys($value["option"]) + ) + ){ + + $sanitized[$parameter] = $keys[0]; + } + }else{ + + // sanitize search & string + switch($value["option"]){ + + case "_DATE": + if($sanitized[$parameter] !== false){ + + $sanitized[$parameter] = strtotime($sanitized[$parameter]); + if($sanitized[$parameter] <= 0){ + + $sanitized[$parameter] = false; + } + } + break; + + case "_SEARCH": + // get search string + $sanitized["s"] = trim($sanitized[$parameter]); + } + } + } + + // invert dates if needed + if( + isset($sanitized["older"]) && + isset($sanitized["newer"]) && + $sanitized["newer"] !== false && + $sanitized["older"] !== false && + $sanitized["newer"] > $sanitized["older"] + ){ + + // invert + [ + $sanitized["older"], + $sanitized["newer"] + ] = [ + $sanitized["newer"], + $sanitized["older"] + ]; + } + + return $sanitized; + } + + public function s_to_timestamp($seconds){ + + if(is_string($seconds)){ + + return "LIVE"; + } + + return ($seconds >= 60) ? ltrim(gmdate("H:i:s", $seconds), ":0") : gmdate("0:s", $seconds); + } + + public function generatehtmltabs($page, $query){ + + $html = null; + + foreach(["web", "images", "videos", "news", "music"] as $type){ + + $html .= '<a href="/' . $type . '?s=' . urlencode($query); + + if(!empty($params)){ + + $html .= $params; + } + + $html .= '" class="tab'; + + if($type == $page){ + + $html .= ' selected'; + } + + $html .= '">' . ucfirst($type) . '</a>'; + } + + return $html; + } + + public function generatehtmlfilters($filters, $params){ + + $html = null; + + foreach($filters as $filter_name => $filter_values){ + + if(!isset($filter_values["display"])){ + + continue; + } + + $output = true; + $tmp = + '<div class="filter">' . + '<div class="title">' . htmlspecialchars($filter_values["display"]) . '</div>'; + + if(is_array($filter_values["option"])){ + + $tmp .= '<select name="' . $filter_name . '">'; + + foreach($filter_values["option"] as $option_name => $option_title){ + + $tmp .= '<option value="' . $option_name . '"'; + + if($params[$filter_name] == $option_name){ + + $tmp .= ' selected'; + } + + $tmp .= '>' . htmlspecialchars($option_title) . '</option>'; + } + + $tmp .= '</select>'; + }else{ + + switch($filter_values["option"]){ + + case "_DATE": + $tmp .= '<input type="date" name="' . $filter_name . '"'; + + if($params[$filter_name] !== false){ + + $tmp .= ' value="' . date("Y-m-d", $params[$filter_name]) . '"'; + } + + $tmp .= '>'; + break; + + default: + $output = false; + break; + } + } + + $tmp .= '</div>'; + + if($output === true){ + + $html .= $tmp; + } + } + + return $html; + } + + public function buildquery($gets, $ommit = false){ + + $out = []; + foreach($gets as $key => $value){ + + if( + $value == null || + $value == false || + $key == "npt" || + $key == "extendedsearch" || + $value == "any" || + $value == "all" || + $key == "spellcheck" || + ( + $ommit === true && + $key == "s" + ) + ){ + + continue; + } + + if( + $key == "older" || + $key == "newer" + ){ + + $value = date("Y-m-d", (int)$value); + } + + $out[$key] = $value; + } + + return http_build_query($out); + } + + public function htmlimage($image, $format){ + + if( + preg_match( + '/^data:/', + $image + ) + ){ + + return htmlspecialchars($image); + } + + return "/proxy?i=" . urlencode($image) . "&s=" . $format; + } + + public function htmlnextpage($gets, $npt, $page){ + + $query = $this->buildquery($gets); + + return $page . "?" . $query . "&npt=" . $npt; + } +} diff --git a/lib/fuckhtml.php b/lib/fuckhtml.php new file mode 100644 index 0000000..3ea256f --- /dev/null +++ b/lib/fuckhtml.php @@ -0,0 +1,622 @@ +<?php +class fuckhtml{ + + public function __construct($html = null, $isfile = false){ + + if($html !== null){ + + $this->load($html, $isfile); + } + } + + public function load($html, $isfile = false){ + + if(is_array($html)){ + + if(!isset($html["innerHTML"])){ + + throw new Exception("(load) Supplied array doesn't contain an innerHTML index"); + } + $html = $html["innerHTML"]; + } + + if($isfile){ + + $handle = fopen($html, "r"); + $fetch = fread($handle, filesize($html)); + fclose($handle); + + $this->html = $fetch; + }else{ + + $this->html = $html; + } + + $this->strlen = strlen($this->html); + } + + public function getloadedhtml(){ + + return $this->html; + } + + public function getElementsByTagName(string $tagname){ + + $out = []; + + /* + Scrape start of the tag. Example + <div class="mydiv"> ... + */ + + if($tagname == "*"){ + + $tagname = '[A-Za-z0-9._-]+'; + }else{ + + $tagname = preg_quote(strtolower($tagname)); + } + + preg_match_all( + '/<\s*(' . $tagname . ')(\s(?:[^>\'"]*|"[^"]*"|\'[^\']*\')+)?\s*>/i', + /* '/<\s*(' . $tagname . ')(\s[\S\s]*?)?>/i', */ + $this->html, + $starting_tags, + PREG_OFFSET_CAPTURE + ); + + for($i=0; $i<count($starting_tags[0]); $i++){ + + /* + Parse attributes + */ + $attributes = []; + + preg_match_all( + '/([^\/\s\\=]+)(?:\s*=\s*("[^"]*"|\'[^\']*\'|[^\s]*))?/i', + $starting_tags[2][$i][0], + $regex_attributes + ); + + for($k=0; $k<count($regex_attributes[0]); $k++){ + + if(trim($regex_attributes[2][$k]) == ""){ + + $attributes[$regex_attributes[1][$k]] = + "true"; + + continue; + } + + $attributes[strtolower($regex_attributes[1][$k])] = + trim($regex_attributes[2][$k], "'\" \n\r\t\v\x00"); + } + + $out[] = [ + "tagName" => strtolower($starting_tags[1][$i][0]), + "startPos" => $starting_tags[0][$i][1], + "endPos" => 0, + "startTag" => $starting_tags[0][$i][0], + "attributes" => $attributes, + "innerHTML" => null + ]; + } + + /* + Get innerHTML + */ + // get closing tag positions + preg_match_all( + '/<\s*\/\s*(' . $tagname . ')\s*>/i', + $this->html, + $regex_closing_tags, + PREG_OFFSET_CAPTURE + ); + + // merge opening and closing tags together + for($i=0; $i<count($regex_closing_tags[1]); $i++){ + + $out[] = [ + "tagName" => strtolower($regex_closing_tags[1][$i][0]), + "endTag" => $regex_closing_tags[0][$i][0], + "startPos" => $regex_closing_tags[0][$i][1] + ]; + } + + usort( + $out, + function($a, $b){ + + return $a["startPos"] > $b["startPos"]; + } + ); + + // compute the indent level for each element + $level = []; + $count = count($out); + + for($i=0; $i<$count; $i++){ + + if(!isset($level[$out[$i]["tagName"]])){ + + $level[$out[$i]["tagName"]] = 0; + } + + if(isset($out[$i]["startTag"])){ + + // encountered starting tag + $level[$out[$i]["tagName"]]++; + $out[$i]["level"] = $level[$out[$i]["tagName"]]; + }else{ + + // encountered closing tag + $out[$i]["level"] = $level[$out[$i]["tagName"]]; + $level[$out[$i]["tagName"]]--; + } + } + + // if the indent level is the same for a div, + // we encountered _THE_ closing tag + for($i=0; $i<$count; $i++){ + + if(!isset($out[$i]["startTag"])){ + + continue; + } + + for($k=$i; $k<$count; $k++){ + + if( + isset($out[$k]["endTag"]) && + $out[$i]["tagName"] == $out[$k]["tagName"] && + $out[$i]["level"] + === $out[$k]["level"] + ){ + + $startlen = strlen($out[$i]["startTag"]); + $endlen = strlen($out[$k]["endTag"]); + + $out[$i]["endPos"] = $out[$k]["startPos"] + $endlen; + + $out[$i]["innerHTML"] = + substr( + $this->html, + $out[$i]["startPos"] + $startlen, + $out[$k]["startPos"] - ($out[$i]["startPos"] + $startlen) + ); + + $out[$i]["outerHTML"] = + substr( + $this->html, + $out[$i]["startPos"], + $out[$k]["startPos"] - $out[$i]["startPos"] + $endlen + ); + + break; + } + } + } + + // filter out ending divs + for($i=0; $i<$count; $i++){ + + if(isset($out[$i]["endTag"])){ + + unset($out[$i]); + } + + unset($out[$i]["startTag"]); + } + + return array_values($out); + } + + public function getElementsByAttributeName(string $name, $collection = null){ + + if($collection === null){ + + $collection = $this->getElementsByTagName("*"); + }elseif(is_string($collection)){ + + $collection = $this->getElementsByTagName($collection); + } + + $return = []; + foreach($collection as $elem){ + + foreach($elem["attributes"] as $attrib_name => $attrib_value){ + + if($attrib_name == $name){ + + $return[] = $elem; + continue 2; + } + } + } + + return $return; + } + + public function getElementsByFuzzyAttributeValue(string $name, string $value, $collection = null){ + + $elems = $this->getElementsByAttributeName($name, $collection); + + $value = + explode( + " ", + trim( + preg_replace( + '/\s+/', + " ", + $value + ) + ) + ); + + $return = []; + + foreach($elems as $elem){ + + foreach($elem["attributes"] as $attrib_name => $attrib_value){ + + $attrib_value = + explode( + " ", + trim( + preg_replace( + '/\s+/', + " ", + $attrib_value + ) + ) + ); + + $ac = count($attrib_value); + $nc = count($value); + $cr = 0; + + for($i=0; $i<$nc; $i++){ + + for($k=0; $k<$ac; $k++){ + + if($value[$i] == $attrib_value[$k]){ + + $cr++; + } + } + } + + if($cr === $nc){ + + $return[] = $elem; + continue 2; + } + } + } + + return $return; + } + + public function getElementsByAttributeValue(string $name, string $value, $collection = null){ + + $elems = $this->getElementsByAttributeName($name, $collection); + + $return = []; + + foreach($elems as $elem){ + + foreach($elem["attributes"] as $attrib_name => $attrib_value){ + + if($attrib_value == $value){ + + $return[] = $elem; + continue 2; + } + } + } + + return $return; + } + + public function getElementById(string $idname, $collection = null){ + + $id = $this->getElementsByAttributeValue("id", $idname, $collection); + + if(count($id) !== 0){ + + return $id[0]; + } + + return false; + } + + public function getElementsByClassName(string $classname, $collection = null){ + + return $this->getElementsByFuzzyAttributeValue("class", $classname, $collection); + } + + public function getTextContent($html, $whitespace = false, $trim = true){ + + if(is_array($html)){ + + if(!isset($html["innerHTML"])){ + + throw new Exception("(getTextContent) Supplied array doesn't contain an innerHTML index"); + } + + $html = $html["innerHTML"]; + } + + $html = preg_split('/\n|<\/?br>/i', $html); + + $out = ""; + for($i=0; $i<count($html); $i++){ + + $tmp = + html_entity_decode( + strip_tags( + $html[$i] + ), + ENT_QUOTES | ENT_XML1, "UTF-8" + ); + + if($trim){ + + $tmp = trim($tmp); + } + + $out .= $tmp; + + if($whitespace === true){ + + $out .= "\n"; + }else{ + + $out .= " "; + } + } + + if($trim){ + + return trim($out); + } + + return $out; + } + + public function parseJsObject(string $json){ + + $bracket = false; + $is_close_bracket = false; + $escape = false; + $lastchar = false; + $json_out = null; + $last_char = null; + + $keyword_check = null; + + for($i=0; $i<strlen($json); $i++){ + + switch($json[$i]){ + + case "\"": + case "'": + if($escape === true){ + + break; + } + + if($json[$i] == $bracket){ + + $bracket = false; + $is_close_bracket = true; + + }else{ + + if($bracket === false){ + + $bracket = $json[$i]; + } + } + break; + + default: + $is_close_bracket = false; + break; + } + + if( + $json[$i] == "\\" && + !( + $lastchar !== false && + $lastchar . $json[$i] == "\\\\" + ) + ){ + + $escape = true; + }else{ + + $escape = false; + } + + if( + $bracket === false && + $is_close_bracket === false + ){ + + // do keyword check + $keyword_check .= $json[$i]; + + if(in_array($json[$i], [":", "{"])){ + + $keyword_check = substr($keyword_check, 0, -1); + + if( + preg_match( + '/function|array|return/i', + $keyword_check + ) + ){ + + $json_out = + preg_replace( + '/[{"]*' . preg_quote($keyword_check, "/") . '$/', + "", + $json_out + ); + } + + $keyword_check = null; + } + + // here we know we're not iterating over a quoted string + switch($json[$i]){ + + case "[": + case "{": + $json_out .= $json[$i]; + break; + + case "]": + case "}": + case ",": + case ":": + if(!in_array($last_char, ["[", "{", "}", "]", "\""])){ + + $json_out .= "\""; + } + + $json_out .= $json[$i]; + break; + + default: + if(in_array($last_char, ["{", "[", ",", ":"])){ + + $json_out .= "\""; + } + + $json_out .= $json[$i]; + break; + } + }else{ + + $json_out .= $json[$i]; + } + + $last_char = $json[$i]; + } + + return json_decode($json_out, true); + } + + public function parseJsString($string){ + + return + preg_replace_callback( + '/\\\u[A-Fa-f0-9]{4}|\\\x[A-Fa-f0-9]{2}|\\\n|\\\r/', + function($match){ + + switch($match[0][1]){ + + case "u": + return json_decode('"' . $match[0] . '"'); + break; + + case "x": + return mb_convert_encoding( + stripcslashes($match[0]), + "utf-8", + "windows-1252" + ); + break; + + default: + return " "; + break; + } + }, + $string + ); + } + + public function extract_json($json){ + + $len = strlen($json); + $array_level = 0; + $object_level = 0; + $in_quote = null; + $start = null; + + for($i=0; $i<$len; $i++){ + + switch($json[$i]){ + + case "[": + if($in_quote === null){ + + $array_level++; + if($start === null){ + + $start = $i; + } + } + break; + + case "]": + if($in_quote === null){ + + $array_level--; + } + break; + + case "{": + if($in_quote === null){ + + $object_level++; + if($start === null){ + + $start = $i; + } + } + break; + + case "}": + if($in_quote === null){ + + $object_level--; + } + break; + + case "\"": + case "'": + if( + $i !== 0 && + $json[$i - 1] !== "\\" + ){ + // found a non-escaped quote + + if($in_quote === null){ + + // open quote + $in_quote = $json[$i]; + }elseif($in_quote === $json[$i]){ + + // close quote + $in_quote = null; + } + } + break; + } + + if( + $start !== null && + $array_level === 0 && + $object_level === 0 + ){ + + return substr($json, $start, $i - $start + 1); + break; + } + } + } +} diff --git a/lib/img404.png b/lib/img404.png Binary files differnew file mode 100644 index 0000000..e8588cf --- /dev/null +++ b/lib/img404.png diff --git a/lib/type-todo.php b/lib/type-todo.php new file mode 100644 index 0000000..f813543 --- /dev/null +++ b/lib/type-todo.php @@ -0,0 +1,132 @@ + + public function type($get){ + + $search = $get["s"]; + $bang = $get["bang"]; + + if(empty($search)){ + + if(!empty($bang)){ + + // !youtube + $conn = pg_connect("host=localhost dbname=4get user=postgres password=postgres"); + + pg_prepare($conn, "bang_get", "SELECT bang,name FROM bangs WHERE bang LIKE $1 ORDER BY bang ASC LIMIT 8"); + $q = pg_execute($conn, "bang_get", ["$bang%"]); + + $results = []; + while($row = pg_fetch_array($q, null, PGSQL_ASSOC)){ + + $results[] = [ + "s" => "!" . $row["bang"], + "n" => $row["name"] + ]; + } + + return $results; + }else{ + + // everything is empty + // lets just return a bang list + return [ + [ + "s" => "!w", + "n" => "Wikipedia", + "u" => "https://en.wikipedia.org/wiki/Special:Search?search={%q%}" + ], + [ + "s" => "!4ch", + "n" => "4chan Board", + "u" => "https://find.4chan.org/?q={%q%}" + ], + [ + "s" => "!a", + "n" => "Amazon", + "u" => "https://www.amazon.com/s?k={%q%}" + ], + [ + "s" => "!e", + "n" => "eBay", + "u" => "https://www.ebay.com/sch/items/?_nkw={%q%}" + ], + [ + "s" => "!so", + "n" => "Stack Overflow", + "u" => "http://stackoverflow.com/search?q={%q%}" + ], + [ + "s" => "!gh", + "n" => "GitHub", + "u" => "https://github.com/search?utf8=%E2%9C%93&q={%q%}" + ], + [ + "s" => "!tw", + "n" => "Twitter", + "u" => "https://twitter.com/search?q={%q%}" + ], + [ + "s" => "!r", + "n" => "Reddit", + "u" => "https://www.reddit.com/search?q={%q%}" + ], + ]; + } + } + + // now we know search isnt empty + if(!empty($bang)){ + + // check if the bang exists + $conn = pg_connect("host=localhost dbname=4get user=postgres password=postgres"); + + pg_prepare($conn, "bang_get_single", "SELECT bang,name FROM bangs WHERE bang = $1 LIMIT 1"); + $q = pg_execute($conn, "bang_get_single", [$bang]); + + $row = pg_fetch_array($q, null, PGSQL_ASSOC); + + if(isset($row["bang"])){ + + $bang = "!$bang "; + }else{ + + $bang = ""; + } + } + + try{ + $res = $this->get( + "https://duckduckgo.com/ac/", + [ + "q" => strtolower($search) + ], + ddg::req_xhr + ); + + $res = json_decode($res, true); + + }catch(Exception $e){ + + throw new Exception("Failed to get /ac/"); + } + + $arr = []; + for($i=0; $i<count($res); $i++){ + + if($i === 8){break;} + + if(empty($bang)){ + + $arr[] = [ + "s" => $res[$i]["phrase"] + ]; + }else{ + + $arr[] = [ + "s" => $bang . $res[$i]["phrase"], + "n" => $row["name"] + ]; + } + } + + return $arr; + } diff --git a/license.txt b/license.txt new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/license.txt @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<https://www.gnu.org/licenses/>. diff --git a/music.php b/music.php new file mode 100644 index 0000000..c49fc08 --- /dev/null +++ b/music.php @@ -0,0 +1,222 @@ +<?php + +/* + Initialize random shit +*/ +include "data/config.php"; + +include "lib/frontend.php"; +$frontend = new frontend(); + +[$scraper, $filters] = $frontend->getscraperfilters("music"); + +$get = $frontend->parsegetfilters($_GET, $filters); + +/* + Captcha +*/ +include "lib/bot_protection.php"; +new bot_protection($frontend, $get, $filters, "music", true); + +$payload = [ + "timetaken" => microtime(true), + "class" => "", + "right-left" => "", + "right-right" => "", + "left" => "" +]; + +try{ + $results = $scraper->music($get); + +}catch(Exception $error){ + + $frontend->drawscrapererror($error->getMessage(), $get, "music", $payload["timetaken"]); +} + +$categories = [ + "song" => "", + "author" => "", + "playlist" => "", + "album" => "", + "podcast" => "", + "user" => "" +]; + +/* + Set the main container +*/ +$main = null; + +if(count($results["song"]) !== 0){ + + $main = "song"; + +}elseif(count($results["album"]) !== 0){ + + $main = "album"; + +}elseif(count($results["playlist"]) !== 0){ + + $main = "playlist"; + +}elseif(count($results["podcast"]) !== 0){ + + $main = "podcast"; + +}elseif(count($results["author"]) !== 0){ + + $main = "author"; + +}elseif(count($results["user"]) !== 0){ + + $main = "user"; + +}else{ + + // No results found! + echo + $frontend->drawerror( + "Nobody here but us chickens!", + 'Have you tried:' . + '<ul>' . + '<li>Using a different scraper</li>' . + '<li>Using fewer keywords</li>' . + '<li>Defining broader filters (Is NSFW turned off?)</li>' . + '</ul>' . + '</div>' + ); + die(); +} + +/* + Generate list of songs +*/ +foreach($categories as $name => $data){ + + foreach($results[$name] as $item){ + + $greentext = []; + + if( + isset($item["date"]) && + $item["date"] !== null + ){ + + $greentext[] = date("jS M y @ g:ia", $item["date"]); + } + + if( + isset($item["views"]) && + $item["views"] !== null + ){ + + $views = number_format($item["views"]) . " views"; + $greentext[] = $views; + } + + if( + isset($item["followers"]) && + $item["followers"] !== null + ){ + + $greentext[] = number_format($item["followers"]) . " followers"; + } + + if( + isset($item["author"]["name"]) && + $item["author"]["name"] !== null + ){ + + $greentext[] = $item["author"]["name"]; + } + + $greentext = implode(" • ", $greentext); + + if( + isset($item["duration"]) && + $item["duration"] !== null + ){ + + $duration = $frontend->s_to_timestamp($item["duration"]); + }else{ + + $duration = null; + } + + $tabindex = $name == $main ? true : false; + + $customhtml = null; + + if( + ( + $name == "song" || + $name == "podcast" + ) && + $item["stream"]["endpoint"] !== null + ){ + + $customhtml = + '<audio src="/audio/' . $item["stream"]["endpoint"] . '?s=' . urlencode($item["stream"]["url"]) . '" controls autostart="false" preload="none">'; + } + + $categories[$name] .= $frontend->drawtextresult($item, $greentext, $duration, $get["s"], $tabindex, $customhtml); + } +} + +$payload["left"] = $categories[$main]; + +// dont re-draw the category +unset($categories[$main]); + +/* + Populate right handside +*/ + +$i = 1; +foreach($categories as $name => $value){ + + if($value == ""){ + + continue; + } + + if($i % 2 === 1){ + + $write = "right-left"; + }else{ + + $write = "right-right"; + } + + $payload[$write] .= + '<div class="answer-wrapper">' . + '<input id="answer' . $i . '" class="spoiler" type="checkbox">' . + '<div class="answer">' . + '<div class="answer-title">' . + '<a class="answer-title" href="?s=' . urlencode($get["s"]); + + $payload[$write] .= + '&type=' . $name . '"><h2>' . ucfirst($name) . 's</h2></a>'; + + $payload[$write] .= + '</div>' . + $categories[$name] . + '</div>' . + '<label class="spoiler-button" for="answer' . $i . '"></label></div>'; + + $i++; +} + +if($i !== 1){ + + $payload["class"] = " has-answer"; +} + +if($results["npt"] !== null){ + + $payload["left"] .= + '<a href="' . $frontend->htmlnextpage($get, $results["npt"], "music") . '" class="nextpage">Next page ></a>'; +} + +echo $frontend->load("search.html", $payload); diff --git a/news.php b/news.php new file mode 100644 index 0000000..b205819 --- /dev/null +++ b/news.php @@ -0,0 +1,86 @@ +<?php + +/* + Initialize random shit +*/ +include "data/config.php"; + +include "lib/frontend.php"; +$frontend = new frontend(); + +[$scraper, $filters] = $frontend->getscraperfilters("news"); + +$get = $frontend->parsegetfilters($_GET, $filters); + +/* + Captcha +*/ +include "lib/bot_protection.php"; +new bot_protection($frontend, $get, $filters, "news", true); + +$payload = [ + "timetaken" => microtime(true), + "class" => "", + "right-left" => "", + "right-right" => "", + "left" => "" +]; + +try{ + $results = $scraper->news($get); + +}catch(Exception $error){ + + $frontend->drawscrapererror($error->getMessage(), $get, "news", $payload["timetaken"]); +} + +/* + Populate links +*/ +if(count($results["news"]) === 0){ + + $payload["left"] = + '<div class="infobox">' . + "<h1>Nobody here but us chickens!</h1>" . + 'Have you tried:' . + '<ul>' . + '<li>Using a different scraper</li>' . + '<li>Using fewer keywords</li>' . + '<li>Defining broader filters (Is NSFW turned off?)</li>' . + '</ul>' . + '</div>'; +} + +foreach($results["news"] as $news){ + + $greentext = []; + + if($news["date"] !== null){ + + $greentext[] = date("jS M y @ g:ia", $news["date"]); + } + + if($news["author"] !== null){ + + $greentext[] = htmlspecialchars($news["author"]); + } + + if(count($greentext) !== 0){ + + $greentext = implode(" • ", $greentext); + }else{ + + $greentext = null; + } + + $n = null; + $payload["left"] .= $frontend->drawtextresult($news, $greentext, $n, $get["s"]); +} + +if($results["npt"] !== null){ + + $payload["left"] .= + '<a href="' . $frontend->htmlnextpage($get, $results["npt"], "news") . '" class="nextpage">Next page ></a>'; +} + +echo $frontend->load("search.html", $payload); diff --git a/opensearch.php b/opensearch.php new file mode 100644 index 0000000..4bdf97c --- /dev/null +++ b/opensearch.php @@ -0,0 +1,42 @@ +<?php + +header("Content-Type: application/xml"); +include "data/config.php"; + +$domain = + htmlspecialchars( + (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on" ? "https" : "http") . + '://' . $_SERVER["HTTP_HOST"] + ); + +if( + preg_match( + '/\.onion$/', + $domain + ) +){ + + $onion = true; +}else{ + + $onion = false; +} + +echo + '<?xml version="1.0" encoding="UTF-8"?>' . + '<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">' . + '<ShortName>' . htmlspecialchars(config::SERVER_NAME) . ($onion ? " (onion)" : "") . '</ShortName>' . + '<InputEncoding>UTF-8</InputEncoding>' . + '<Image width="16" height="16">' . $domain . '/favicon.ico</Image>' . + '<Url type="text/html" method="GET" template="' . $domain . '/web?s={searchTerms}"/>'; + +if( + isset($_GET["ac"]) && + is_string($_GET["ac"]) && + $_GET["ac"] != "disabled" +){ + + echo '<Url rel="suggestions" type="application/x-suggestions+json" template="' . $domain . '/api/v1/ac?s={searchTerms}&scraper=' . htmlspecialchars($_GET["ac"]) . '"/>'; +} + +echo '</OpenSearchDescription>'; diff --git a/oracles/base.php b/oracles/base.php new file mode 100644 index 0000000..84299fd --- /dev/null +++ b/oracles/base.php @@ -0,0 +1,36 @@ +<?php +abstract class oracle { + // some info to spit out alongside the result, so the user knows + // what exactly is giving out the answer. prevents confusion + // about what oracle is answering them for ambiguous queries. + public $info = [ + "name" => "some oracle" + ]; + // this function should take in a query string search from $_GET, + // and return a bool determining whether or not it is a question + // intended for the oracle. + public function check_query($q) { + return false; + } + // produce the correct answer for the query using the oracle. + // note: if it becomes apparent /during generation/ that the + // query is not in fact for the oracle, returning an empty + // string will kill the oracle pane. + // answer format: ["ans1 title" => "ans1", ...] + public function generate_response($q) { + return ""; + } +} +// backwards compatibility +if (!function_exists('str_starts_with')) { + function str_starts_with($haystack, $needle) { + return strncmp($haystack, $needle, strlen($needle)) === 0;; + } +} +if (!function_exists('str_contains')) { + function str_contains($haystack, $needle) { + return strpos((string)$haystack, (string)$needle) !== false; + } +} + +?>
\ No newline at end of file diff --git a/oracles/calc.php b/oracles/calc.php new file mode 100644 index 0000000..833749e --- /dev/null +++ b/oracles/calc.php @@ -0,0 +1,165 @@ +<?php +include_once("oracles/base.php"); +class calculator extends oracle { + public $info = [ + "name" => "calculator" + ]; + public function check_query($q) { + // straight numerics should go to that oracle + if (is_numeric($q)) { + return false; + } + // all chars should be number-y or operator-y + $char_whitelist = str_split("1234567890.+-/*^%() "); + foreach (str_split($q) as $char) { + if (!in_array($char, $char_whitelist)) { + return false; + } + } + return true; + } + // a custom parser and calculator because FUCK YUO, libraries are + // gay. + public function generate_response($q) + { + $nums = str_split("1234567890."); + $ops = str_split("+-/*^%;"); + $grouping = str_split("()"); + + $q = str_replace(" ", "", $q); + + // backstop for the parser so it catches the last + // numeric token + $q .= ";"; + + // the following comments refer to this example input: + // 21+9*(3+2^9)+1 + + // 2-length lists of the following patterns: + // ["n" (umeric), <some number>] + // ["o" (perator), "<some operator>"] + // ["g" (roup explicit), <"(" or ")">] + // e.g. [["n", 21], ["o", "+"], ["n", 9], ["o", *], + // ["g", "("], ["n", 3], ["o", "+"], ["n", 2], + // ["o", "^"], ["n", 9], ["g", ")"], ["o", "+"], + // ["n", "1"]] + $tokens = array(); + $dragline = 0; + foreach(str_split($q) as $i=>$char) { + if (in_array($char, $nums)) { + continue; + } + elseif (in_array($char, $ops) || in_array($char, $grouping)) { + // hitting a non-numeric implies everything since the + // last hit has been part of a number + $capture = substr($q, $dragline, $i - $dragline); + // prevent the int cast from creating imaginary + // ["n", 0] tokens + if ($capture != "") { + if (substr_count($capture, ".") > 1) { + return ""; + } + array_push($tokens, ["n", (float)$capture]); + } + // reset to one past the current (non-numeric) char + $dragline = $i + 1; + // the `;' backstop is not a real token and this should + // never be present in the token list + if ($char != ";") { + array_push($tokens, [ + ($char == "(" || $char == ")") ? "g" : "o", + $char + ]); + } + } + else { + return ""; + } + } + + // two operators back to back should fail + for ($i = 1; $i < count($tokens); $i++) { + if ($tokens[$i][0] == "o" && $tokens[$i-1][0] == "o") { + return ""; + } + } + + // no implicit multiplication + for ($i = 0; $i < count($tokens) - 1; $i++) { + if ($tokens[$i][0] == "n" && $tokens[$i+1] == ["g", "("]) { + return ""; + } + } + + //strategy: + // traverse to group open (if there is one) + // - return to start with the internals + // traverse to ^, attack token previous and after + // same but for *, then / then + then - + // poppers all teh way down + try { + return [ + substr($q, 0, strlen($q)-1)." = " => $this->executeBlock($tokens)[0][1] + ]; + } + catch (\Throwable $e) { + if (get_class($e) == "DivisionByZeroError") { + return [ + $q." = " => "Division by Zero Error!!" + ]; + } + return ""; + } + } + public function executeBlock($tokens) { + if (count($tokens) >= 2 && $tokens[0][0] == "o" && $tokens[0][1] == "-" && $tokens[1][0] == "n") { + array_splice($tokens, 0, 2, [["n", -1 * (float)$tokens[1][1]]]); + } + if (count($tokens) > 0 && $tokens[0][0] == "o" || $tokens[count($tokens)-1][0] == "o") { + throw new Exception("Error Processing Request", 1); + } + while (in_array(["g", "("], $tokens)) { + $first_open = array_search(["g", "("], $tokens); + $enclosedality = 1; + for ($i = $first_open+1; $i < count($tokens); $i++) { + if ($tokens[$i][0] == "g") { + $enclosedality += ($tokens[$i][1] == "(") ? 1 : -1; + } + if ($enclosedality == 0) { + array_splice($tokens, + $first_open, + $i+1 - $first_open, + $this->executeBlock( + array_slice($tokens, $first_open+1, $i-1 - $first_open) + ) + ); + break; + } + } + } + $operators_in_pemdas_order = [ + "^" => (fn($x, $y) => $x ** $y), + "*" => (fn($x, $y) => $x * $y), + "/" => (fn($x, $y) => $x / $y), + "%" => (fn($x, $y) => $x % $y), + "+" => (fn($x, $y) => $x + $y), + "-" => (fn($x, $y) => $x - $y) + ]; + foreach ($operators_in_pemdas_order as $op=>$func) { + while (in_array(["o", $op], $tokens)) { + for ($i = 0; $i < count($tokens); $i++) { + if ($tokens[$i] == ["o", $op]) { + array_splice( + $tokens, + $i-1, + 3, + [["n", (string)($func((float)$tokens[$i-1][1], (float)$tokens[$i+1][1]))]] + ); + } + } + } + } + return $tokens; + } +} +?>
\ No newline at end of file diff --git a/oracles/encoder.php b/oracles/encoder.php new file mode 100644 index 0000000..00b5ad0 --- /dev/null +++ b/oracles/encoder.php @@ -0,0 +1,40 @@ +<?php +include_once("oracles/base.php"); +class encoder extends oracle { + public $info = [ + "name" => "text encoder/hasher" + ]; + private $special_types = [ + "rot13", + "base64" + ]; + public function check_query($q) { + $types = array_merge($this->special_types, hash_algos()); + foreach ($types as $type) { + $type .= " "; + if (str_starts_with($q, $type)) { + return true; + } + } + return false; + } + public function generate_response($q) + { + $type = explode(" ", $q)[0]; + $victim = substr($q, strlen($type)+1); + if (in_array($type, hash_algos())) { + return [$type." hash" => hash($type, $victim)]; + } + switch ($type) { + case "rot13": + return ["rot13 encoded" => str_rot13($victim)]; + case "base64": + return [ + "base64 encoded" => base64_encode($victim), + "base64 decoded" => base64_decode($victim) + ]; + } + return ""; + } +} +?>
\ No newline at end of file diff --git a/oracles/numerics.php b/oracles/numerics.php new file mode 100644 index 0000000..3d428e3 --- /dev/null +++ b/oracles/numerics.php @@ -0,0 +1,54 @@ +<?php +include_once("oracles/base.php"); +class numerics extends oracle { + public $info = [ + "name" => "numeric base conversion" + ]; + public function check_query($q) { + if (str_contains($q, " ")) { + return false; + } + + $q = strtolower($q); + + $profiles = [ + ["0x", str_split("0123456789abcdef")], + ["", str_split("1234567890")], + ["b", str_split("10")] + ]; + + foreach ($profiles as $profile) { + $good = true; + $good &= str_starts_with($q, $profile[0]); + $nq = substr($q, strlen($profile[0])); + foreach (str_split($nq) as $c) { + $good &= in_array($c, $profile[1]); + } + if ($good) { + return true; + } + } + return false; + } + public function generate_response($q) { + $n = 0; + if (str_starts_with($q, "0x")) { + $nq = substr($q, strlen("0x")); + $n = hexdec($nq); + } + elseif (str_starts_with($q, "b")) { + $nq = substr($q, strlen("b")); + $n = bindec($nq); + } + else { + $n = (int)$q; + } + return [ + "decimal (base 10)" => (string)$n, + "hexadecimal (base 16)" => "0x".(string)dechex($n), + "binary (base 2)" => "b".(string)decbin($n), + "" => "binary inputs should be prefixed with 'b', hex with '0x'." + ]; + } +} +?>
\ No newline at end of file diff --git a/oracles/time.php b/oracles/time.php new file mode 100644 index 0000000..954bc60 --- /dev/null +++ b/oracles/time.php @@ -0,0 +1,45 @@ +<?php +include_once("oracles/base.php"); +class time extends oracle { + public $info = [ + "name" => "what time is it?" + ]; + public function check_query($q) { + $prompts = [ + "what", "time", "is", "it", + "right", "now", "the", "current", + "get", "date" + ]; + $q = str_replace(",", "", $q); + $q = str_replace("?", "", $q); + $q = str_replace("what's", "what is", $q); + $oq = $q; + $q = explode(" ", $q); + $count = 0; + foreach ($q as $word) { + if (in_array($word, $prompts)) { + $count++; + } + } + // remove one from total count if a timezone is specified + return ($count/(count($q) + (str_contains($oq, "tz:") ? -1 : 0))) > 3/4; + } + public function generate_response($q) { + $timezone = timezone_name_from_abbr("UTC"); + foreach (explode(" ", $q) as $word) { + if (str_starts_with($word, "tz:")) { + $decltz = timezone_name_from_abbr(substr($word, 3, 3)); + if ($decltz) { + $timezone = $decltz; + } + } + } + date_default_timezone_set($timezone); + return [ + "The time in ".$timezone => date("H:i:s"), + " " => date("l, F jS"), + "" => "include the string \"tz:XXX\" to use timezone XXX" + ]; + } +} +?>
\ No newline at end of file diff --git a/proxy.php b/proxy.php new file mode 100644 index 0000000..730358b --- /dev/null +++ b/proxy.php @@ -0,0 +1,180 @@ +<?php + +include "data/config.php"; +include "lib/curlproxy.php"; +$proxy = new proxy(); + +if(!isset($_GET["i"])){ + + header("X-Error: No URL(i) provided!"); + $proxy->do404(); + die(); +} + +try{ + + // original size request, stream file to browser + if( + !isset($_GET["s"]) || + $_GET["s"] == "original" + ){ + + $proxy->stream_linear_image($_GET["i"]); + die(); + } + + // bing request, ask bing to resize and stream to browser + $image = parse_url($_GET["i"]); + + if( + isset($image["host"]) && + preg_match( + '/^[A-z0-9.]*bing\.(net|com)$/i', + $image["host"] + ) + ){ + + if(!isset($image["path"])){ + + header("X-Error: Missing bing image path"); + $proxy->do404(); + die(); + } + + // + // get image ID + // formations: + // https://tse2.mm.bing.net/th/id/OIP.3yLBkUPn8EXA1wlhWP2BHwHaE3 + // https://tse2.mm.bing.net/th?id=OIP.3yLBkUPn8EXA1wlhWP2BHwHaE3 + // + $id = null; + if(isset($image["query"])){ + + parse_str($image["query"], $str); + + if(isset($str["id"])){ + + $id = $str["id"]; + } + } + + if($id === null){ + + $id = explode("/th/id/", $image["path"], 2); + + if(count($id) !== 2){ + + // malformed + return $url; + } + + $id = $id[1]; + } + + if(is_array($id)){ + + header("X-Error: Missing bing id parameter"); + $proxy->do404(); + die(); + } + + switch($_GET["s"]){ + + case "portrait": $req = "&w=50&h=90&p=0&qlt=90"; break; + case "landscape": $req = "&w=160&h=90&p=0&qlt=90"; break; + case "square": $req = "&w=90&h=90&p=0&qlt=90"; break; + case "thumb": $req = "&w=236&h=180&p=0&qlt=90"; break; + case "cover": $req = "&w=207&h=270&p=0&qlt=90"; break; + } + + $proxy->stream_linear_image("https://" . $image["host"] . "/th?id=" . rawurlencode($id) . $req, "https://www.bing.com"); + die(); + } + + // resize image ourselves + $payload = $proxy->get($_GET["i"], $proxy::req_image, true); + + // get image format & set imagick + $image = null; + $format = $proxy->getimageformat($payload, $image); + + try{ + + if($format !== false){ + $image->setFormat($format); + } + + $image->readImageBlob($payload["body"]); + + $image_width = $image->getImageWidth(); + $image_height = $image->getImageHeight(); + + switch($_GET["s"]){ + + case "portrait": + $width = 50; + $height = 90; + break; + + case "landscape": + $width = 160; + $height = 90; + break; + + case "square": + $width = 90; + $height = 90; + break; + + case "thumb": + $width = 236; + $height = 180; + break; + + case "cover": + $width = 207; + $height = 270; + break; + } + + $ratio = $image_width / $image_height; + + if($image_width > $width){ + + $image_width = $width; + $image_height = round($image_width / $ratio); + } + if($image_height > $height){ + + $ratio = $image_width / $image_height; + $image_height = $height; + $image_width = $image_height * $ratio; + } + + $image->setImageBackgroundColor("#504945"); + $image->setImageAlphaChannel(Imagick::ALPHACHANNEL_REMOVE); + + $image->stripImage(); + $image->setFormat("jpeg"); + $image->setImageCompressionQuality(90); + $image->setImageCompression(Imagick::COMPRESSION_JPEG2000); + + $image->resizeImage($image_width, $image_height, Imagick::FILTER_LANCZOS, 1); + + $proxy->getfilenameheader($payload["headers"], $_GET["i"]); + + header("Content-Type: image/jpeg"); + echo $image->getImageBlob(); + + }catch(ImagickException $error){ + + header("X-Error: Could not convert the image: (" . $error->getMessage() . ")"); + $proxy->do404(); + } + +}catch(Exception $error){ + + header("X-Error: " . $error->getMessage()); + $proxy->do404(); + die(); +} diff --git a/robots.txt b/robots.txt new file mode 100644 index 0000000..6c10c2a --- /dev/null +++ b/robots.txt @@ -0,0 +1,28 @@ +# When the robots.txt is sus + +# ⠀⠀⠀⡯⡯⡾⠝⠘⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢊⠘⡮⣣⠪⠢⡑⡌ +# ⠀⠀⠀⠟⠝⠈⠀⠀⠀⠡⠀⠠⢈⠠⢐⢠⢂⢔⣐⢄⡂⢔⠀⡁⢉⠸⢨⢑⠕⡌ +# ⠀⠀⡀⠁⠀⠀⠀⡀⢂⠡⠈⡔⣕⢮⣳⢯⣿⣻⣟⣯⣯⢷⣫⣆⡂⠀⠀⢐⠑⡌ +# ⢀⠠⠐⠈⠀⢀⢂⠢⡂⠕⡁⣝⢮⣳⢽⡽⣾⣻⣿⣯⡯⣟⣞⢾⢜⢆⠀⡀⠀⠪ +# ⣬⠂⠀⠀⢀⢂⢪⠨⢂⠥⣺⡪⣗⢗⣽⢽⡯⣿⣽⣷⢿⡽⡾⡽⣝⢎⠀⠀⠀⢡ +# ⣿⠀⠀⠀⢂⠢⢂⢥⢱⡹⣪⢞⡵⣻⡪⡯⡯⣟⡾⣿⣻⡽⣯⡻⣪⠧⠑⠀⠁⢐ +# ⣿⠀⠀⠀⠢⢑⠠⠑⠕⡝⡎⡗⡝⡎⣞⢽⡹⣕⢯⢻⠹⡹⢚⠝⡷⡽⡨⠀⠀⢔ +# ⣿⡯⠀⢈⠈⢄⠂⠂⠐⠀⠌⠠⢑⠱⡱⡱⡑⢔⠁⠀⡀⠐⠐⠐⡡⡹⣪⠀⠀⢘ +# ⣿⣽⠀⡀⡊⠀⠐⠨⠈⡁⠂⢈⠠⡱⡽⣷⡑⠁⠠⠑⠀⢉⢇⣤⢘⣪⢽⠀⢌⢎ +# ⣿⢾⠀⢌⠌⠀⡁⠢⠂⠐⡀⠀⢀⢳⢽⣽⡺⣨⢄⣑⢉⢃⢭⡲⣕⡭⣹⠠⢐⢗ +# ⣿⡗⠀⠢⠡⡱⡸⣔⢵⢱⢸⠈⠀⡪⣳⣳⢹⢜⡵⣱⢱⡱⣳⡹⣵⣻⢔⢅⢬⡷ +# ⣷⡇⡂⠡⡑⢕⢕⠕⡑⠡⢂⢊⢐⢕⡝⡮⡧⡳⣝⢴⡐⣁⠃⡫⡒⣕⢏⡮⣷⡟ +# ⣷⣻⣅⠑⢌⠢⠁⢐⠠⠑⡐⠐⠌⡪⠮⡫⠪⡪⡪⣺⢸⠰⠡⠠⠐⢱⠨⡪⡪⡰ +# ⣯⢷⣟⣇⡂⡂⡌⡀⠀⠁⡂⠅⠂⠀⡑⡄⢇⠇⢝⡨⡠⡁⢐⠠⢀⢪⡐⡜⡪⡊ +# ⣿⢽⡾⢹⡄⠕⡅⢇⠂⠑⣴⡬⣬⣬⣆⢮⣦⣷⣵⣷⡗⢃⢮⠱⡸⢰⢱⢸⢨⢌ +# ⣯⢯⣟⠸⣳⡅⠜⠔⡌⡐⠈⠻⠟⣿⢿⣿⣿⠿⡻⣃⠢⣱⡳⡱⡩⢢⠣⡃⠢⠁ +# ⡯⣟⣞⡇⡿⣽⡪⡘⡰⠨⢐⢀⠢⢢⢄⢤⣰⠼⡾⢕⢕⡵⣝⠎⢌⢪⠪⡘⡌⠀ +# ⡯⣳⠯⠚⢊⠡⡂⢂⠨⠊⠔⡑⠬⡸⣘⢬⢪⣪⡺⡼⣕⢯⢞⢕⢝⠎⢻⢼⣀⠀ +# ⠁⡂⠔⡁⡢⠣⢀⠢⠀⠅⠱⡐⡱⡘⡔⡕⡕⣲⡹⣎⡮⡏⡑⢜⢼⡱⢩⣗⣯⣟ +# ⢀⢂⢑⠀⡂⡃⠅⠊⢄⢑⠠⠑⢕⢕⢝⢮⢺⢕⢟⢮⢊⢢⢱⢄⠃⣇⣞⢞⣞⢾ +# ⢀⠢⡑⡀⢂⢊⠠⠁⡂⡐⠀⠅⡈⠪⠪⠪⠣⠫⠑⡁⢔⠕⣜⣜⢦⡰⡎⡯⡾⡽ + +User-agent: * +Disallow: +Host: 4get.ca +Sitemap: https://4get.ca/sitemap diff --git a/scraper/baidu.php b/scraper/baidu.php new file mode 100644 index 0000000..efb14ca --- /dev/null +++ b/scraper/baidu.php @@ -0,0 +1,2229 @@ +<?php + +class baidu{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("baidu"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + + $this->handles = []; + $this->proc = null; + $this->handle_category = null; + $this->handle_increment = 0; + $this->sublink_increment = 0; + + $this->cookie = null; + } + + public function getfilters($page){ + + switch($page){ + + case "web": + return + [ + "newer" => [ + "display" => "Newer than", + "option" => "_DATE" + ], + "older" => [ + "display" => "Older than", + "option" => "_DATE" + ] + ]; + break; + + case "images": + return + [ + "sort" => [ + "display" => "Sort", + "option" => [ + "relevance" => "Relevance", // no param + "latest" => "Latest", // &latest=1 + "hot" => "Hot" // &hot=1 + ] + ], + "size" => [ + "display" => "Size", + "option" => [ + "any" => "Any size", + "7" => "Extra large (1080px+)", // &z=7 + "6" => "Large (600px~1080px)", // &z=6 + "5" => "Medium (300px~600px)", // &z=5 + "4" => "Small (1px~300px)" // &z=4 + ] + ], + "ratio" => [ + "display" => "Ratio", + "option" => [ + "any" => "Any ratio", + "1" => "Tall vertical", // &imgratio=1 + "2" => "Vertical", // &imgratio=2 + "3" => "Square", // &imgratio=3 + "4" => "Horizontal", // &imgratio=4 + "5" => "Wide horizontal" // &imgratio=5 + ] + ], + "format" => [ + "display" => "Format", + "option" => [ + "any" => "Any format", + "3" => "JPG", // &imgformat=3 + "5" => "JPEG", // &imgformat=5 + "4" => "PNG", // &imgformat=4 + "2" => "BMP", // &imgformat=2 + "6" => "GIF (Animated)" // &imgformat=6 + ] + ], + "color" => [ + "display" => "Color", + "option" => [ + "any" => "Any color", + "1024" => "White", // &ic=1024 + "2048" => "Black & White", + "512" => "Black", + "64" => "Magenta", + "16" => "Blue", + "1" => "Red", + "2" => "Yellow", + "32" => "Purple", + "4" => "Green", + "8" => "Teal", + "256" => "Orange", + "128" => "Brown" + ] + ], + "type" => [ + "display" => "Type", + "option" => [ + "any" => "Any type", + "hd" => "HD", // &hd=1 + "isImgSet" => "Photo album", // &isImgSet=1 + "copyright" => "Copyright" // ©right=1 + ] + ] + ]; + break; + + case "videos": + return []; + break; + + case "news": + return [ + "category" => [ + "display" => "Category", + "option" => [ + "any" => "All news", + "media" => "Media websites", // &medium=1 + "baijiahao" => "Baidu Baijiahao" // &medium=2 + ] + ] + ]; + break; + } + } + + private function get($proxy, $url, $get = [], $referer = false){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + $cookies_tmp = []; + curl_setopt($curlproc, CURLOPT_HEADERFUNCTION, function($curlproc, $header) use (&$cookies_tmp){ + + $length = strlen($header); + + $header = explode(":", $header, 2); + + if(trim(strtolower($header[0])) == "set-cookie"){ + + $cookie_tmp = explode("=", trim($header[1]), 2); + + $cookies_tmp[trim($cookie_tmp[0])] = + explode(";", $cookie_tmp[1], 2)[0]; + } + + return $length; + }); + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + if($referer === false){ + if($this->cookie === null){ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: cross-site", + "Priority: u=0, i"] + ); + }else{ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Cookie: {$this->cookie}", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: cross-site", + "Priority: u=0, i"] + ); + } + }else{ + + if($this->cookie === null){ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: application/json, text/plain, */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + "Referer: {$referer}", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-origin"] + ); + }else{ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: application/json, text/plain, */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + "Referer: {$referer}", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Cookie: {$this->cookie}", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-origin"] + ); + } + } + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + // store cookie + if(strlen($this->cookie) !== 0){ + + $this->cookie .= "; "; + } + + foreach($cookies_tmp as $cookie_name => $cookie_value){ + + $this->cookie .= $cookie_name . "=" . $cookie_value . "; "; + } + + $this->cookie = rtrim($this->cookie, " ;"); + + curl_close($curlproc); + return $data; + } + + private function redirect_add_url($proxy, $url){ + + if( + preg_match( + '/^https?:\/\/(?:www\.)?baidu\.com\/link\?/', + $url + ) === 0 + ){ + + // not a baidu redirect + return; + } + + $curlproc = curl_init(); + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1", + "Priority: u=0, i"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + curl_setopt($curlproc, CURLOPT_HEADER, true); + curl_setopt($curlproc, CURLOPT_NOBODY, true); + + $this->backend->assign_proxy($curlproc, $proxy); + + curl_multi_add_handle($this->proc, $curlproc); + $this->handles[$this->handle_category][$this->handle_increment][$this->sublink_increment] = $curlproc; + } + + private function resolve_urls($proxy, &$collection, $categories){ + + $this->proc = curl_multi_init(); + curl_multi_select($this->proc); + + foreach($categories as $category){ + + $this->sublink_increment = 0; + $this->handle_increment = 0; + $this->handle_category = $category; + + foreach($collection[$category] as $item){ + + $this->sublink_increment = 0; + $this->redirect_add_url($proxy, $item["url"]); + + if(isset($item["sublink"])){ + + foreach($item["sublink"] as $sublink){ + + $this->sublink_increment++; + $this->redirect_add_url($proxy, $sublink["url"]); + } + } + + $this->handle_increment++; + } + } + + do{ + $status = curl_multi_exec($this->proc, $active); + + }while($active && $status == CURLM_OK); + + // + // if we reach this, we're done downloading garbage + // + + foreach($this->handles as $category => $v){ + + foreach($v as $index => $data){ + + foreach($this->handles[$category][$index] as $sublinkindex => $handle){ + + preg_match( + '/location: ?(.*)$/im', + curl_multi_getcontent($handle), + $location + ); + + if(isset($location[1])){ + + if($sublinkindex === 0){ + + $collection[$category][$index]["url"] = trim($location[1]); + }else{ + + $collection[$category][$index]["sublink"][$sublinkindex - 1]["url"] = trim($location[1]); + } + } + + curl_multi_remove_handle($this->proc, $handle); + curl_close($handle); + } + } + } + + curl_multi_close($this->proc); + } + + private function resolve_images($proxy, &$data){ + + // get the image viewer that contains all of the images direct URLs + // for some reason, getting the second image's url in the set + // doesnt trigger the captcha + + if( + !isset($data["image"][1]["url"]) || + preg_match( + '/^https:\/\/image\.baidu\.com\/search\/detail/', + $data["image"][1]["url"] + ) === 0 + ){ + + // we have an already resolved image link, do nothing + return; + } + + try{ + + $html = + $this->get( + $proxy, + $data["image"][1]["url"], + [] + ); + }catch(Exception $error){ + + // fallback to the limited dataset we have + return; + } + + $this->fuckhtml->load($html); + + $script = + $this->fuckhtml + ->getElementById( + "image-detail-data", + "script" + ); + + if($script){ + + $json = + json_decode( + $script["innerHTML"], + true + ); + + if( + !isset($json["data"]["images"]) || + count($json["data"]["images"]) === 0 + ){ + + // do nothing + return; + } + + // + // Discard all previously scraped images and use data + // from the newly downloaded image carousel + // the imageset !!should!! be the same + // + $data["image"] = []; + + foreach($json["data"]["images"] as $image){ + + parse_str(parse_url($image["thumburl"], PHP_URL_QUERY), $thumb_size); + + $data["image"][] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $image["titleShow"] + ), + "source" => [ + [ + "url" => $image["objurl"], + "width" => (int)$image["width"], + "height" => (int)$image["height"] + ], + [ // thumbnail + "url" => $image["thumburl"], + "width" => (int)$thumb_size["w"], + "height" => (int)$thumb_size["h"] + ] + ], + "url" => $image["fromUrl"] + ]; + } + } + } + + public function web($get){ + + if($get["npt"]){ + + [$json, $proxy] = $this->backend->get($get["npt"], "web"); + + $json = json_decode($json, true); + $this->cookie = $json["cookie"]; + $npt_data = $json["req"]; + + $npt_data["pn"] = $npt_data["pn"] + 20; + + try{ + + $html = $this->get( + $proxy, + "https://www.baidu.com/s", + $npt_data + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + }else{ + + // + // Get authentication token + // + $proxy = $this->backend->get_ip(); + + // running this will give us shit in $this->cookie + // @TODO probably not needed? I get blocked anyways ffs + //$this->get($proxy, "https://www.baidu.com", []); + + $npt_data = [ + "wd" => $get["s"], + "rn" => 20 + ]; + + // &gpc=stf%3D0%2C1752638400|stftype%3D2 + if( + $get["older"] !== false || + $get["newer"] !== false + ){ + + if($get["older"] === false){ + + $get["older"] = 0; + } + + $npt_data["gpc"] = "stf={$get["older"]},{$get["newer"]}|stftype=2"; + } + + try{ + + $html = $this->get( + $proxy, + "https://www.baidu.com/s", + $npt_data + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + $npt_data["pn"] = 0; + } + + return $this->parse_search($proxy, "web", $npt_data, $html); + } + + private function parse_search($proxy, $pagetype, $npt_data, $html){ + + // @HACK + // remove newlines from the html, cause it fucks with fuckhtml + $html = str_replace(["\n", "\r"], "", $html); + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + $this->fuckhtml->load($html); + + $this->detect_ass(); + + $datafields = + $this->fuckhtml + ->getElementsByAttributeName( + "id", + "div" + ); + + // + // Get next page + // + $npt = + $this->fuckhtml + ->getElementsByClassName( + "n", + "a" + ); + + if(count($npt) !== 0){ + + $out["npt"] = + $this->backend->store( + json_encode([ + "req" => $npt_data, + "cookie" => $this->cookie + ]), + $pagetype, + $proxy + ); + } + + // + // Get related searches + // + $related_container = + $this->fuckhtml + ->getElementById( + "rs_new", + $datafields + ); + + if($related_container){ + + $this->fuckhtml->load($related_container); + + $as = + $this->fuckhtml + ->getElementsByClassName( + "c-color-link", + "a" + ); + + foreach($as as $a){ + + $text = + explode( + ">", + $this->fuckhtml + ->getTextContent( + $a + ), + 2 + ); + + $out["related"][] = $text[count($text) - 1]; + } + } + + foreach($datafields as $datafield){ + + if( + !isset($datafield["attributes"]["id"]) || + preg_match( + '/^[0-9]+$/', + $datafield["attributes"]["id"] + ) === 0 + ){ + + // not a search result + continue; + } + + $this->fuckhtml->load($datafield); + $div = + $this->fuckhtml + ->getElementsByTagName( + "div" + ); + + // + // Don't parse as a search result if it's a card + // + $card = + $this->fuckhtml + ->getElementsByClassName( + "cosc-card", + $div + ); + + if(count($card) !== 0){ + + // + // Parse chinese youtube shorts + // + $ytshorts_probe = + $this->fuckhtml + ->getElementsByClassName( + "tts-b-item", + $div + ); + + if(count($ytshorts_probe) !== 0){ + + $videos = + $this->fuckhtml + ->getElementsByAttributeValue( + "data-show", + "list", + $div + ); + + foreach($videos as $video){ + + $this->fuckhtml->load($video); + + $title = + $this->fuckhtml + ->getElementsByClassName( + "cosc-title-slot", + "span" + ); + + if(count($title) === 0){ + + continue; + } + + $url = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + if(count($url) === 0){ + + continue; + } + + $image = + $this->fuckhtml + ->getElementsByClassName( + "cos-image-body", + "img" + ); + + if(count($image) === 0){ + + $image = [ + "ratio" => null, + "url" => null + ]; + }else{ + + $image = [ + "ratio" => "1:1", + "url" => + $this->fuckhtml + ->getTextContent( + $image[0]["attributes"]["src"] + ) + ]; + } + + // get duration + $divs = + $this->fuckhtml + ->getElementsByAttributeName( + "class", + "div" + ); + + $duration = null; + foreach($divs as $probe){ + + if(strpos($probe["attributes"]["class"], "tag-bottom-right") !== false){ + + $duration = + $this->hms2int( + $this->fuckhtml + ->getTextContent( + $probe + ) + ); + break; + } + } + + $out["video"][] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $title[0] + ), + "description" => null, + "date" => null, + "duration" => $duration, + "views" => null, + "thumb" => $image, + "url" => + $this->fuckhtml + ->getTextContent( + $url[0]["attributes"]["href"] + ) + ]; + } + } + + // + // Parse image carousel + // + $is_image_carousel = false; + foreach($div as $d){ + + if( + isset($d["attributes"]["class"]) && + strpos($d["attributes"]["class"], "image-container") !== false + ){ + + $is_image_carousel = true; + break; + } + } + + if($is_image_carousel){ + + preg_match( + '/<!--s-data:([\S\s]*)-->/U', + $datafield["innerHTML"], + $matches + ); + + if(isset($matches[1])){ + + // weird behavior with the smaller image carousel where --cos* CSS variables are escaped wrong + $json = + $this->fuckhtml + ->parseJsObject( + str_replace( + "-\-", + "--", + $matches[1] + ) + ); + + if( + $json !== null && + isset($json["imageList"][0]["images"]) + ){ + + // parse image carousel + foreach($json["imageList"][0]["images"] as $image){ + + parse_str(parse_url($image["thumburl"], PHP_URL_QUERY), $thumb_size); + + $out["image"][] = [ + "title" => "image", + "source" => [ + [ + "url" => $image["objurl"], + "width" => (int)$image["width"], + "height" => (int)$image["height"] + ], + [ // thumbnail + "url" => $image["thumburl"], + "width" => (int)$thumb_size["w"], + "height" => (int)$thumb_size["h"] + ] + ], + "url" => $image["jumpUrl"] + ]; + } + } + } + } + continue; + } + + if(!isset($datafield["attributes"]["mu"])){ + + // dont scrape if we dont have the direct link + continue; + } + + // class:FYB_RD -> News garbage, IGNORE + + $result = + $this->fuckhtml + ->getElementsByClassName( + "result", + [$datafield] + ); + + if(count($result) !== 0){ + + // + // Parse normal search result + // + + $title = + $this->fuckhtml + ->getElementsByClassName( + "sc-link", + "a" + ); + + if(count($title) === 0){ + + // should not happen + continue; + } + + $title = + $this->titledots( + $this->fuckhtml + ->getTextContent( + $title[0] + ) + ); + + $description = + $this->fuckhtml + ->getElementsByClassName( + "c-color", + $div + ); + + if(count($description) !== 0){ + + $this->fuckhtml->load($description[0]); + + $description = + $this->fuckhtml + ->getElementsByAttributeName( + "class", + "span" + ); + + $found_desc = false; + foreach($description as $desc){ + + if(stripos($desc["attributes"]["class"], "summary-text") !== false){ + + $found_desc = true; + $description = + $this->titledots( + $this->fuckhtml + ->getTextContent( + $desc + ) + ); + break; + } + } + + if($found_desc === false){ + + $description = null; + } + + $this->fuckhtml->load($datafield); + }else{ + + $description = null; + } + + // parse date + $date_probe = + $this->fuckhtml + ->getElementsByClassName( + "cos-color-text-minor", + "span" + ); + + if(count($date_probe) !== 0){ + + $date = + $this->parse_time( + $this->fuckhtml + ->getTextContent( + $date_probe[0] + ) + ); + }else{ + + $date = null; + } + + // parse image + $img = + $this->fuckhtml + ->getElementsByTagName( + "img" + ); + + if(count($img) !== 0){ + + $image = [ + "ratio" => "16:9", + "url" => + $this->unfuckthumb( + $this->fuckhtml + ->getTextContent( + $img[0]["attributes"]["src"] + ) + ) + ]; + }else{ + + $image = [ + "ratio" => null, + "url" => null + ]; + } + + // get page type + $pagetype_probe = + $this->fuckhtml + ->getElementsByTagName( + "b" + ); + + $pagetype = "web"; + foreach($pagetype_probe as $probe){ + + $pagetype = + strtolower( + trim( + $this->fuckhtml + ->getTextContent( + $probe + ), + " 【】" + ) + ); + } + + // get extra links + $sublinks = []; + + foreach($div as $d){ + + if( + isset($d["attributes"]["class"]) && + strpos($d["attributes"]["class"], "exta-link") !== false + ){ + + $this->fuckhtml->load($d); + + $links = + $this->fuckhtml + ->getElementsByClassName( + "cos-space-mt-xs", + "div" + ); + + foreach($links as $link){ + + $this->fuckhtml->load($link); + $s_title = + $this->fuckhtml + ->getElementsByTagName( + "h3" + ); + + if(count($s_title) === 0){ + + // should not happen + continue; + } + + $data2 = + json_decode( + $this->fuckhtml + ->getTextContent( + $s_title[0]["attributes"]["data-click"] + ), + true + ); + + if(!isset($data2["clk_info"])){ + + // wtf + continue; + } + + $data2 = + json_decode( + $data2["clk_info"], + true + ); + + if(!isset($data2["url"])){ + + // no link, fuck off + continue; + } + + $url = + rawurldecode( + $data2["url"] + ); + + $data = + $this->fuckhtml + ->getElementsByTagName( + "p" + ); + + $s_description = null; + + if(count($data) !== 0){ + + $data = + json_decode( + $this->fuckhtml + ->getTextContent( + $data[0]["attributes"]["sub-show-log"] + ), + true + ); + + if(isset($data["ext"]["content"])){ + + $s_description = $data["ext"]["content"]; + } + } + + $sublinks[] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $s_title[0] + ), + "description" => $s_description, + "url" => $url, + "date" => null + ]; + } + break; + } + } + + $out["web"][] = [ + "title" => $title, + "description" => $description, + "url" => + $this->fuckhtml + ->getTextContent( + $datafield["attributes"]["mu"] + ), + "date" => $date, + "type" => $pagetype, + "thumb" => $image, + "sublink" => $sublinks, + "table" => [] + ]; + + continue; + } + + // parse special result + $result = + $this->fuckhtml + ->getElementsByClassName( + "result-op", + [$datafield] + ); + + if(count($result) !== 0){ + + // + // Parse video carousel + // + if( + isset($datafield["attributes"]["tpl"]) && + stripos($datafield["attributes"]["tpl"], "video") !== false + ){ + + preg_match( + '/<!--s-data:([\S\s]*)-->/U', + $datafield["innerHTML"], + $matches + ); + + if(isset($matches[1])){ + + $json = + json_decode( + $matches[1], + true + ); + + if($json !== null){ + + foreach($json["videoList"] as $video){ + + $out["video"][] = [ + "title" => $video["title"], + "description" => + $this->titledots( + $video["desc"] + ), + "date" => + $this->parse_time( + $video["pubTime"] + ), + "duration" => + $this->hms2int( + $video["duration"] + ), + "views" => + $this->parse_viewcount( + $video["playCount"] + ), + "thumb" => [ + "ratio" => "16:9", + "url" => $video["poster"] + ], + "url" => $video["bindProps"]["link"] + ]; + } + } + } + continue; + } + + // + // Special result div (wiki entries, rich divs) + // + $title = + $this->fuckhtml + ->getElementsByTagName( + "h3" + ); + + if(count($title) === 0){ + + // should have a title somewhere + continue; + } + + $title = + explode( + ">", + $this->fuckhtml + ->getTextContent( + $title[0] + ), + 2 + ); + + if(count($title) === 2){ + + $title = $title[1]; + }else{ + + $title = $title[0]; + } + + // probe for wiki-like entry + $description = + $this->fuckhtml + ->getElementsByClassName( + "sc-paragraph", + "p" + ); + + if(count($description) === 0){ + + // try and get grey description + $description = + $this->fuckhtml + ->getElementsByClassName( + "c-color-gray2", + "p" + ); + + if(count($description) === 0){ + + // probe for special social media description + $description = + $this->fuckhtml + ->getElementsByClassName( + "c-color-text", + "div" + ); + + if(isset($description[0]["attributes"]["aria-label"])){ + + $description = + $this->fuckhtml + ->getTextContent( + $description[0] + ["attributes"] + ["aria-label"] + ); + }else{ + + // check for news tab description + $span = + $this->fuckhtml + ->getElementsByClassName( + "c-font-normal", + "span" + ); + + $description = null; + + foreach($span as $s){ + + if(isset($s["attributes"]["aria-label"])){ + + $description = + $this->titledots( + $this->fuckhtml + ->getTextContent( + $span[count($span) - 1] + ) + ); + + break; + } + } + } + }else{ + + $description = + $this->fuckhtml + ->getTextContent( + $description[0] + ); + } + + }else{ + + preg_match( + '/<!--s-text-->([\S\s]*)<!--\/s-text-->/U', + $description[count($description) - 1]["innerHTML"], + $matches + ); + + if(isset($matches[1])){ + + $description = + $this->titledots( + $this->fuckhtml + ->getTextContent( + $matches[1] + ) + ); + }else{ + + $description = null; + } + } + + // get thumbnail + $thumb = + $this->fuckhtml + ->getElementsByTagName( + "img" + ); + + if(count($thumb) !== 0){ + + $thumb = [ + "ratio" => "1:1", + "url" => + $this->unfuckthumb( + $this->fuckhtml + ->getTextContent( + $thumb[0]["attributes"]["src"] + ) + ) + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + // get sublinks + preg_match( + '/<!--s-data:([\S\s]*)-->/U', + $datafield["innerHTML"], + $matches + ); + + $sublinks = []; + + if(isset($matches[1])){ + + $json = + json_decode( + $matches[1], + true + ); + + if($json !== null){ + + if(isset($json["buttons"])){ + + foreach($json["buttons"] as $button){ + + $sublinks[] = [ + "title" => $button["text"], + "description" => null, + "date" => null, + "url" => $button["url"] + ]; + } + }elseif(isset($json["mthreadList"])){ + + foreach($json["mthreadList"] as $thread){ + + $sublinks[] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $thread["title"] + ), + "description" => null, + "date" => null, + "url" => $thread["ttsInfo"]["titleUrl"] + ]; + } + } + } + } + + // get URL + // handle http://fakeurl.baidu.com bullshit + $url = + $this->fuckhtml + ->getTextContent( + $datafield["attributes"]["mu"] + ); + + if( + preg_match( + '/^https?:\/\/(?:fakeurl|nourl)(?:\.ubs)?\.baidu\.com/', + $url + ) + ){ + + // we got some bullshit, get jumpUrl instead + $as = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + if(count($as) !== 0){ + + $url = + $this->fuckhtml + ->getTextContent( + $as[0]["attributes"]["href"] + ); + } + } + + // get xueshu sublinks + // get list + $xueshu_list = + $this->fuckhtml + ->getElementsByClassName( + "op-xueshu-links-d20-list", + $div + ); + + if(count($xueshu_list) !== 0){ + + $this->fuckhtml->load($xueshu_list[0]); + + $rows = + $this->fuckhtml + ->getElementsByClassName( + "c-row", + "div" + ); + + // remove "read more" bullshit + foreach($rows as $row){ + + if(strpos($row["attributes"]["class"], "op-xueshu-links-more") !== false){ + + $xueshu_list[0]["innerHTML"] = + str_replace( + $row["outerHTML"], + "", + $xueshu_list[0]["innerHTML"] + ); + } + } + + $this->fuckhtml->load($xueshu_list[0]); + + foreach($rows as $row){ + + $this->fuckhtml->load($row); + + if(strpos($row["attributes"]["class"], "op-xueshu-links-more") !== false){ + + continue; + } + + $as = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + foreach($as as $a){ + + $sublinks[] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $a + ) + ), + "description" => null, + "date" => null, + "url" => + $this->fuckhtml + ->getTextContent( + $a["attributes"]["href"] + ) + ]; + } + } + } + + $out["web"][] = [ + "title" => $title, + "description" => $description, + "url" => $url, + "date" => null, + "type" => "web", + "thumb" => $thumb, + "sublink" => $sublinks, + "table" => [] + ]; + continue; + } + } + + // + // Remove tracking URLs and fetch additonal image resources + // + $this->resolve_urls($proxy, $out, ["web", "video"]); + $this->resolve_images($proxy, $out); + + return $out; + } + + public function image($get){ + + // https://image.baidu.com/search/acjson?word=asmr&rn=60&pn=0&newReq=1 + //$json = file_get_contents("scraper/baidu_img.json"); + + if($get["npt"]){ + + [$params, $proxy] = $this->backend->get($get["npt"], "images"); + $params = json_decode($params, true); + + $params["pn"] = $params["pn"] + 60; + + }else{ + + $proxy = $this->backend->get_ip(); + $params = [ + "word" => $get["s"], + "rn" => 60, // results/page + "pn" => 0, // item increment (0 * 60) + "newReq" => 1 // otherwise json is fucked up + ]; + + switch($get["sort"]){ + + case "latest": $params["latest"] = 1; break; + case "hot": $params["hot"] = 1; break; + } + + if($get["size"] != "any"){ + + $params["z"] = $get["size"]; + } + + if($get["ratio"] != "any"){ + + $params["imgratio"] = $get["ratio"]; + } + + if($get["format"] != "any"){ + + $params["imgformat"] = $get["format"]; + } + + if($get["color"] != "any"){ + + $params["ic"] = $get["color"]; + } + + switch($get["type"]){ + + case "hd": $params["hd"] = 1; break; + case "isImgSet": $params["isImgSet"] = 1; break; + case "copyright": $params["copyright"] = 1; break; + } + } + + try{ + + $json = + $this->get( + $proxy, + "https://image.baidu.com/search/acjson", + $params, + "https://image.baidu.com/search/index?tn=baiduimage&word=" . urlencode($get["s"]) + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + $json = json_decode($json, true); + + if($json === null){ + + // detect captcha first + $this->fuckhtml->load($json); + $this->detect_ass(); + + // fallback to json decode error + throw new Exception("Failed to decode JSON"); + } + + if( + isset($json["message"]) && + $json["message"] != "success" + ){ + + throw new Exception("Baidu returned an error: {$json["message"]}"); + } + + if(!isset($json["data"]["images"])){ + + throw new Exception("Baidu did not return an image object"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + foreach($json["data"]["images"] as $image){ + + parse_str(parse_url($image["thumburl"], PHP_URL_QUERY), $thumb_size); + + $out["image"][] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $image["titleShow"] + ), + "source" => [ + [ + "url" => $image["objurl"], + "width" => (int)$image["width"], + "height" => (int)$image["height"] + ], + [ // thumbnail + "url" => $image["thumburl"], + "width" => (int)$thumb_size["w"], + "height" => (int)$thumb_size["h"] + ] + ], + "url" => $image["fromUrl"] + ]; + } + + // + // Detect if there's a next page + // + if((int)$json["data"]["totalNum"] >= $params["pn"] + 60){ + + $out["npt"] = + $this->backend->store( + json_encode($params), + "images", + $proxy + ); + } + + return $out; + } + + public function video($get){ + + // https://www.baidu.com/sf/vsearch?pd=video&tn=vsearch&wd=jak%2Band%2Bdaxter&async=1&pn=0 + // increase &pn +20 for pagination + + //$html = file_get_contents("scraper/baidu_vid.html"); + + if($get["npt"]){ + + [$params, $proxy] = $this->backend->get($get["npt"], "videos"); + $params = json_decode($params, true); + + $params["pn"] = $params["pn"] + 10; + }else{ + + $proxy = $this->backend->get_ip(); + $params = [ + "pd" => "video", + "tn" => "vsearch", + "wd" => $get["s"], + "async" => 1, + "pn" => 0 + ]; + } + + try{ + $html = + $this->get( + $proxy, + "https://www.baidu.com/sf/vsearch", + $params + ); + }catch(Exception $error){ + + throw new Exception("Failed to get search page"); + } + + $html = + str_replace( + ["\r", "\n"], + "", + $html + ); + + $out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + $html = explode("<script>", $html); + + foreach($html as $result){ + + $result = trim($result); + + $this->fuckhtml->load($result); + + // get URL + preg_match( + '/<!-- *([^ ]*) *-->/', + $result, + $matches + ); + + if(!isset($matches[1])){ + + // no link, give up + continue; + } + + $link = $matches[1]; + + // get title + $title = + $this->fuckhtml + ->getElementsByClassName( + "video-title", + "a" + ); + + if(count($title) === 0){ + + // should not happen + continue; + } + + $title = + $this->fuckhtml + ->getTextContent( + $title[0] + ); + + // get thumbnail + $img = + $this->fuckhtml + ->getElementsByClassName( + "border-radius", + "img" + ); + + if(count($img) !== 0){ + + $thumb = [ + "url" => + $this->unfuckthumb( + $this->fuckhtml + ->getTextContent( + $img[0]["attributes"]["src"] + ) + ), + "ratio" => "16:9" + ]; + }else{ + + $thumb = [ + "url" => null, + "ratio" => null + ]; + } + + $span = + $this->fuckhtml + ->getElementsByTagName( + "span" + ); + + // get duration + $duration = + $this->fuckhtml + ->getElementsByClassName( + "video_play_timer", + $span + ); + + if(count($duration) !== 0){ + + $duration = + $this->hms2int( + $this->fuckhtml + ->getTextContent( + $duration[0] + ) + ); + }else{ + + $duration = null; + } + + // get author + // 来源:哔哩哔哩 + $author = + $this->fuckhtml + ->getElementsByClassName( + "wetSource", + $span + ); + + if(count($author) !== 0){ + + $author = + explode( + ":", + $this->fuckhtml + ->getTextContent( + $author[0] + ), + 2 + )[1]; + }else{ + + $author = null; + } + + // get date posted + //发布时间:2024-05-06 + + // AND get description + // 简介:Our first look + $infospans = + array_merge( + $this->fuckhtml + ->getElementsByClassName( + "c-font-normal", + $span + ), + $this->fuckhtml + ->getElementsByClassName( + "c-font-normal", + "div" + ) + ); + + $date = null; + $description = null; + + foreach($infospans as $infospan){ + + $infospan = + explode( + ":", + $this->fuckhtml + ->getTextContent( + $infospan + ), + 2 + ); + + if(count($infospan) !== 2){ + + // should not happen + continue; + } + + $infospan[1] = + $this->fuckhtml + ->getTextContent( + $infospan[1] + ); + + switch($infospan[0]){ + + case "发布时间": // date posted + $date = $this->parse_time($infospan[1]); + break; + + case "简介": // description + $description = $infospan[1]; + break; + } + } + + $out["video"][] = [ + "title" => $this->titledots($title), + "description" => $this->titledots($description), + "author" => [ + "name" => $author, + "url" => null, + "avatar" => null + ], + "date" => $date, + "duration" => $duration, + "views" => null, + "thumb" => $thumb, + "url" => $link + ]; + } + + if(count($out["video"]) === 10){ + + // assume there's another page after this + $out["npt"] = + $this->backend->store( + json_encode($params), + "videos", + $proxy + ); + } + + return $out; + } + + public function news($get){ + + //$proxy = $this->backend->get_ip(); + //$html = file_get_contents("scraper/baidu.html"); + //$npt_data = []; + + if($get["npt"]){ + + [$json, $proxy] = $this->backend->get($get["npt"], "news"); + + $json = json_decode($json, true); + $this->cookie = $json["cookie"]; + $npt_data = $json["req"]; + + $npt_data["pn"] = $npt_data["pn"] + 20; + + try{ + + $html = $this->get( + $proxy, + "https://www.baidu.com/s", + $npt_data + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + }else{ + + // + // Get authentication token + // + $proxy = $this->backend->get_ip(); + + $npt_data = [ + "wd" => $get["s"], + "rn" => 20, + "tn" => "news" + ]; + + // @TODO add filters + + try{ + + $html = $this->get( + $proxy, + "https://www.baidu.com/s", + $npt_data + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + $npt_data["pn"] = 0; + } + + $data = $this->parse_search($proxy, "news", $npt_data, $html); + + $out = [ + "status" => "ok", + "npt" => $data["npt"], + "news" => [] + ]; + + foreach($data["web"] as $article){ + + $out["news"][] = [ + "title" => $article["title"], + "author" => null, + "description" => $article["description"], + "date" => $article["date"], + "thumb" => [ + "url" => $article["thumb"]["url"], + "ratio" => $article["thumb"]["url"] !== null ? "16:9" : null, + ], + "url" => $article["url"] + ]; + } + + return $out; + } + + private function unfuckthumb($url){ + + // probe for proxy URL + $parsed_url = parse_url($url); + if( + preg_match( + '/^https?:\/\/gimg(?:[0-9]+)?\.baidu\.com/', + $url + ) + ){ + + $parts = explode("src=", $url); + if(count($parts) !== 2){ + + // shits fucked + return $url; + } + + return urldecode(explode("&", $parts[1])[0]); + } + + $q = explode("&", $url, 2); + + if(count($q) !== 2){ + + // shits fucked, again + return $url; + } + + // baidu devs are fucking retarded and dont follow spec: + // &fmt=auto?s=BB32F3A050471AEC72886934030090C4&sec=1753203600&t=0fb2194775d3bd3d1bb114b818479e0a + parse_str(str_replace("?", "&", $q[1]), $query); + + if(isset($query["size"])){ unset($query["size"]); } + if(isset($query["q"])){ $query["q"] = "90"; } + + $query = http_build_query($query); + + return + str_replace( + $q[1], + $query, + $url + ); + } + + private function titledots($title){ + + return trim($title, " .\t\n\r\0\x0B…"); + } + + private function hms2int($time){ + + $parts = explode(":", $time, 3); + $time = 0; + + if(count($parts) === 3){ + + // hours + $time = $time + ((int)$parts[0] * 3600); + array_shift($parts); + } + + if(count($parts) === 2){ + + // minutes + $time = $time + ((int)$parts[0] * 60); + array_shift($parts); + } + + // seconds + $time = $time + (int)$parts[0]; + + return $time; + } + + private function parse_viewcount($views){ + + if( + // 10k (wtf lol) + preg_match( + '/([0-9]+)万次/', + $views, + $matches + ) + ){ + + return (int)$matches[1] * 10000; + } + + if( + // units + preg_match( + '/([0-9]+)次/', + $views, + $matches + ) + ){ + + return (int)$matches[1]; + } + + return null; + } + + private function parse_time($time){ + + // 2023年8月7日 => yyyy/m/d + if( + preg_match( + '/([0-9]{4})年([0-9]{1,2})月([0-9]{1,2})日/', + $time, + $matches + ) + ){ + + return strtotime("{$matches[1]}/{$matches[2]}/{$matches[3]}"); + } + + // 昨天11:45 => yesterday at 11:45 + // 昨天 => yesterday + if( + preg_match( + '/昨天(.*)/', + $time, + $matches + ) + ){ + + return strtotime("Yesterday {$matches[1]}"); + } + + // 3天前 => 3 days ago + if( + preg_match( + '/([0-9]{1,4})天前/', + $time, + $matches + ) + ){ + + return strtotime("{$matches[1]} days ago"); + } + + // 1个月前 => 1 month ago + if( + preg_match( + '/([0-9]{1,4})个月前/', + $time, + $matches + ) + ){ + + return strtotime("{$matches[1]} months ago"); + } + + // attempt to parse as-is + $time = strtotime($time); + + if($time !== false){ + + return $time; + } + + return null; + } + + private function detect_ass(){ + + $as = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + if( + count($as) === 0 || + preg_match( + '/^https?:\/\/wappass\.baidu\.com\/static\/captcha/', + $this->fuckhtml + ->getTextContent( + $as[0]["attributes"]["href"] + ) + ) + ){ + + throw new Exception("Baidu returned a Captcha"); + } + } +} diff --git a/scraper/brave.php b/scraper/brave.php new file mode 100644 index 0000000..e6f5908 --- /dev/null +++ b/scraper/brave.php @@ -0,0 +1,1860 @@ +<?php + +class brave{ + + public function __construct(){ + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + + include "lib/backend.php"; + $this->backend = new backend("brave"); + } + + public function getfilters($page){ + + switch($page){ + + case "web": + return [ + "country" => [ + "display" => "Country", + "option" => [ + "all" => "All Regions", + "ar" => "Argentina", + "au" => "Australia", + "at" => "Austria", + "be" => "Belgium", + "br" => "Brazil", + "ca" => "Canada", + "cl" => "Chile", + "cn" => "China", + "dk" => "Denmark", + "fi" => "Finland", + "fr" => "France", + "de" => "Germany", + "hk" => "Hong Kong", + "in" => "India", + "id" => "Indonesia", + "it" => "Italy", + "jp" => "Japan", + "kr" => "Korea", + "my" => "Malaysia", + "mx" => "Mexico", + "nl" => "Netherlands", + "nz" => "New Zealand", + "no" => "Norway", + "pl" => "Poland", + "pt" => "Portugal", + "ph" => "Philippines", + "ru" => "Russia", + "sa" => "Saudi Arabia", + "za" => "South Africa", + "es" => "Spain", + "se" => "Sweden", + "ch" => "Switzerland", + "tw" => "Taiwan", + "tr" => "Turkey", + "gb" => "United Kingdom", + "us" => "United States" + ] + ], + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "maybe" => "Maybe", + "no" => "No" + ] + ], + "newer" => [ + "display" => "Newer than", + "option" => "_DATE" + ], + "older" => [ + "display" => "Older than", + "option" => "_DATE" + ], + "spellcheck" => [ + "display" => "Spellcheck", + "option" => [ + "yes" => "Yes", + "no" => "No" + ] + ] + ]; + break; + + case "images": + case "videos": + case "news": + return [ + "country" => [ + "display" => "Country", + "option" => [ + "all" => "All regions", + "ar" => "Argentina", + "au" => "Australia", + "at" => "Austria", + "be" => "Belgium", + "br" => "Brazil", + "ca" => "Canada", + "cl" => "Chile", + "cn" => "China", + "dk" => "Denmark", + "fi" => "Finland", + "fr" => "France", + "de" => "Germany", + "hk" => "Hong Kong", + "in" => "India", + "id" => "Indonesia", + "it" => "Italy", + "jp" => "Japan", + "kr" => "Korea", + "my" => "Malaysia", + "mx" => "Mexico", + "nl" => "Netherlands", + "nz" => "New Zealand", + "no" => "Norway", + "pl" => "Poland", + "pt" => "Portugal", + "ph" => "Philippines", + "ru" => "Russia", + "sa" => "Saudi Arabia", + "za" => "South Africa", + "es" => "Spain", + "se" => "Sweden", + "ch" => "Switzerland", + "tw" => "Taiwan", + "tr" => "Turkey", + "gb" => "United Kingdom", + "us" => "United States" + ] + ], + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "maybe" => "Maybe", + "no" => "No" + ] + ], + "spellcheck" => [ + "display" => "Spellcheck", + "option" => [ + "yes" => "Yes", + "no" => "No" + ] + ] + ]; + break; + } + } + + private function get($proxy, $url, $get = [], $nsfw, $country){ + + switch($nsfw){ + + case "yes": $nsfw = "off"; break; + case "maybe": $nsfw = "moderate"; break; + case "no": $nsfw = "strict"; break; + } + + if($country == "any"){ + + $country = "all"; + } + + $headers = [ + "User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Cookie: safesearch={$nsfw}; country={$country}; useLocation=0; summarizer=0", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1" + ]; + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + private function get_js(){ + + $script_disc = + $this->fuckhtml + ->getElementsByTagName( + "script" + ); + + $data = null; + foreach($script_disc as &$discs){ + + if( + preg_match( + '/kit\.start\(/', + $discs["innerHTML"] + ) + ){ + + $data = + explode( + "data:", + $discs["innerHTML"], + 2 + ); + + if(count($data) !== 2){ + + throw new Exception("Failed to split up data field"); + } + + $data = $data[1]; + break; + } + } + + if($data === null){ + + throw new Exception("Could not grep JavaScript object"); + } + + $data = + $this->fuckhtml + ->parseJsObject( + $this->fuckhtml + ->extract_json( + $data + ) + ); + + if($data === null){ + + throw new Exception("Failed to decode JavaScript object"); + } + + return $data; + } + + public function web($get){ + + if($get["npt"]){ + + // get next page data + [$q, $proxy] = $this->backend->get($get["npt"], "web"); + + $q = json_decode($q, true); + + $search = $q["q"]; + $q["spellcheck"] = "0"; + + $nsfw = $q["nsfw"]; + unset($q["nsfw"]); + + $country = $q["country"]; + unset($q["country"]); + + }else{ + + // get _GET data instead + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + if(strlen($search) > 2048){ + + throw new Exception("Search term is too long!"); + } + + $proxy = $this->backend->get_ip(); + $nsfw = $get["nsfw"]; + $country = $get["country"]; + $older = $get["older"]; + $newer = $get["newer"]; + $spellcheck = $get["spellcheck"]; + + $q = [ + "q" => $search + ]; + + /* + Pass older/newer filters to brave + */ + if($newer !== false){ + + $newer = date("Y-m-d", $newer); + + if($older === false){ + + $older = date("Y-m-d", time()); + } + } + + if( + is_string($older) === false && + $older !== false + ){ + + $older = date("Y-m-d", $older); + + if($newer === false){ + + $newer = "1970-01-02"; + } + } + + if($older !== false){ + + $q["tf"] = "{$newer}to{$older}"; + } + + // spellcheck + if($spellcheck == "no"){ + + $q["spellcheck"] = "0"; + } + } + /* + $handle = fopen("scraper/brave.html", "r"); + $html = fread($handle, filesize("scraper/brave.html")); + fclose($handle);*/ + + + try{ + $html = + $this->get( + $proxy, + "https://search.brave.com/search", + $q, + $nsfw, + $country + ); + + }catch(Exception $error){ + + throw new Exception("Could not fetch search page"); + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + // load html + $this->fuckhtml->load($html); + + /* + Get next page "token" + */ + $nextpage = + $this->fuckhtml + ->getElementById( + "pagination", + "div" + ); + + if($nextpage){ + + $this->fuckhtml->load($nextpage); + + $nextpage = + $this->fuckhtml + ->getElementsByClassName("button", "a"); + + if(count($nextpage) !== 0){ + + $nextpage = + $nextpage[count($nextpage) - 1]; + + if( + strtolower( + $this->fuckhtml + ->getTextContent( + $nextpage + ) + ) == "next" + ){ + + preg_match( + '/offset=([0-9]+)/', + $this->fuckhtml->getTextContent($nextpage["attributes"]["href"]), + $nextpage + ); + + $q["offset"] = (int)$nextpage[1]; + $q["nsfw"] = $nsfw; + $q["country"] = $country; + + $out["npt"] = + $this->backend->store( + json_encode($q), + "web", + $proxy + ); + } + } + } + + // do some magic + $this->fuckhtml->load($html); + $data = $this->get_js(); + + if( + isset($data[2]["data"]["title"]) && + stripos($data[2]["data"]["title"], "PoW Captcha") !== false + ){ + + throw new Exception("Brave returned a PoW captcha"); + } + + if(!isset($data[1]["data"]["body"]["response"])){ + + throw new Exception("Brave did not return a result object"); + } + + $data = $data[1]["data"]["body"]["response"]; + + /* + Get web results + */ + if(!isset($data["web"]["results"])){ + + return $out; + } + + foreach($data["web"]["results"] as $result){ + + if( + isset($result["thumbnail"]) && + is_array($result["thumbnail"]) + ){ + + $thumb = [ + "ratio" => $result["thumbnail"]["logo"] == "false" ? "16:9" : "1:1", + "url" => $result["thumbnail"]["original"] + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + // get sublinks + $sublink = []; + if( + isset($result["cluster"]) && + is_array($result["cluster"]) + ){ + + foreach($result["cluster"] as $cluster){ + + $sublink[] = [ + "title" => $this->titledots($cluster["title"]), + "description" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $cluster["description"] + ) + ), + "url" => $cluster["url"], + "date" => null + ]; + } + } + + // more sublinks + if( + isset($result["deep_results"]) && + is_array($result["deep_results"]) + ){ + + foreach($result["deep_results"]["buttons"] as $r){ + + $sublink[] = [ + "title" => $this->titledots($r["title"]), + "description" => null, + "url" => $r["url"], + "date" => null + ]; + } + } + + // parse table elements + $table = []; + + /* + [locations] => void 0 Done + [video] => void 0 Done + [movie] => void 0 Done + [faq] => void 0 + [recipe] => void 0 + [qa] => void 0 Not needed + [book] => void 0 + [rating] => void 0 + [article] => void 0 + [product] => void 0 Done + [product_cluster] => void 0 + [cluster_type] => void 0 + [cluster] => void 0 Done + [creative_work] => void 0 Done + [music_recording] => void 0 + [review] => void 0 Done + [software] => void 0 Done + [content_type] => void 0 + [descriptionLength] => 271 + */ + + // product + // creative_work + $ref = null; + + if(isset($result["product"])){ + + $ref = &$result["product"]; + }elseif(isset($result["creative_work"])){ + + $ref = &$result["creative_work"]; + } + + if($ref !== null){ + + if(isset($ref["offers"])){ + + foreach($ref["offers"] as $offer){ + + $price = null; + + if(isset($offer["price"])){ + + if((float)$offer["price"] == 0){ + + $price = "Free"; + }else{ + + $price = $offer["price"]; + } + } + + if($price !== "Free"){ + if(isset($offer["priceCurrency"])){ + + $price .= " " . $offer["priceCurrency"]; + } + } + + if($price !== null){ + + $table["Price"] = trim($price); + } + } + } + + if(isset($ref["rating"])){ + + $rating = null; + if(isset($ref["rating"]["ratingValue"])){ + + $rating = $ref["rating"]["ratingValue"]; + + if(isset($ref["rating"]["bestRating"])){ + + $rating .= "/" . $ref["rating"]["bestRating"]; + } + } + + if(isset($ref["rating"]["reviewCount"])){ + + $isnull = $rating === null ? false : true; + + if($isnull){ + + $rating .= " ("; + } + + $rating .= number_format($ref["rating"]["reviewCount"]) . " hits"; + + if($isnull){ + + $rating .= ")"; + } + } + + if($rating !== null){ + + $table["Rating"] = $rating; + } + } + } + + // review + if( + isset($result["review"]) && + is_array($result["review"]) + ){ + + if(isset($result["review"]["rating"]["ratingValue"])){ + + $table["Rating"] = + $result["review"]["rating"]["ratingValue"] . "/" . + $result["review"]["rating"]["bestRating"]; + } + } + + // software + if( + isset($result["software"]) && + is_array($result["software"]) + ){ + + if(isset($result["software"]["author"])){ + $table["Author"] = $result["software"]["author"]; + } + + if(isset($result["software"]["stars"])){ + $table["Stars"] = number_format($result["software"]["stars"]); + } + + if(isset($result["software"]["forks"])){ + $table["Forks"] = number_format($result["software"]["forks"]); + } + + if( + isset($result["software"]["programmingLanguage"]) && + $result["software"]["programmingLanguage"] != "" + ){ + $table["Programming languages"] = $result["software"]["programmingLanguage"]; + } + } + + // location + if( + isset($result["location"]) && + is_array($result["location"]) + ){ + + if(isset($result["location"]["postal_address"]["displayAddress"])){ + + $table["Address"] = $result["location"]["postal_address"]["displayAddress"]; + } + + if( + isset($result["location"]["rating"]) && + $result["location"]["rating"] != "void 0" + ){ + + $table["Rating"] = + $result["location"]["rating"]["ratingValue"] . "/" . + $result["location"]["rating"]["bestRating"] . " (" . + number_format($result["location"]["rating"]["reviewCount"]) . " votes)"; + } + + if( + isset($result["location"]["contact"]["telephone"]) && + $result["location"]["contact"]["telephone"] != "void 0" + ){ + + $table["Phone number"] = + $result["location"]["contact"]["telephone"]; + } + + if( + isset($result["location"]["price_range"]) && + $result["location"]["price_range"] != "void 0" + ){ + + $table["Price"] = + $result["location"]["price_range"]; + } + } + + // video + if( + isset($result["video"]) && + is_array($result["video"]) + ){ + + foreach($result["video"] as $key => $value){ + + if(is_string($result["video"][$key]) === false){ + + continue; + } + + $table[ucfirst($key)] = $value; + } + } + + // movie + if( + isset($result["video"]) && + is_array($result["movie"]) + ){ + + if(isset($result["movie"]["release"])){ + + $table["Release date"] = $result["movie"]["release"]; + } + + if(isset($result["movie"]["directors"])){ + + $directors = []; + + foreach($result["movie"]["directors"] as $director){ + + $directors[] = $director["name"]; + } + + if(count($directors) !== 0){ + + $table["Directors"] = implode(", ", $directors); + } + } + + if(isset($result["movie"]["actors"])){ + + $actors = []; + + foreach($result["movie"]["actors"] as $actor){ + + $actors[] = $actor["name"]; + } + + if(count($actors) !== 0){ + $table["Actors"] = implode(", ", $actors); + } + } + + if(isset($result["movie"]["rating"])){ + + $table["Rating"] = + $result["movie"]["rating"]["ratingValue"] . "/" . + $result["movie"]["rating"]["bestRating"] . " (" . + number_format($result["movie"]["rating"]["reviewCount"]) . " votes)"; + } + + if(isset($result["movie"]["duration"])){ + + $table["Duration"] = + $result["movie"]["duration"]; + } + + if(isset($result["movie"]["genre"])){ + + $genres = []; + + foreach($result["movie"]["genre"] as $genre){ + + $genres[] = $genre; + } + + if(count($genres) !== 0){ + $table["Genre"] = implode(", ", $genres); + } + } + } + + if( + isset($result["age"]) && + $result["age"] != "void 0" && + $result["age"] != "" + ){ + + $date = strtotime($result["age"]); + }else{ + + $date = null; + } + + $out["web"][] = [ + "title" => + $this->titledots( + $result["title"] + ), + "description" => + isset($result["review"]["description"]) ? + $this->limitstrlen( + strip_tags( + $result["review"]["description"] + ) + ) : + $this->titledots( + $this->fuckhtml + ->getTextContent( + $result["description"] + ) + ), + "url" => $result["url"], + "date" => $date, + "type" => "web", + "thumb" => $thumb, + "sublink" => $sublink, + "table" => $table + ]; + } + + /* + Get spelling autocorrect + */ + if( + isset($data["query"]["bo_altered_diff"][0][0]) && + $data["query"]["bo_altered_diff"][0][0] == "true" + ){ + $using = []; + + foreach($data["query"]["bo_altered_diff"] as $diff){ + + $using[] = $diff[1]; + } + + $out["spelling"] = [ + "type" => "including", + "using" => implode(" ", $using), + "correction" => $get["s"] + ]; + } + + /* + Get wikipedia heads + */ + if(isset($data["infobox"]["results"][0])){ + + foreach($data["infobox"]["results"] as $info){ + + if($info["subtype"] == "code"){ + + $description = + $this->stackoverflow_parse($info["data"]["answer"]["text"]); + + if(isset($info["data"]["answer"]["author"])){ + + $description[] = [ + "type" => "quote", + "value" => "Answer from " . $info["data"]["answer"]["author"] + ]; + } + }else{ + + $description = []; + + if( + isset($info["description"]) && + $info["description"] != "" + ){ + $description[] = [ + "type" => "quote", + "value" => $info["description"] + ]; + } + + if( + isset($info["long_desc"]) && + $info["long_desc"] != "" + ){ + $description[] = [ + "type" => "text", + "value" => $this->titledots($info["long_desc"]) + ]; + } + + // parse ratings + if( + isset($info["ratings"]) && + $info["ratings"] != "void 0" && + is_array($info["ratings"]) && + count($info["ratings"]) !== 0 + ){ + + $description[] = [ + "type" => "title", + "value" => "Ratings" + ]; + + foreach($info["ratings"] as $rating){ + + $description[] = [ + "type" => "link", + "url" => $rating["profile"]["url"], + "value" => $rating["profile"]["name"] + ]; + + $description[] = [ + "type" => "text", + "value" => ": " . $rating["ratingValue"] . "/" . $rating["bestRating"] . "\n" + ]; + } + } + } + + $table = []; + if(isset($info["attributes"])){ + + foreach($info["attributes"] as $row){ + + if( + $row[1] == "null" && + count($table) !== 0 + ){ + + break; + } + + if($row[1] == "null"){ + + continue; + } + + $table[ + $this->fuckhtml->getTextContent($row[0]) + ] = + $this->fuckhtml->getTextContent($row[1]); + } + } + + $sublink = []; + if(isset($info["profiles"])){ + + foreach($info["profiles"] as $row){ + + $name = $this->fuckhtml->getTextContent($row["name"]); + + if(strtolower($name) == "steampowered"){ + + $name = "Steam"; + } + + $sublink[ + $this->fuckhtml->getTextContent($name) + ] = + $this->fuckhtml->getTextContent($row["url"]); + } + } + + $out["answer"][] = [ + "title" => $this->fuckhtml->getTextContent($info["title"]), + "description" => $description, + "url" => $info["url"], + "thumb" => isset($info["images"][0]["original"]) ? $info["images"][0]["original"] : null, + "table" => $table, + "sublink" => $sublink + ]; + + break; // only iterate once, we get garbage most of the time + } + } + + /* + Get videos + */ + if(isset($data["videos"]["results"])){ + + foreach($data["videos"]["results"] as $video){ + + $out["video"][] = [ + "title" => $this->titledots($video["title"]), + "description" => $this->titledots($video["description"]), + "date" => isset($video["age"]) && $video["age"] != "void 0" ? strtotime($video["age"]) : null, + "duration" => isset($video["video"]["duration"]) && $video["video"]["duration"] != "void 0" ? $this->hms2int($video["video"]["duration"]) : null, + "views" => isset($video["video"]["views"]) && $video["video"]["views"] != "void 0" ? (int)$video["video"]["views"] : null, + "thumb" => + isset($video["thumbnail"]["src"]) ? + [ + "ratio" => "16:9", + "url" => $this->unshiturl($video["thumbnail"]["src"]) + ] : + [ + "ratio" => null, + "url" => null + ], + "url" => $video["url"] + ]; + } + } + + /* + Get news + */ + if(isset($data["news"]["results"])){ + + foreach($data["news"]["results"] as $news){ + + $out["news"][] = [ + "title" => $this->titledots($news["title"]), + "description" => $this->titledots($news["description"]), + "date" => isset($news["age"]) ? strtotime($news["age"]) : null, + "thumb" => + isset($video["thumbnail"]["src"]) ? + [ + "ratio" => "16:9", + "url" => $this->unshiturl($video["thumbnail"]["src"]) + ] : + [ + "ratio" => null, + "url" => null + ], + "url" => $news["url"] + ]; + } + } + + /* + Get discussions + */ + $disc_out = []; + + if(isset($data["discussions"]["results"])){ + + foreach($data["discussions"]["results"] as $disc){ + + $table = []; + + if(isset($disc["data"]["num_votes"])){ + + $table["Votes"] = number_format($disc["data"]["num_votes"]); + } + + if(isset($disc["data"]["num_answers"])){ + + $table["Comments"] = number_format($disc["data"]["num_answers"]); + } + + $disc_out[] = [ + "title" => + $this->titledots( + $disc["title"] + ), + "description" => + $this->limitstrlen( + $this->titledots( + $this->fuckhtml + ->getTextContent( + $disc["description"] + ) + ) + ), + "url" => $disc["url"], + "date" => isset($disc["age"]) ? strtotime($disc["age"]) : null, + "type" => "web", + "thumb" => [ + "ratio" => null, + "url" => null + ], + "sublink" => [], + "table" => $table + ]; + } + } + + // append discussions at position 2 + array_splice($out["web"], 1, 0, $disc_out); + + return $out; + } + + public function news($get){ + + if($get["npt"]){ + + [$req, $proxy] = $this->backend->get($get["npt"], "news"); + + $req = json_decode($req, true); + + $search = $req["q"]; + $country = $req["country"]; + $nsfw = $req["nsfw"]; + $offset = $req["offset"]; + $spellcheck = $req["spellcheck"]; + + try{ + $html = + $this->get( + $proxy, + "https://search.brave.com/news", + [ + "q" => $search, + "offset" => $offset, + "spellcheck" => $spellcheck + ], + $nsfw, + $country + ); + + }catch(Exception $error){ + + throw new Exception("Could not fetch search page"); + } + + }else{ + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + if(strlen($search) > 2048){ + + throw new Exception("Search term is too long!"); + } + + $proxy = $this->backend->get_ip(); + $nsfw = $get["nsfw"]; + $country = $get["country"]; + $spellcheck = $get["spellcheck"] == "yes" ? "1" : "0"; + + /* + $handle = fopen("scraper/brave-news.html", "r"); + $html = fread($handle, filesize("scraper/brave-news.html")); + fclose($handle);*/ + try{ + $html = + $this->get( + $proxy, + "https://search.brave.com/news", + [ + "q" => $search, + "spellcheck" => $spellcheck + ], + $nsfw, + $country + ); + + }catch(Exception $error){ + + throw new Exception("Could not fetch search page"); + } + } + + $out = [ + "status" => "ok", + "npt" => null, + "news" => [] + ]; + + // load html + $this->fuckhtml->load($html); + + // get npt + $out["npt"] = + $this->generatenextpagetoken( + $search, + $nsfw, + $country, + $spellcheck, + "news", + $proxy + ); + + $this->fuckhtml->load($html); + $json = $this->get_js(); + + foreach( + $json[1]["data"]["body"]["response"]["news"]["results"] + as $news + ){ + + if( + !isset($news["thumbnail"]["src"]) || + $news["thumbnail"]["src"] == "void 0" + ){ + + $thumb = [ + "url" => null, + "ratio" => null + ]; + }else{ + + $thumb = [ + "url" => $this->unshiturl($news["thumbnail"]["src"]), + "ratio" => "16:9" + ]; + } + + $out["news"][] = [ + "title" => $news["title"], + "author" => null, + "description" => $news["description"], + "date" => !isset($news["age"]) || $news["age"] == "void 0" || $news["age"] == "null" ? null : strtotime($news["age"]), + "thumb" => $thumb, + "url" => $news["url"] + ]; + } + + return $out; + } + + public function image($get){ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + if(strlen($search) > 2048){ + + throw new Exception("Search term is too long!"); + } + + $country = $get["country"]; + $nsfw = $get["nsfw"]; + $spellcheck = $get["spellcheck"] == "yes" ? "1" : "0"; + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + try{ + $html = + $this->get( + $this->backend->get_ip(), // no nextpage right now, pass proxy directly + "https://search.brave.com/images", + [ + "q" => $search, + "spellcheck" => $spellcheck + ], + $nsfw, + $country + ); + + }catch(Exception $error){ + + throw new Exception("Could not fetch search page"); + } + /* + $handle = fopen("scraper/brave-image.html", "r"); + $html = fread($handle, filesize("scraper/brave-image.html")); + fclose($handle);*/ + + $this->fuckhtml->load($html); + $json = $this->get_js(); + + foreach( + $json[1] + ["data"] + ["body"] + ["response"] + ["results"] + as $result + ){ + + $out["image"][] = [ + "title" => $result["title"], + "source" => [ + [ + "url" => $result["properties"]["url"], + "width" => null, + "height" => null + ], + [ + "url" => $result["thumbnail"]["src"], + "width" => null, + "height" => null + ] + ], + "url" => $result["url"] + ]; + } + + return $out; + } + + public function video($get){ + + if($get["npt"]){ + + [$npt, $proxy] = $this->backend->get($get["npt"], "videos"); + + $npt = json_decode($npt, true); + $search = $npt["q"]; + $offset = $npt["offset"]; + $spellcheck = $npt["spellcheck"]; + $country = $npt["country"]; + $nsfw = $npt["nsfw"]; + + try{ + $html = + $this->get( + $proxy, + "https://search.brave.com/videos", + [ + "q" => $search, + "offset" => $offset, + "spellcheck" => $spellcheck + ], + $nsfw, + $country + ); + + }catch(Exception $error){ + + throw new Exception("Could not fetch search page"); + } + + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + if(strlen($search) > 2048){ + + throw new Exception("Search term is too long!"); + } + + $country = $get["country"]; + $nsfw = $get["nsfw"]; + $spellcheck = $get["spellcheck"] == "yes" ? "1" : "0"; + + $proxy = $this->backend->get_ip(); + + try{ + $html = + $this->get( + $proxy, + "https://search.brave.com/videos", + [ + "q" => $search, + "spellcheck" => $spellcheck + ], + $nsfw, + $country + ); + + }catch(Exception $error){ + + throw new Exception("Could not fetch search page"); + } + } + + $this->fuckhtml->load($html); + + $out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + // get npt + $out["npt"] = + $this->generatenextpagetoken( + $search, + $nsfw, + $country, + $spellcheck, + "videos", + $proxy + ); + + /* + $handle = fopen("scraper/brave-video.html", "r"); + $html = fread($handle, filesize("scraper/brave-video.html")); + fclose($handle);*/ + + $this->fuckhtml->load($html); + $json = $this->get_js(); + + foreach( + $json + [1] + ["data"] + ["body"] + ["response"] + ["results"] + as $result + ){ + + if($result["video"]["author"] != "null"){ + + $author = [ + "name" => $result["video"]["author"]["name"] == "null" ? null : $result["video"]["author"]["name"], + "url" => $result["video"]["author"]["url"] == "null" ? null : $result["video"]["author"]["url"], + "avatar" => $result["video"]["author"]["img"] == "null" ? null : $result["video"]["author"]["img"] + ]; + }else{ + + $author = [ + "name" => null, + "url" => null, + "avatar" => null + ]; + } + + if($result["thumbnail"] != "null"){ + + $thumb = [ + "url" => $result["thumbnail"]["original"], + "ratio" => "16:9" + ]; + }else{ + + $thumb = [ + "url" => null, + "ratio" => null + ]; + } + + $out["video"][] = [ + "title" => $result["title"], + "description" => $result["description"] == "null" ? null : $this->titledots($result["description"]), + "author" => $author, + "date" => ($result["age"] == "null" || $result["age"] == "void 0") ? null : strtotime($result["age"]), + "duration" => $result["video"]["duration"] == "null" ? null : $this->hms2int($result["video"]["duration"]), + "views" => $result["video"]["views"] == "null" ? null : (int)$result["video"]["views"], + "thumb" => $thumb, + "url" => $result["url"] + ]; + } + + return $out; + } + + private function stackoverflow_parse($html){ + + $i = 0; + $answer = []; + + $this->fuckhtml->load($html); + + foreach( + $this->fuckhtml->getElementsByTagName("*") + as $snippet + ){ + + switch($snippet["tagName"]){ + + case "p": + $this->fuckhtml->load($snippet["innerHTML"]); + + $codetags = + $this->fuckhtml + ->getElementsByTagName("*"); + + $tmphtml = $snippet["innerHTML"]; + + foreach($codetags as $tag){ + + if(!isset($tag["outerHTML"])){ + + continue; + } + + $tmphtml = + explode( + $tag["outerHTML"], + $tmphtml, + 2 + ); + + $value = $this->fuckhtml->getTextContent($tmphtml[0], false, false); + $this->appendtext($value, $answer, $i); + + $type = null; + switch($tag["tagName"]){ + + case "code": $type = "inline_code"; break; + case "em": $type = "italic"; break; + case "blockquote": $type = "quote"; break; + default: $type = "text"; + } + + if($type !== null){ + $value = $this->fuckhtml->getTextContent($tag, false, true); + + if(trim($value) != ""){ + + if( + $i !== 0 && + $type == "title" + ){ + + $answer[$i - 1]["value"] = rtrim($answer[$i - 1]["value"]); + } + + $answer[] = [ + "type" => $type, + "value" => $value + ]; + $i++; + } + } + + if(count($tmphtml) === 2){ + + $tmphtml = $tmphtml[1]; + }else{ + + break; + } + } + + if(is_array($tmphtml)){ + + $tmphtml = $tmphtml[0]; + } + + if(strlen($tmphtml) !== 0){ + + $value = $this->fuckhtml->getTextContent($tmphtml, false, false); + $this->appendtext($value, $answer, $i); + } + break; + + case "img": + $answer[] = [ + "type" => "image", + "url" => + $this->fuckhtml + ->getTextContent( + $tag["attributes"]["src"] + ) + ]; + $i++; + break; + + case "pre": + + switch($answer[$i - 1]["type"]){ + + case "text": + case "italic": + $answer[$i - 1]["value"] = rtrim($answer[$i - 1]["value"]); + break; + } + + $answer[] = + [ + "type" => "code", + "value" => + rtrim( + $this->fuckhtml + ->getTextContent( + $snippet, + true, + false + ) + ) + ]; + $i++; + + break; + + case "ol": + $o = 0; + + $this->fuckhtml->load($snippet); + $li = + $this->fuckhtml + ->getElementsByTagName("li"); + + foreach($li as $elem){ + $o++; + + $this->appendtext( + $o . ". " . + $this->fuckhtml + ->getTextContent( + $elem + ), + $answer, + $i + ); + } + break; + } + } + + if( + $i !== 0 && + $answer[$i - 1]["type"] == "text" + ){ + + $answer[$i - 1]["value"] = rtrim($answer[$i - 1]["value"]); + } + + return $answer; + } + + private function hms2int($time){ + + $parts = explode(":", $time, 3); + $time = 0; + + if(count($parts) === 3){ + + // hours + $time = $time + ((int)$parts[0] * 3600); + array_shift($parts); + } + + if(count($parts) === 2){ + + // minutes + $time = $time + ((int)$parts[0] * 60); + array_shift($parts); + } + + // seconds + $time = $time + (int)$parts[0]; + + return $time; + } + + private function appendtext($payload, &$text, &$index){ + + if(trim($payload) == ""){ + + return; + } + + if( + $index !== 0 && + $text[$index - 1]["type"] == "text" + ){ + + $text[$index - 1]["value"] .= "\n\n" . preg_replace('/ $/', " ", $payload); + }else{ + + $text[] = [ + "type" => "text", + "value" => preg_replace('/ $/', " ", $payload) + ]; + $index++; + } + } + + private function tablesublink($html_collection, &$data){ + + foreach($html_collection as $html){ + + $html["innerHTML"] = preg_replace( + '/<style>[\S\s]*<\/style>/i', + "", + $html["innerHTML"] + ); + + $html = + explode( + ":", + $this->fuckhtml->getTextContent($html), + 2 + ); + + if(count($html) === 1){ + + $html = ["Rating", $html[0]]; + } + + $data["table"][trim($html[0])] = trim($html[1]); + } + } + /* + private function getimagelinkfromstyle($thumb){ + + $thumb = + $this->fuckhtml + ->getElementsByClassName( + $thumb, + "div" + ); + + if(count($thumb) === 0){ + + return [ + "url" => null, + "ratio" => null + ]; + } + + $thumb = $thumb[0]["attributes"]["style"]; + + preg_match( + '/background-image: ?url\((\'[^\']+\'|"[^"]+"|[^\)]+)\)/', + $thumb, + $thumb + ); + + $url = $this->fuckhtml->getTextContent($this->unshiturl(trim($thumb[1], '"\' '))); + + if(parse_url($url, PHP_URL_HOST) == "cdn.search.brave.com"){ + + return [ + "url" => null, + "ratio" => null + ]; + } + + return [ + "url" => $url, + "ratio" => "16:9" + ]; + }*/ + + private function limitstrlen($text){ + + return explode("\n", wordwrap($text, 300, "\n"))[0]; + } + /* + private function limitwhitespace($text){ + + return + preg_replace( + '/[\s]+/', + " ", + $text + ); + }*/ + + private function titledots($title){ + + $substr = substr($title, -3); + + if( + $substr == "..." || + $substr == "…" + ){ + + return trim(substr($title, 0, -3)); + } + + return trim($title); + } + + private function generatenextpagetoken($q, $nsfw, $country, $spellcheck, $page, $proxy){ + + $nextpage = + $this->fuckhtml + ->getElementById( + "pagination", + "div" + ); + + if($nextpage){ + + $this->fuckhtml->load($nextpage); + + $nextpage = + $this->fuckhtml + ->getElementsByClassName( + "button", + "a" + ); + + if(count($nextpage) !== 0){ + + $nextpage = + $nextpage[count($nextpage) - 1]; + + if( + strtolower( + $this->fuckhtml + ->getTextContent( + $nextpage + ) + ) == "next" + ){ + + preg_match( + '/offset=([0-9]+)/', + $this->fuckhtml->getTextContent($nextpage["attributes"]["href"]), + $nextpage + ); + + return + $this->backend->store( + json_encode( + [ + "q" => $q, + "offset" => (int)$nextpage[1], + "nsfw" => $nsfw, + "country" => $country, + "spellcheck" => $spellcheck + ] + ), + $page, + $proxy + ); + } + } + } + + return null; + } + + private function unshiturl($url){ + + // https://imgs.search.brave.com/XFnbR8Sl7ge82MBDEH7ju0UHImRovMVmQ2qnDvgNTuA/rs:fit:844:225:1/g:ce/aHR0cHM6Ly90c2U0/Lm1tLmJpbmcubmV0/L3RoP2lkPU9JUC54/UWotQXU5N2ozVndT/RDJnNG9BNVhnSGFF/SyZwaWQ9QXBp.jpeg + + $tmp = explode("aHR0", $url); + + if(count($tmp) !== 2){ + + // nothing to do + return $url; + } + + return + base64_decode( + "aHR0" . + str_replace(["/", "_"], ["", "/"], + explode( + ".", + $tmp[1] + )[0] + ) + ); + } +} diff --git a/scraper/cara.php b/scraper/cara.php new file mode 100644 index 0000000..ed3d0b5 --- /dev/null +++ b/scraper/cara.php @@ -0,0 +1,847 @@ +<?php + +class cara{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("cara"); + } + + public function getfilters($page){ + + return [ + "sort" => [ + "display" => "Sort by", + "option" => [ + "Top" => "Top", + "MostRecent" => "Most Recent" + ] + ], + "type" => [ + "display" => "Post type", + "option" => [ + "any" => "Any type", + "portfolio" => "Portfolio", // {"posts":["portfolio"]} + "timeline" => "Timeline" // {"posts":["timeline"]} + ] + ], + "fields" => [ + "display" => "Field/Medium", + "option" => [ + "any" => "Any field", + "2D" => "2D Work", + "3D" => "3D Work", + "3DPrinting" => "3D Printing", + "Acrylic" => "Acrylic", + "AlcoholMarkers" => "Alcohol Markers", + "Animation" => "Animation", + "Chalk" => "Chalk", + "Charcoal" => "Charcoal", + "Colored pencil" => "Colored pencil", + "Conte" => "Conte", + "Crayon" => "Crayon", + "Digital" => "Digital", + "Gouache" => "Gouache", + "Ink" => "Ink", + "MixedMedia" => "Mixed-Media", + "Oil" => "Oil", + "Oil-based Markers" => "Oil-based Markers", + "Other" => "Other", + "Pastels" => "Pastels", + "Photography" => "Photography", + "Sculpture" => "Sculpture", + "Sketches" => "Sketches", + "Tattoos" => "Tattoos", + "Traditional" => "Traditional", + "VFX" => "VFX", + "Watercolor" => "Watercolor" + ] + ], + "category" => [ + "display" => "Category", + "option" => [ + "any" => "Any category", + "3DScanning" => "3D Scanning", + "Abstract" => "Abstract", + "Adoptable" => "Adoptable", + "Anatomy" => "Anatomy", + "Animals" => "Animals", + "Anime" => "Anime", + "App" => "App", + "ArchitecturalConcepts" => "Architectural Concepts", + "ArchitecturalVisualization" => "Architectural Visualization", + "AugmentedReality" => "Augmented Reality", + "Automotive" => "Automotive", + "BoardGameArt" => "Board Game Art", + "BookIllustration" => "Book Illustration", + "CardGameArt" => "Card Game Art", + "CeramicsPottery" => "Ceramics/Pottery", + "CharacterAnimation" => "Character Animation", + "CharacterDesign" => "Character Design", + "CharacterModeling" => "Character Modeling", + "ChildrensArt" => "Children's Illustration", + "Collectibles" => "Collectibles", + "ColoringPage" => "Coloring Page", + "ComicArt" => "Comic Art", + "ConceptArt" => "Concept Art", + "Cosplay" => "Cosplay", + "CostumeDesign" => "Costume Design", + "CoverArt" => "Cover Art", + "Creatures" => "Creatures", + "Diorama" => "Diorama", + "EditorialIllustration" => "Editorial Illustration", + "EmbroiderySewing" => "Embroidery/Sewing", + "EnvironmentalConceptArt" => "Environmental Concept Art", + "EnvironmentalConceptDesign" => "Environmental Concept Design", + "FanArt" => "Fan Art", + "Fantasy" => "Fantasy", + "Fashion" => "Fashion", + "FashionStyling" => "Fashion Styling", + "FiberArts" => "Fiber Arts", + "Furry" => "Furry", + "GameArt" => "Game Art", + "GameplayDesign" => "Gameplay Design", + "GamesEnvironmentArt" => "Games Environment Art", + "Gem" => "Gem", + "GraphicDesign" => "Graphic Design", + "Handicraft" => "Handicraft", + "HairStyling" => "Hair Styling", + "HardSurface" => "Hard Surface", + "Horror" => "Horror", + "Illustration" => "Illustration", + "IllustrationVisualization" => "Illustration Visualization", + "IndustrialDesign" => "Industrial Design", + "Jewelry" => "Jewelry", + "KnittingCrochet" => "Knitting/Crochet", + "Landscape" => "Landscape", + "LevelDesign" => "Level Design", + "Lighting" => "Lighting", + "Makeup" => "Makeup", + "Manga" => "Manga", + "MapsCartography" => "Maps/Cartography", + "MattePainting" => "Matte Painting", + "Materials" => "Materials", + "MechanicalDesign" => "Mechanical Design", + "Medical" => "Medical", + "Mecha" => "Mecha", + "MiniatureArt" => "Miniature Art", + "MotionGraphics" => "Motion Graphics", + "FrescoMurals" => "Fresco/Murals", + "Natural" => "Natural", + "Original Character" => "Original Character", + "Overlay" => "Overlay", + "PleinAir" => "Plein Air", + "Photogrammetry" => "Photogrammetry", + "PixelArt" => "Pixel Art", + "Portraits" => "Portraits", + "Props" => "Props", + "ProductDesign" => "Product Design", + "PublicDomain" => "Public Domain or Royalty Free", + "Real-Time3DEnvironmentArt" => "Real-Time 3D Environment Art", + "Realism" => "Realism", + "ScienceFiction" => "Science Fiction", + "ScientificVisualization" => "Scientific Visualization", + "Scripts" => "Scripts", + "StillLife" => "Still Life", + "Storyboards" => "Storyboards", + "Stylized" => "Stylized", + "Surreal" => "Surreal", + "TechnicalArt" => "Technical Art", + "Textures" => "Textures", + "Tools" => "Tools", + "Toys" => "Toys", + "ToyPackaging" => "Toy Packaging", + "Tutorials" => "Tutorials", + "UIArt" => "User Interface (UI) Art", + "UrbanSketch" => "Urban Sketch", + "VFXforAnimation" => "VFX for Animation", + "VFXforFilm" => "VFX for Film", + "VFXforGames" => "VFX for Games", + "VFXforRealTime" => "VFX for Real-Time", + "VFXforTV" => "VFX for TV", + "Vehicles" => "Vehicles", + "VirtualReality" => "Virtual Reality", + "VisualDevelopment" => "Visual Development", + "VoxelArt" => "Voxel Art", + "Vtubers" => "Vtubers", + "WIP" => "WIP (Work in Progress)", + "Web" => "Web", + "Weapons" => "Weapons", + "Wildlife" => "Wildlife", + "Woodcutting" => "Woodcutting" + ] + ], + "software" => [ + "display" => "Software", + "option" => [ + "any" => "Any software", + "123D" => "123D", + "123DCatch" => "123D Catch", + "3DBee" => "3DBee", + "3DCoat" => "3DCoat", + "3DCoatPrint" => "3DCoatPrint", + "3DCoatTextura" => "3DCoatTextura", + "3DEqualizer" => "3DEqualizer", + "3DFZephyr" => "3DF Zephyr", + "3Delight" => "3Delight", + "3dpeople" => "3dpeople", + "3dsMax" => "3ds Max", + "3DSPaint" => "3DS Paint", + "ACDSeeCanvas" => "ACDSee Canvas", + "AbletonLive" => "Ableton Live", + "Acrobat" => "Acrobat", + "AdobeDraw" => "Adobe Draw", + "AdobeFlash" => "Adobe Flash", + "AdobeFresco" => "Adobe Fresco", + "AdobeSubstance3Dassets" => "Adobe Substance 3D assets", + "AdobeXD" => "Adobe XD", + "AffinityDesigner" => "Affinity Designer", + "AffinityPhoto" => "Affinity Photo", + "AfterEffects" => "After Effects", + "Akeytsu" => "Akeytsu", + "Alchemy" => "Alchemy", + "AliasDesign" => "Alias Design", + "AlightMotion" => "Alight Motion", + "Amadine" => "Amadine", + "Amberlight" => "Amberlight", + "Animate" => "Animate", + "AnimationMaster" => "Animation:Master", + "AnimeStudio" => "Anime Studio", + "Apophysis" => "Apophysis", + "ArchiCAD" => "ArchiCAD", + "Arion" => "Arion", + "ArionFX" => "ArionFX", + "Arnold" => "Arnold", + "ArtEngine" => "ArtEngine", + "ArtFlow" => "ArtFlow", + "ArtRage" => "ArtRage", + "ArtstudioPro" => "Artstudio Pro", + "Artweaver" => "Artweaver", + "Aseprite" => "Aseprite", + "Audition" => "Audition", + "AutoCAD" => "AutoCAD", + "AutodeskSketchBook" => "Autodesk SketchBook", + "AvidMediaComposer" => "Avid Media Composer", + "AzPainter" => "AzPainter", + "babylonjs" => "babylon.js", + "BalsamiqMockup" => "Balsamiq Mockup", + "Bforartists" => "Bforartists", + "BlackInk" => "Black Ink", + "BlackmagicDesignFusion" => "Blackmagic Design Fusion", + "Blender" => "Blender", + "Blender DeepPaint" => "Blender DeepPaint", + "BlenderGreasePencil" => "Blender Grease Pencil", + "Blockbench" => "Blockbench", + "BodyPaint" => "BodyPaint", + "Boxcutter" => "Boxcutter", + "BraidMaker" => "Braid Maker", + "BrickLinkStudio" => "BrickLink Studio", + "Bridge" => "Bridge", + "Brushifyio" => "Brushify.io", + "C" => "C", + "C#" => "C#", + "C++" => "C++", + "CACANi" => "CACANi", + "CLIPSTUDIOPAINT" => "CLIP STUDIO PAINT", + "CLO" => "CLO", + "CRYENGINE" => "CRYENGINE", + "Callipeg" => "Callipeg", + "Canva" => "Canva", + "CaptureOne" => "Capture One", + "CartoonAnimator" => "Cartoon Animator", + "Carveco" => "Carveco", + "Cavalry" => "Cavalry", + "Chaotica" => "Chaotica", + "CharacterAnimator" => "Character Animator", + "CharacterCreator" => "Character Creator", + "Cinema4D" => "Cinema 4D", + "ClarisseiFX" => "Clarisse iFX", + "Coiffure" => "Coiffure", + "ColorsLive" => "Colors Live", + "Combustion" => "Combustion", + "Construct2" => "Construct 2", + "Core" => "Core", + "CorelPainter" => "Corel Painter", + "CorelDRAWGraphicsSuite" => "CorelDRAW Graphics Suite", + "CoronaRenderer" => "Corona Renderer", + "ProMotionNG" => "Cosmigo Pro Motion NG", + "CrazyBump" => "CrazyBump", + "Crocotile3D" => "Crocotile 3D", + "Curvy3D" => "Curvy 3D", + "Cycles4D" => "Cycles 4D", + "Darkroom" => "Darkroom", + "DAZStudio" => "DAZ Studio", + "DDO" => "DDO", + "DECIMA" => "DECIMA", + "Darktable" => "Darktable", + "DaVinciResolve" => "DaVinci Resolve", + "Dimension" => "Dimension", + "DragonBones" => "DragonBones", + "Dragonframe" => "Dragonframe", + "Drawpile" => "Drawpile", + "Dreams" => "Dreams", + "Dreamweaver" => "Dreamweaver", + "DxOPhotoLab" => "DxO PhotoLab", + "ECycles" => "E-Cycles", + "EmberGen" => "EmberGen", + "Encore" => "Encore", + "Expresii" => "Expresii", + "FStorm" => "FStorm", + "FadeIn" => "FadeIn", + "Feather3D" => "Feather 3D", + "FiberShop" => "FiberShop", + "Figma" => "Figma", + "FilmoraWondershare" => "Filmora Wondershare", + "FilterForge" => "Filter Forge", + "FinalCutPro" => "Final Cut Pro", + "FinalDraft" => "Final Draft", + "finalRender" => "finalRender", + "FireAlpaca" => "FireAlpaca", + "Fireworks" => "Fireworks", + "FlamePainter" => "Flame Painter", + "Flash" => "Flash", + "FlipaClip" => "FlipaClip", + "FlipnoteStudio" => "Flipnote Studio", + "Fluent" => "Fluent", + "ForestPack" => "Forest Pack", + "FormZ" => "Form-Z", + "Fractorium" => "Fractorium", + "FreeCAD" => "FreeCAD", + "FreeHand" => "FreeHand", + "Forger" => "Forger", + "FrostbiteEngine" => "Frostbite Engine", + "fSpy" => "fSpy", + "FumeFX" => "FumeFX", + "Fusion360" => "Fusion 360", + "GIMP" => "GIMP", + "GSCurveTools" => "GS CurveTools", + "GSToolbox" => "GS Toolbox", + "Gaea" => "Gaea", + "GameTextures" => "Game Textures", + "GameMakerStudio" => "GameMaker: Studio", + "GarageFarmNET" => "GarageFarm.NET", + "GeoGlyph" => "GeoGlyph", + "GigapixelAl" => "Gigapixel Al", + "Glaxnimate" => "Glaxnimate", + "GnomePaint" => "Gnome Paint", + "Godot" => "Godot", + "Goxel" => "Goxel", + "Graphite" => "Graphite", + "Graswald" => "Graswald", + "GravitySketch" => "Gravity Sketch", + "GuerillaRender" => "GuerillaRender", + "HDRLightStudio" => "HDR Light Studio", + "HairStrandDesigner" => "Hair Strand Designer", + "HairTGHairFur" => "HairTG - Hair & Fur", + "HairTGSurfaceFeatherEdition" => "HairTG - Surface, Feather Edition", + "HairTGSurfaceHairEdition" => "HairTG - Surface, Hair Edition", + "Handplane" => "Handplane", + "Hansoft" => "Hansoft", + "HardOps" => "Hard Ops", + "HardMesh" => "HardMesh", + "Harmony" => "Harmony", + "HeavypaintWebbypaint" => "Heavypaint/Webbypaint", + "HelloPaint" => "HelloPaint", + "HeliconFocus" => "Helicon Focus", + "Hexels" => "Hexels", + "HiPaint" => "HiPaint", + "Houdini" => "Houdini", + "HydraRenderer" => "Hydra Renderer", + "iArtbook" => "iArtbook", + "IbisPaint" => "ibisPaint", + "Ideas" => "Ideas", + "IllustStudio" => "Illust Studio", + "Illustrator" => "Illustrator", + "IllustratorDraw" => "Illustrator Draw", + "InDesign" => "InDesign", + "Inochi2D" => "Inochi2D", + "InVision" => "InVision", + "InVisionCraft" => "InVision Craft", + "InfinitePainter" => "Infinite Painter", + "Inkscape" => "Inkscape", + "Inspirit" => "Inspirit", + "InstaLOD" => "InstaLOD", + "InstaMAT" => "InstaMAT", + "InstantLightRealtimePBR" => "Instant Light Realtime PBR", + "InstantMeshes" => "Instant Meshes", + "InstantTerra" => "Instant Terra", + "Inventor" => "Inventor", + "Iray" => "Iray", + "JWildfire" => "JWildfire", + "Java" => "Java", + "Jira" => "Jira", + "JumpPaint" => "Jump Paint by MediBang", + "JSPaint" => "JS Paint", + "Katana" => "Katana", + "Keyshot" => "Keyshot", + "KidPix" => "Kid Pix", + "KitBash3D" => "KitBash3D", + "Knald" => "Knald", + "Kodon" => "Kodon", + "KolourPaint" => "KolourPaint", + "Krakatoa" => "Krakatoa", + "KRESKA" => "KRESKA", + "Krita" => "Krita", + "LensStudio" => "Lens Studio", + "LibreSprite" => "LibreSprite", + "LightWave3D" => "LightWave 3D", + "Lightroom" => "Lightroom", + "Linearity" => "Linearity", + "LiquiGen" => "LiquiGen", + "Live2DCubism" => "Live2D Cubism", + "LookatmyHair" => "Look at my Hair", + "Lotpixel" => "Lotpixel", + "Lumion" => "Lumion", + "LuxRender" => "LuxRender", + "MacPaint" => "MacPaint", + "MagicaCSG" => "MagicaCSG", + "MagicaVoxel" => "MagicaVoxel", + "Magma" => "Magma", + "MakeHuman" => "MakeHuman", + "Malmal" => "Malmal", + "Mandelbulb3D" => "Mandelbulb 3D", + "Mandelbulber" => "Mandelbulber", + "MangaStudio" => "Manga Studio", + "Mari" => "Mari", + "MarmosetToolbag" => "Marmoset Toolbag", + "MarvelousDesigner" => "Marvelous Designer", + "MasterpieceStudioPro" => "Masterpiece Studio Pro", + "MasterpieceVR" => "MasterpieceVR", + "Maverick" => "Maverick", + "MaxwellRender" => "Maxwell Render", + "Maya" => "Maya", + "MediBangPaint" => "MediBang Paint", + "MediumbyAdobe" => "Medium by Adobe", + "Megascans" => "Megascans", + "mentalray" => "mental ray", + "MeshLab" => "MeshLab", + "Meshroom" => "Meshroom", + "MetaHumanCreator" => "MetaHuman Creator", + "Metashape" => "Metashape", + "MightyBake" => "MightyBake", + "MikuMikuDance" => "MikuMikuDance", + "Minecraft" => "Minecraft", + "Mischief" => "Mischief", + "Mixamo" => "Mixamo", + "Mixer" => "Mixer", + "MoI3D" => "MoI3D", + "Mocha" => "Mocha", + "Modo" => "Modo", + "Moho" => "Moho", + "MotionBuilder" => "MotionBuilder", + "Mudbox" => "Mudbox", + "Muse" => "Muse", + "MSPaint" => "MS Paint", + "MyPaint" => "MyPaint", + "NDO" => "NDO", + "NX" => "NX", + "NdotCAD" => "NdotCAD", + "NintendoNotes" => "Nintendo Notes", + "NomadSculpt" => "Nomad Sculpt", + "Notability" => "Notability", + "Nuke" => "Nuke", + "Nvil" => "Nvil", + "OctaneRender" => "Octane Render", + "Omniverse" => "Omniverse", + "OmniverseCreate" => "Omniverse Create", + "ON1PhotoRAW" => "ON1 Photo RAW", + "Open3DEngine" => "Open 3D Engine", + "OpenCanvas" => "OpenCanvas", + "OpenGL" => "OpenGL", + "OpenToonz" => "OpenToonz", + "Ornatrix" => "Ornatrix", + "OsciRender" => "Osci-Render", + "OurPaint" => "Our Paint", + "PBRMAX" => "PBRMAX", + "PFTrack" => "PFTrack", + "PTGui" => "PTGui", + "Paintbrush" => "Paintbrush", + "PaintNET" => "Paint.NET", + "PaintShopPro" => "PaintShop Pro", + "PaintToolSAI" => "Paint Tool SAI", + "PaintstormStudio" => "Paintstorm Studio", + "Paper" => "Paper", + "Pencil2D" => "Pencil2D", + "Penpot" => "Penpot", + "PhoenixFD" => "Phoenix FD", + "Phonto" => "Phonto", + "PhotoLab2" => "PhotoLab 2", + "Photopea" => "Photopea", + "Photoscan" => "Photoscan", + "Photoshop" => "Photoshop", + "PhotoshopElements" => "Photoshop Elements", + "PicoCAD" => "picoCAD", + "PicoCAD2" => "picoCAD 2", + "Pinta" => "Pinta", + "Piskel" => "Piskel", + "Pixilart" => "Pixilart", + "Pixelitor" => "Pixelitor", + "Pixelmator" => "Pixelmator", + "Pixelorama" => "Pixelorama", + "PixivSketch" => "pixiv Sketch", + "Pixquare" => "Pixquare", + "PlantCatalog" => "PlantCatalog", + "PlantFactory" => "PlantFactory", + "Plasticity" => "Plasticity", + "PNGtuberPlus" => "PNGtuber Plus", + "Poliigon" => "Poliigon", + "Polybrush" => "Polybrush", + "PopcornFx" => "PopcornFx", + "Poser" => "Poser", + "Premiere" => "Premiere", + "PremiereElements" => "Premiere Elements", + "PresagisCreator" => "Presagis Creator", + "ProTools" => "Pro Tools", + "Procreate" => "Procreate", + "ProcreateDreams" => "Procreate Dreams", + "Producer" => "Producer", + "PrometheanAI" => "Promethean AI", + "PureRef" => "PureRef", + "Python" => "Python", + "PyxelEdit" => "PyxelEdit", + "QuadRemesher" => "Quad Remesher", + "QuarkXPress" => "QuarkXPress", + "Qubicle" => "Qubicle", + "Quill" => "Quill", + "QuixelBridge" => "Quixel Bridge", + "QuixelMegascans" => "Quixel Megascans", + "QuixelMixer" => "Quixel Mixer", + "QuixelSuite" => "Quixel Suite", + "R3DSWrap" => "R3DS Wrap", + "R3DSZWRAP" => "R3DS ZWRAP", + "RDTextures" => "RD-Textures", + "RailClone" => "RailClone", + "RealFlow" => "RealFlow", + "RealisticPaintStudio" => "Realistic Paint Studio", + "RealityCapture" => "RealityCapture", + "RealityScan" => "RealityScan", + "RealtimeBoard" => "Realtime Board", + "Rebelle" => "Rebelle", + "Redshift" => "Redshift", + "RenderMan" => "RenderMan", + "RenderNetwork" => "Render Network", + "Revit" => "Revit", + "Rhino" => "Rhino", + "Rhinoceros" => "Rhinoceros", + "RizomUV" => "RizomUV", + "RoughAnimator" => "Rough Animator", + "SamsungNotes" => "Samsung Notes", + "SamsungPENUP" => "Samsung PENUP", + "ScansLibrary" => "ScansLibrary", + "Scrivener" => "Scrivener", + "Sculpt+" => "Sculpt+", + "Sculptris" => "Sculptris", + "ShaveandaHaircut" => "Shave and a Haircut", + "ShiVa3D" => "ShiVa3D", + "Shotgun" => "Shotgun", + "Silo" => "Silo", + "Silugen" => "Silugen", + "Sketch" => "Sketch", + "SketchApp" => "Sketch App", + "SketchBookPro" => "SketchBook Pro", + "SketchClub" => "SketchClub", + "SketchUp" => "SketchUp", + "Sketchable" => "Sketchable", + "Sketchfab" => "Sketchfab", + "Skyshop" => "Skyshop", + "Snapseed" => "Snapseed", + "Snowdrop" => "Snowdrop", + "Softimage" => "Softimage", + "SolidWorks" => "SolidWorks", + "SonySketch" => "Sony Sketch", + "Soundbooth" => "Soundbooth", + "Source2" => "Source 2", + "SourceControl" => "Source Control", + "SourceFilmmaker" => "Source Filmmaker", + "SpeedTree" => "SpeedTree", + "Speedgrade" => "Speedgrade", + "SpeedyPainter" => "SpeedyPainter", + "Spine2D" => "Spine 2D", + "Spriter" => "Spriter", + "Stingray" => "Stingray", + "Storyboarder" => "Storyboarder", + "StoryboardPro" => "Storyboard Pro", + "SublimeText" => "Sublime Text", + "Substance3DDesigner" => "Substance 3D Designer", + "Substance3DModeler" => "Substance 3D Modeler", + "Substance3DPainter" => "Substance 3D Painter", + "Substance3DSampler" => "Substance 3D Sampler", + "Substance3DStager" => "Substance 3D Stager", + "SubstanceB2M" => "Substance B2M", + "SweetHome3D" => "Sweet Home 3D", + "SynthEyes" => "SynthEyes", + "TTools" => "TTools", + "TVPaint" => "TVPaint", + "TVPaintAnimation" => "TVPaint Animation", + "TayasuiSketches" => "Tayasui Sketches", + "TayasuiSketchesMobileApp" => "Tayasui Sketches Mobile App", + "TayasuiSketchesPro" => "Tayasui Sketches Pro", + "Terragen" => "Terragen", + "Texturescom" => "Textures.com", + "Texturingxyz" => "Texturingxyz", + "TeyaConceptor" => "Teya Conceptor", + "TheGrove3D" => "The Grove 3D", + "TheaRender" => "Thea Render", + "Threejs" => "Three.js", + "Tiled" => "Tiled", + "TiltBrush" => "Tilt Brush", + "Tooll3" => "Tooll3", + "ToonBoomHarmony" => "Toon Boom Harmony", + "ToonBoomStudio" => "Toon Boom Studio", + "ToonSquid" => "ToonSquid", + "TopoGun" => "TopoGun", + "TuxPaint" => "Tux Paint", + "Tvori" => "Tvori", + "Twinmotion" => "Twinmotion", + "UNIGINEEngine" => "UNIGINE Engine", + "UVLayout" => "UVLayout", + "UltraFractal" => "Ultra Fractal", + "uMake" => "uMake", + "Unfold3D" => "Unfold 3D", + "Unity" => "Unity", + "UnrealEngine" => "Unreal Engine", + "Vengi" => "vengi", + "VRay" => "V-Ray", + "VRED" => "VRED", + "VTubeStudio" => "VTube Studio", + "Vectary" => "Vectary", + "VectorayGen" => "VectorayGen", + "Vectorworks" => "Vectorworks", + "VegasPro" => "Vegas Pro", + "VisualDesigner3D" => "Visual Designer 3D", + "VisualStudio" => "Visual Studio", + "VRoidStudio" => "VRoid Studio", + "Vue" => "Vue", + "Vuforia" => "Vuforia", + "WebGL" => "WebGL", + "WhiteboardFox" => "Whiteboard Fox", + "WickEditor" => "Wick Editor", + "Wings3D" => "Wings 3D", + "Word" => "Word", + "WorldCreator" => "World Creator", + "WorldMachine" => "World Machine", + "XParticles" => "X-Particles", + "Xfrog" => "Xfrog", + "Xgen" => "Xgen", + "xNormal" => "xNormal", + "xTex" => "xTex", + "XoliulShader" => "Xoliul Shader", + "Yafaray" => "Yafaray", + "Yeti" => "Yeti", + "ZBrush" => "ZBrush", + "ZBrushCore" => "ZBrushCore", + "ZenBrush" => "Zen Brush" + ] + ] + ]; + } + + private function get($proxy, $url, $get = [], $search){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: application/json, text/plain, */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + //"sentry-trace: 72b0318a7141fe18cbacbd905572eddf-a60de161b66b1e6f-1 + //"baggage: sentry-environment=vercel-production,sentry-release=251ff5179b4de94974f36d9b8659a487bbb8a819,sentry-public_key=2b87af2b44c84643a011838ad097735f,sentry-trace_id=72b0318a7141fe18cbacbd905572eddf,sentry-transaction=GET%20%2Fsearch,sentry-sampled=true,sentry-sample_rand=0.09967130764937493,sentry-sample_rate=0.5", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + //"Referer: https://cara.app/search?q=jak+and+daxter&type=&sortBy=Top&filters=%7B%7D", + "Referer: https://cara.app/search?q=" . urlencode($search), + //"Cookie: __Host-next-auth.csrf-token=b752c4296375bccb7b480ff010e1e916c65c35c311a4a57ac6cd871468730578%7C4d3783cfb72a98f390e534abd149806432b6cf8d50555a52d00e99216a516911; __Secure-next-auth.callback-url=https%3A%2F%2Fcara.app; crumb=BV0HDt87G5+fOWE0ZDQ5MWM0ZTQ3YTZmMzM4MGU5MGNjNDNmMzY2", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-origin", + "TE: trailers"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function image($get){ + + if($get["npt"]){ + + [$npt, $proxy] = + $this->backend->get( + $get["npt"], + "images" + ); + + $npt = json_decode($npt, true); + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + + $npt = [ + "q" => $get["s"], + "sortBy" => $get["sort"], + "take" => 24, + "skip" => 0, + "filters" => [] + ]; + + // parse filters + if($get["type"] != "any"){ + + $npt["filters"]["posts"] = [$get["type"]]; + } + + if($get["fields"] != "any"){ + + $npt["filters"]["fields"] = [$get["fields"]]; + } + + if($get["category"] != "any"){ + + $npt["filters"]["categories"] = [$get["category"]]; + } + + if($get["software"] != "any"){ + + $npt["filters"]["softwares"] = [$get["software"]]; + } + + if($npt["filters"] == []){ + + $npt["filters"] = "{}"; + }else{ + + $npt["filters"] = json_encode($npt["filters"]); + } + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + // https://cara.app/api/search/portfolio-posts?q=jak+and+daxter&sortBy=Top&take=24&skip=0&filters=%7B%7D + try{ + $json = + $this->get( + $proxy, + "https://cara.app/api/search/posts", + $npt, + $npt["q"] + ); + + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + $imagecount = 0; + foreach($json as $image){ + + if(count($image["images"]) === 0){ + + // sometimes the api returns no images for an object + $imagecount++; + continue; + } + + $cover = null; + $sources = []; + + foreach($image["images"] as $source){ + + if($source["isCoverImg"]){ + + $cover = [ + "url" => "https://images.cara.app/" . $this->fix_url($source["src"]), + "width" => 500, + "height" => 500 + ]; + }else{ + + $sources[] = [ + "url" => "https://images.cara.app/" . $this->fix_url($source["src"]), + "width" => null, + "height" => null + ]; + } + } + + if($cover !== null){ + + $sources[] = $cover; + } + + $out["image"][] = [ + "title" => str_replace("\n", " ", $image["content"]), + "source" => $sources, + "url" => "https://cara.app/post/" . $image["id"] + ]; + + $imagecount++; + } + + if($imagecount === 24){ + + $npt["skip"] += 24; + + $out["npt"] = + $this->backend->store( + json_encode($npt), + "images", + $proxy + ); + } + + return $out; + } + + private function fix_url($url){ + + return + str_replace( + [" "], + ["%20"], + $url + ); + } +} diff --git a/scraper/coccoc.php b/scraper/coccoc.php new file mode 100644 index 0000000..fd09556 --- /dev/null +++ b/scraper/coccoc.php @@ -0,0 +1,672 @@ +<?php + +class coccoc{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("coccoc"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + + private function get($proxy, $url, $get = []){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + // http2 bypass + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, [ + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + //"Cookie: _contentAB_15040_vi=V-06_01; split_test_search=new_search; uid=L_bauXyZBY1B; vid=uCVQJQSTgb9QGT3o; ls=1753742684; serp_version=29223843/7621a70; savedS=direct", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: cross-site", + "Priority: u=0, i" + ]); + + $this->backend->assign_proxy($curlproc, $proxy); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function getfilters($pagetype){ + + return [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", // nsfw by default???? + "no" => "No" // &safe=1 + ] + ], + "time" => [ + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "1w" => "1 week ago", + "2w" => "2 weeks ago", + "1m" => "1 month ago", + "3m" => "3 months ago", + "6m" => "6 months ago", + "1Y" => "1 year ago" + ] + ], + "filter" => [ + "display" => "Remove duplicates", + "option" => [ + "no" => "No", + "yes" => "Yes" // &filter=0 + ] + ] + ]; + } + + public function web($get){ + + if($get["npt"]){ + + [$query, $proxy] = + $this->backend->get( + $get["npt"], + "web" + ); + + $query = json_decode($query, true); + }else{ + + $proxy = $this->backend->get_ip(); + + $query = [ + "query" => $get["s"] + ]; + + // add filters + if($get["nsfw"] == "no"){ + + $query["safe"] = 1; + } + + if($get["time"] != "any"){ + + $query["tbs"] = $get["time"]; + } + + if($get["filter"] == "yes"){ + + $query["filter"] = 0; + } + } + + try{ + + $html = + $this->get( + $proxy, + "https://coccoc.com/search", + $query + ); + }catch(Exception $error){ + + throw new Exception("Failed to get search page"); + } + //$html = file_get_contents("scraper/coccoc.html"); + + + $html = explode("window.composerResponse", $html, 2); + + if(count($html) !== 2){ + + throw new Exception("Failed to grep window.composerResponse"); + } + + $html = + json_decode( + $this->fuckhtml + ->extract_json( + ltrim($html[1], " =") + ), + true + ); + + if($html === null){ + + throw new Exception("Failed to decode JSON"); + } + + if(!isset($html["search"]["search_results"])){ + + throw new Exception("Coc Coc did not return a search_results object"); + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + // word correction + foreach($html["top"] as $element){ + + if(isset($element["spellChecker"][0]["query"])){ + + $out["spelling"] = [ + "type" => "not_many", + "using" => $html["search"]["query"], + "correction" => $element["spellChecker"][0]["query"] + ]; + } + } + + foreach($html["search"]["search_results"] as $result){ + + if(isset($result["type"])){ + + switch($result["type"]){ + + // + // Related searches + // + case "related_queries": + $out["related"] = $result["queries"]; + continue 2; + + // + // Videos + // + case "video_hits": + foreach($result["results"] as $video){ + + if( + isset($video["image_url"]) && + !empty($video["image_url"]) + ){ + + $thumb = [ + "ratio" => "16:9", + "url" => $video["image_url"] + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["video"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $video["title"] + ) + ), + "description" => null, + "author" => [ + "name" => $video["uploader"], + "url" => null, + "avatar" => null + ], + "date" => (int)$video["date"], + "duration" => (int)$video["duration"], + "views" => null, + "thumb" => $thumb, + "url" => $video["url"] + ]; + } + continue 2; + } + } + + if( + !isset($result["title"]) || + !isset($result["url"]) + ){ + + // should not happen + continue; + } + + if(isset($result["rich"]["data"]["image_url"])){ + + $thumb = [ + "url" => $result["rich"]["data"]["image_url"], + "ratio" => "16:9" + ]; + }else{ + + $thumb = [ + "url" => null, + "ratio" => null + ]; + } + + $sublinks = []; + + if(isset($result["rich"]["data"]["linked_docs"])){ + + foreach($result["rich"]["data"]["linked_docs"] as $sub){ + + $sublinks[] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $sub["title"] + ) + ), + "description" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $sub["content"] + ) + ), + "date" => null, + "url" => $sub["url"] + ]; + } + } + + // get date + if(isset($result["date"])){ + + $date = (int)$result["date"]; + }else{ + + $date = null; + } + + // probe for metadata + $table = []; + + if(isset($result["rich"]["data"]["rating"])){ + + $table["Rating"] = $result["rich"]["data"]["rating"]; + + if(isset($result["rich"]["data"]["num_rating"])){ + + $table["Rating"] .= " (" . number_format($result["rich"]["data"]["num_rating"]) . " ratings)"; + } + } + + if(isset($result["rich"]["data"]["views"])){ + + $table["Views"] = number_format($result["rich"]["data"]["views"]); + } + + if(isset($result["rich"]["data"]["duration"])){ + + $table["Duration"] = $this->int2hms($result["rich"]["data"]["duration"]); + } + + if(isset($result["rich"]["data"]["channel_name"])){ + + $table["Author"] = $result["rich"]["data"]["channel_name"]; + } + + if(isset($result["rich"]["data"]["video_quality"])){ + + $table["Quality"] = $result["rich"]["data"]["video_quality"]; + } + + if(isset($result["rich"]["data"]["category"])){ + + $table["Category"] = $result["rich"]["data"]["category"]; + } + + $out["web"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $result["title"] + ) + ), + "description" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $result["content"] + ) + ), + "url" => $result["url"], + "date" => $date, + "type" => "web", + "thumb" => $thumb, + "sublink" => $sublinks, + "table" => $table + ]; + } + + // + // Get wikipedia head + // + if(isset($html["right"])){ + + foreach($html["right"] as $wiki){ + + $description = []; + + if(isset($wiki["short_intro"])){ + + $description[] = + [ + "type" => "quote", + "value" => $wiki["short_intro"], + ]; + } + + if(isset($wiki["intro"])){ + + $description[] = + [ + "type" => "text", + "value" => $wiki["intro"], + ]; + } + + // get table elements + $table = []; + + if(isset($wiki["fields"])){ + + foreach($wiki["fields"] as $element){ + + $table[$element["title"]] = implode(", ", $element["value"]); + } + } + + // get sublinks + $sublinks = []; + + if(isset($wiki["website"])){ + + if( + preg_match( + '/^http/', + $wiki["website"] + ) === 0 + ){ + + $sublinks["Website"] = "https://" . $wiki["website"]; + }else{ + + $sublinks["Website"] = $wiki["website"]; + } + } + + foreach($wiki["profiles"] as $sitename => $url){ + + $sitename = explode("_", $sitename); + $sitename = ucfirst($sitename[count($sitename) - 1]); + + $sublinks[$sitename] = $url; + } + + $out["answer"][] = [ + "title" => + $this->titledots( + $wiki["title"] + ), + "description" => $description, + "url" => null, + "thumb" => isset($wiki["image"]["contentUrl"]) ? $wiki["image"]["contentUrl"] : null, + "table" => $table, + "sublink" => $sublinks + ]; + } + } + + // get next page + if((int)$html["search"]["page"] < (int)$html["search"]["max_page"]){ + + // https://coccoc.com/composer?_=1754021153532&p=0&q=zbabduiqwhduwqhdnwq&reqid=bwcAs00q&s=direct&apiV=1 + // ^json endpoint, but we can just do &page=2 lol + + if(!isset($query["page"])){ + + $query["page"] = 2; + }else{ + + $query["page"]++; + } + + $out["npt"] = + $this->backend + ->store( + json_encode($query), + "web", + $proxy + ); + } + + return $out; + } + + public function video($get){ + + //$html = file_get_contents("scraper/coccoc.html"); + if($get["npt"]){ + + [$query, $proxy] = + $this->backend->get( + $get["npt"], + "videos" + ); + + $query = json_decode($query, true); + }else{ + + $proxy = $this->backend->get_ip(); + + $query = [ + "query" => $get["s"], + "tbm" => "vid" + ]; + + // add filters + if($get["nsfw"] == "no"){ + + $query["safe"] = 1; + } + + if($get["time"] != "any"){ + + $query["tbs"] = $get["time"]; + } + + if($get["filter"] == "yes"){ + + $query["filter"] = 0; + } + } + + try{ + + $html = + $this->get( + $proxy, + "https://coccoc.com/search", + $query + ); + }catch(Exception $error){ + + throw new Exception("Failed to get search page"); + } + + $html = explode("window.composerResponse", $html, 2); + + if(count($html) !== 2){ + + throw new Exception("Failed to grep window.composerResponse"); + } + + $html = + json_decode( + $this->fuckhtml + ->extract_json( + ltrim($html[1], " =") + ), + true + ); + + if($html === null){ + + throw new Exception("Failed to decode JSON"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + if(!isset($html["search_video"]["search_results"])){ + + if(isset($html["search_video"]["error"]["title"])){ + + if($html["search_video"]["error"]["title"] == "Không tìm thấy kết quả nào"){ + + return $out; + } + + throw new Exception("Coc Coc returned an error: " . $html["search_video"]["error"]["title"]); + } + + throw new Exception("Coc Coc did not supply a search_results object"); + } + + foreach($html["search_video"]["search_results"] as $video){ + + if(isset($video["rich"]["data"]["image_url"])){ + + $thumb = [ + "ratio" => "16:9", + "url" => $video["rich"]["data"]["image_url"] + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["video"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $video["title"] + ) + ), + "description" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $video["content"] + ) + ), + "author" => [ + "name" => + isset($video["rich"]["data"]["channel_name"]) ? + $video["rich"]["data"]["channel_name"] : null, + "url" => null, + "avatar" => null + ], + "date" => + isset($video["date"]) ? + $video["date"] : null, + "duration" => + isset($video["rich"]["data"]["duration"]) ? + (int)$video["rich"]["data"]["duration"] : null, + "views" => null, + "thumb" => $thumb, + "url" => $video["url"] + ]; + } + + // get next page + if((int)$html["search_video"]["page"] < (int)$html["search_video"]["max_page"]){ + + if(!isset($query["page"])){ + + $query["page"] = 2; + }else{ + + $query["page"]++; + } + + $out["npt"] = + $this->backend + ->store( + json_encode($query), + "videos", + $proxy + ); + } + + return $out; + } + + private function titledots($title){ + + return trim($title, " .\t\n\r\0\x0B…"); + } + + private function int2hms($seconds){ + + $hours = floor($seconds / 3600); + $minutes = floor(($seconds % 3600) / 60); + $seconds = $seconds % 60; + + return sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds); + } +} diff --git a/scraper/crowdview.php b/scraper/crowdview.php new file mode 100644 index 0000000..8fb267b --- /dev/null +++ b/scraper/crowdview.php @@ -0,0 +1,145 @@ +<?php + +class crowdview{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("crowdview"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + return []; + } + + private function get($proxy, $url, $get = []){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function web($get){ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + + try{ + $json = $this->get( + $proxy, + "https://crowdview-next-js.onrender.com/api/search-v3", + [ + "query" => $search + ] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + $json = json_decode($json, true); + + if($json === NULL){ + + throw new Exception("Failed to decode JSON"); + } + + foreach($json["results"] as $item){ + + $description = explode("<b>", $item["snippet"], 2); + + $out["web"][] = [ + "title" => $this->sanitize($item["title"]), + "description" => $this->sanitize($description[1]), + "url" => $item["link"], + "date" => strtotime($description[0]), + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => [], + "table" => [] + ]; + } + + return $out; + } + + private function sanitize($html){ + + return + trim( + $this->fuckhtml + ->getTextContent( + html_entity_decode( + $html + ) + ), + ". " + ); + } +} diff --git a/scraper/curlie.php b/scraper/curlie.php new file mode 100644 index 0000000..61a8eb2 --- /dev/null +++ b/scraper/curlie.php @@ -0,0 +1,309 @@ +<?php + +class curlie{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("curlie"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + if($page != "web"){ + + return []; + } + + return [ + "lang" => [ + "display" => "Language", + "option" => [ + "any" => "Any language", + "en" => "English", + "de" => "German", + "fr" => "French", + "ja" => "Japanese", + "it" => "Italian", + "es" => "Spanish", + "ru" => "Russian", + "nl" => "Dutch", + "pl" => "Polish", + "tr" => "Turkish", + "da" => "Danish", + "sv" => "Swedish", + "no" => "Norwegian", + "is" => "Icelandic", + "fo" => "Faroese", + "fi" => "Finnish", + "et" => "Estonian", + "lt" => "Lithuanian", + "lv" => "Latvian", + "cy" => "Welsh", + "ga" => "Irish", + "gd" => "Scottish Gaelic", + "br" => "Breton", + "fy" => "Frisian", + "frr" => "North Frisian", + "gem" => "Saterland Frisian", + "lb" => "Luxembourgish", + "rm" => "Romansh", + "pt" => "Portuguese", + "ca" => "Catalan", + "gl" => "Galician", + "eu" => "Basque", + "ast" => "Asturian", + "an" => "Aragonese", + "fur" => "Friulan", + "sc" => "Sardinian", + "scn" => "Sicilian", + "oc" => "Occitan", + "be" => "Belarusian", + "cs" => "Czech", + "hu" => "Hungarian", + "sk" => "Slovak", + "uk" => "Ukrainian", + "csb" => "Kashubian", + "tt" => "Tatar", + "ba" => "Bashkir", + "os" => "Ossetian", + "sl" => "Slovene", + "sr" => "Serbian", + "hr" => "Croatian", + "bs" => "Bosnian", + "bg" => "Bulgarian", + "sq" => "Albanian", + "ro" => "Romanian", + "mk" => "Macedonian", + "el" => "Greek", + "iw" => "Hebrew", + "fa" => "Persian", + "ar" => "Arabic", + "ku" => "Kurdish", + "az" => "Azerbaijani", + "hy" => "Armenian", + "af" => "Afrikaans", + "sw" => "Kiswahili", + "uz" => "Uzbek", + "kk" => "Kazakh", + "ky" => "Kyrgyz", + "tg" => "Tajik", + "tk" => "Turkmen", + "ug" => "Uyghurche", + "hi" => "Hindi", + "si" => "Sinhalese", + "gu" => "Gujarati", + "ur" => "Urdu", + "mr" => "Marathi", + "pa" => "Punjabi", + "bn" => "Bengali", + "ta" => "Tamil", + "te" => "Telugu", + "kn" => "Kannada", + "zh_CN" => "Chinese Simplified", + "zh_TW" => "Chinese Traditional", + "ko" => "Korean", + "cfr" => "Taiwanese", + "th" => "Thai", + "vi" => "Vietnamese", + "in" => "Indonesian", + "ms" => "Malay", + "tl" => "Tagalog", + "eo" => "Esperanto", + "ia" => "Interlingua", + "la" => "Latin" + ] + ] + ]; + } + + private function get($proxy, $url, $get = []){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function web($get){ + + if($get["npt"]){ + + [$query, $proxy] = $this->backend->get($get["npt"], "web"); + + try{ + $html = $this->get( + $proxy, + "https://curlie.org/" . $query, + [] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + }else{ + $proxy = $this->backend->get_ip(); + + $query = [ + "q" => $get["s"], + "start" => 0, + "stime" => 92452189 // ? + ]; + + if($get["lang"] !== "any"){ + + $query["lang"] = $get["lang"]; + } + + try{ + $html = $this->get( + $proxy, + "https://curlie.org/search", + $query + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + } + + $this->fuckhtml->load($html); + + $nextpage = + $this->fuckhtml + ->getElementsByClassName( + "next-page", + "a" + ); + + if(count($nextpage) !== 0){ + + $nextpage = + $this->backend->store( + $nextpage[0]["attributes"]["href"], + "web", + $proxy + ); + }else{ + + $nextpage = null; + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => $nextpage, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + $items = + $this->fuckhtml + ->getElementsByClassName( + "site-item", + "div" + ); + + foreach($items as $item){ + + $this->fuckhtml->load($item); + + $a = + $this->fuckhtml + ->getElementsByAttributeValue( + "target", + "_blank", + "a" + )[0]; + + $description = + $this->fuckhtml + ->getElementsByClassName("site-descr"); + + if(count($description) !== 0){ + + $description = + $this->fuckhtml + ->getTextContent( + $description[0] + ); + }else{ + + $description = null; + } + + $out["web"][] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $a + ), + "description" => $description, + "url" => + $this->fuckhtml + ->getTextContent( + $a["attributes"]["href"] + ), + "date" => null, + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => [], + "table" => [] + ]; + } + + return $out; + } +} diff --git a/scraper/ddg.php b/scraper/ddg.php new file mode 100644 index 0000000..49e0d37 --- /dev/null +++ b/scraper/ddg.php @@ -0,0 +1,2246 @@ +<?php + +class ddg{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("ddg"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + /* + curl functions + */ + private const req_web = 0; + private const req_xhr = 1; + + private function get($proxy, $url, $get = [], $reqtype = self::req_web){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + // http2 bypass + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + switch($reqtype){ + case self::req_web: + $headers = + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: same-origin", + "Sec-Fetch-User: ?1", + "Priority: u=0, i", + "TE: trailers"]; + break; + + case self::req_xhr: + $headers = + ["User-Agent: " . config::USER_AGENT, + "Accept: */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Referer: https://duckduckgo.com/", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Sec-Fetch-Dest: script", + "Sec-Fetch-Mode: no-cors", + "Sec-Fetch-Site: same-site", + "Priority: u=1"]; + break; + } + + $this->backend->assign_proxy($curlproc, $proxy); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function getfilters($pagetype){ + + $base = [ + "country" => [ + "display" => "Country", + "option" => [ + "us-en" => "US (English)", + "ar-es" => "Argentina", + "au-en" => "Australia", + "at-de" => "Austria", + "be-fr" => "Belgium (fr)", + "be-nl" => "Belgium (nl)", + "br-pt" => "Brazil", + "bg-bg" => "Bulgaria", + "ca-en" => "Canada (en)", + "ca-fr" => "Canada (fr)", + "ct-ca" => "Catalonia", + "cl-es" => "Chile", + "cn-zh" => "China", + "co-es" => "Colombia", + "hr-hr" => "Croatia", + "cz-cs" => "Czech Republic", + "dk-da" => "Denmark", + "ee-et" => "Estonia", + "fi-fi" => "Finland", + "fr-fr" => "France", + "de-de" => "Germany", + "gr-el" => "Greece", + "hk-tzh" => "Hong Kong", + "hu-hu" => "Hungary", + "in-en" => "India (en)", + "id-en" => "Indonesia (en)", + "ie-en" => "Ireland", + "il-en" => "Israel (en)", + "it-it" => "Italy", + "jp-jp" => "Japan", + "kr-kr" => "Korea", + "lv-lv" => "Latvia", + "lt-lt" => "Lithuania", + "my-en" => "Malaysia (en)", + "mx-es" => "Mexico", + "nl-nl" => "Netherlands", + "nz-en" => "New Zealand", + "no-no" => "Norway", + "pk-en" => "Pakistan (en)", + "pe-es" => "Peru", + "ph-en" => "Philippines (en)", + "pl-pl" => "Poland", + "pt-pt" => "Portugal", + "ro-ro" => "Romania", + "ru-ru" => "Russia", + "xa-ar" => "Saudi Arabia", + "sg-en" => "Singapore", + "sk-sk" => "Slovakia", + "sl-sl" => "Slovenia", + "za-en" => "South Africa", + "es-ca" => "Spain (ca)", + "es-es" => "Spain (es)", + "se-sv" => "Sweden", + "ch-de" => "Switzerland (de)", + "ch-fr" => "Switzerland (fr)", + "tw-tzh" => "Taiwan", + "th-en" => "Thailand (en)", + "tr-tr" => "Turkey", + "us-es" => "US (Spanish)", + "ua-uk" => "Ukraine", + "uk-en" => "United Kingdom", + "vn-en" => "Vietnam (en)" + ] + ] + ]; + + switch($pagetype){ + + case "web": + $base["country"]["option"] = + array_merge(["any" => "All Regions"], $base["country"]["option"]); + + return array_merge($base, + [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "maybe" => "Maybe", + "no" => "No" + ] + ], + "newer" => [ + "display" => "Newer than", + "option" => "_DATE" + ], + "older" => [ + "display" => "Older than", + "option" => "_DATE" + ], + "extendedsearch" => [ + // undefined display + "option" => [ + "yes" => "Yes", + "no" => "No", + ] + ] + ] + ); + break; + + case "images": + return array_merge($base, + [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "no" => "No" + ] + ], + "date" => [ + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "Day" => "Past day", + "Week" => "Past week", + "Month" => "Past month" + ] + ], + "size" => [ + "display" => "Size", + "option" => [ + "any" => "Any size", + "Small" => "Small", + "Medium" => "Medium", + "Large" => "Large", + "Wallpaper" => "Wallpaper" + ] + ], + "color" => [ + "display" => "Colors", + "option" => [ + "any" => "All colors", + "Monochrome" => "Black and white", + "Red" => "Red", + "Orange" => "Orange", + "Yellow" => "Yellow", + "Green" => "Green", + "Blue" => "Blue", + "Purple" => "Purple", + "Pink" => "Pink", + "Brown" => "Brown", + "Black" => "Black", + "Gray" => "Gray", + "Teal" => "Teal", + "White" => "White" + ] + ], + "type" => [ + "display" => "Type", + "option" => [ + "any" => "All types", + "photo" => "Photograph", + "clipart" => "Clipart", + "gif" => "Animated GIF", + "transparent" => "Transparent" + ] + ], + "layout" => [ + "display" => "Layout", + "option" => [ + "any" => "All layouts", + "Square" => "Square", + "Tall" => "Tall", + "Wide" => "Wide" + ] + ], + "license" => [ + "display" => "License", + "option" => [ + "any" => "All licenses", + "Any" => "All Creative Commons", + "Public" => "Public domain", + "Share" => "Free to Share and Use", + "ShareCommercially" => "Free to Share and Use Commercially", + "Modify" => "Free to Modify, Share, and Use", + "ModifyCommercially" => "Free to Modify, Share, and Use Commercially" + ] + ] + ] + ); + break; + + case "videos": + return array_merge($base, + [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "maybe" => "Maybe", + "no" => "No" + ] + ], + "date" => [ + "display" => "Time fetched", + "option" => [ + "any" => "Any time", + "d" => "Past day", + "w" => "Past week", + "m" => "Past month" + ] + ], + "resolution" => [ //videoDefinition + "display" => "Resolution", + "option" => [ + "any" => "Any resolution", + "high" => "High definition", + "standard" => "Standard definition" + ] + ], + "duration" => [ // videoDuration + "display" => "Duration", + "option" => [ + "any" => "Any duration", + "short" => "Short (>5min)", + "medium" => "Medium (5-20min)", + "long" => "Long (<20min)" + ] + ], + "license" => [ + "display" => "License", + "option" => [ + "any" => "Any license", + "creativeCommon" => "Creative Commons", + "youtube" => "YouTube Standard" + ] + ] + ] + ); + break; + + case "news": + return array_merge($base, + [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "maybe" => "Maybe", + "no" => "No" + ] + ], + "date" => [ + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "d" => "Past day", + "w" => "Past week", + "m" => "Past month" + ] + ] + ] + ); + break; + } + } + + public function web($get){ + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + if($get["npt"]){ + + [$js_link, $proxy] = $this->backend->get($get["npt"], "web"); + $js_link = "https://links.duckduckgo.com" . $js_link; + + $html = ""; + $get["extendedsearch"] = "no"; + + }else{ + if(strlen($get["s"]) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + + // generate filters + $get_filters = [ + "q" => $get["s"] + ]; + + if($get["country"] == "any"){ + + $get_filters["kl"] = "wt-wt"; + }else{ + + $get_filters["kl"] = $get["country"]; + } + + switch($get["nsfw"]){ + + case "yes": $get_filters["kp"] = "-2"; break; + case "maybe": $get_filters["kp"] = "-1"; break; + case "no": $get_filters["kp"] = "1"; break; + } + + $df = true; + + if($get["newer"] === false){ + + if($get["older"] !== false){ + + $start = 36000; + $end = $get["older"]; + }else{ + + $df = false; + } + }else{ + + $start = $get["newer"]; + + if($get["older"] !== false){ + + $end = $get["older"]; + }else{ + + $end = time(); + } + } + + if($df === true){ + $get_filters["df"] = date("Y-m-d", $start) . ".." . date("Y-m-d", $end); + } + + // + // Get HTML + // + try{ + $html = $this->get( + $proxy, + "https://duckduckgo.com/", + $get_filters + ); + }catch(Exception $e){ + + throw new Exception("Failed to fetch search page"); + } + + $this->fuckhtml->load($html); + + $script = + $this->fuckhtml + ->getElementById( + "deep_preload_link", + "link" + ); + + if( + $script === null || + !isset($script["attributes"]["href"]) + ){ + + throw new Exception("Failed to grep d.js"); + } + + $js_link = + $this->fuckhtml + ->getTextContent( + $script["attributes"]["href"] + ); + } + + // + // Get d.js + // + try{ + $js = $this->get( + $proxy, + $js_link, + [], + ddg::req_xhr + ); + + }catch(Exception $e){ + + throw new Exception("Failed to fetch d.js"); + } + + //echo htmlspecialchars($js); + + $js_tmp = + preg_split( + '/DDG\.pageLayout\.load\(\s*\'d\'\s*,\s*/', + $js, + 2 + ); + + if(count($js_tmp) <= 1){ + + throw new Exception("Failed to grep pageLayout(d)"); + } + + $json = + json_decode( + $this->fuckhtml + ->extract_json( + $js_tmp[1] + ), + true + ); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + // + // Get search results + NPT token + // + foreach($json as $item){ + + if(isset($item["c"])){ + + if( + !isset($item["s"]) && + isset($item["t"]) && + $item["t"] == "DEEP_ERROR_NO_RESULTS" + ){ + + return $out; + } + + $table = []; + + // get youtube video information + if(isset($item["video"]["thumbnail_url_template"])){ + + $thumb = + [ + "ratio" => "16:9", + "url" => $this->bingimg($item["video"]["thumbnail_url_template"]) + ]; + }else{ + + $thumb = + [ + "ratio" => null, + "url" => null + ]; + } + + // get table items + if(isset($item["rf"])){ + + foreach($item["rf"] as $hint){ + + if( + !isset($hint["label"]["text"]) || + !isset($hint["items"][0]["text"]) + ){ + + continue; + } + + $text = []; + + foreach($hint["items"] as $text_part){ + + $text[] = $text_part["text"]; + } + + $text = implode(", ", $text); + + if(is_numeric($text)){ + + $text = number_format((string)$text); + } + + $table[$hint["label"]["text"]] = $text; + } + } + + // get ratings + if(isset($item["ar"])){ + + foreach($item["ar"] as $rating){ + + if( + isset($rating["aggregateRating"]["bestRating"]) && + isset($rating["aggregateRating"]["ratingValue"]) + ){ + + $text = $rating["aggregateRating"]["ratingValue"] . "/" . $rating["aggregateRating"]["bestRating"]; + + if(isset($rating["aggregateRating"]["reviewCount"])){ + + $text .= " (" . number_format($rating["aggregateRating"]["reviewCount"]) . " votes)"; + } + + $table["Rating"] = $text; + } + } + } + + // get sublinks + $sublinks = []; + + if(isset($item["l"])){ + + foreach($item["l"] as $sublink){ + + $sublinks[] = [ + "title" => $this->titledots($sublink["text"]), + "description" => $this->titledots($sublink["snippet"]), + "url" => $sublink["targetUrl"], + "date" => null + ]; + } + } + + $title = + $this->titledots( + $this->fuckhtml + ->getTextContent( + $item["t"] + ) + ); + + if( + $title == "EOF" && + strpos( + $item["c"], + "google" + ) + ){ + + continue; + } + + // parse search result + $out["web"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $item["t"] + ) + ), + "description" => + isset($item["a"]) ? + $this->titledots( + $this->fuckhtml + ->getTextContent( + $item["a"] + ) + ) : null, + "url" => $this->unshiturl($item["c"]), + "date" => + isset($item["e"]) ? + strtotime($item["e"]) : null, + "type" => "web", + "thumb" => $thumb, + "sublink" => $sublinks, + "table" => $table + ]; + continue; + } + + if(isset($item["n"])){ + + // get NPT + $out["npt"] = + $this->backend->store( + $item["n"], + "web", + $proxy + ); + continue; + } + } + + // + // Get spelling + // + $js_tmp = + preg_split( + '/DDG\.page\.showMessage\(\s*\'spelling\'\s*,\s*/', + $js, + 2 + ); + + if(count($js_tmp) > 1){ + + $json = + json_decode( + $this->fuckhtml + ->extract_json( + $js_tmp[1] + ), + true + ); + + if($json !== null){ + + // parse spelling + // qc=2: including + + switch((int)$json["qc"]){ + + case 2: + $type = "including"; + break; + + default: + $type = "not_many"; + break; + } + + $out["spelling"] = [ + "type" => $type, + "using" => + $this->fuckhtml + ->getTextContent( + $json["suggestion"] + ), + "correction" => html_entity_decode($json["recourseText"]) + ]; + } + } + + // + // Get images + // + $js_tmp = + preg_split( + '/DDG\.duckbar\.load\(\s*\'images\'\s*,\s*/', + $js, + 2 + ); + + if(count($js_tmp) > 1){ + + $json = + json_decode( + $this->fuckhtml + ->extract_json( + $js_tmp[1] + ), + true + ); + + if($json !== null){ + + foreach($json["results"] as $image){ + + $ratio = $this->bingratio((int)$image["width"], (int)$image["height"]); + + $out["image"][] = [ + "title" => $image["title"], + "source" => [ + [ + "url" => $image["image"], + "width" => (int)$image["width"], + "height" => (int)$image["height"] + ], + [ + "url" => $this->bingimg($image["thumbnail"]), + "width" => $ratio[0], + "height" => $ratio[1] + ] + ], + "url" => $this->unshiturl($image["url"]) + ]; + } + } + } + + // + // Get videos + // + $js_tmp = + preg_split( + '/DDG\.duckbar\.load\(\s*\'videos\'\s*,\s*/', + $js, + 2 + ); + + if(count($js_tmp) > 1){ + + $json = + json_decode( + $this->fuckhtml + ->extract_json( + $js_tmp[1] + ), + true + ); + + if($json !== null){ + + foreach($json["results"] as $video){ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + + foreach(["large", "medium", "small"] as $contender){ + + if(isset($video["images"][$contender])){ + + $thumb = [ + "ratio" => "16:9", + "url" => $this->bingimg($video["images"][$contender]) + ]; + break; + } + } + + $out["video"][] = [ + "title" => $this->titledots($video["title"]), + "description" => + $video["description"] != "" ? + $this->titledots($video["description"]) : null, + "date" => + isset($video["published"]) ? + strtotime($video["published"]) : null, + "duration" => + $video["duration"] != "" ? + $this->hms2int($video["duration"]) : null, + "views" => + isset($video["statistics"]["viewCount"]) ? + (int)$video["statistics"]["viewCount"] : null, + "thumb" => $thumb, + "url" => $this->unshiturl($video["content"]) + ]; + } + } + } + + // + // Get news + // + $js_tmp = + preg_split( + '/DDG\.duckbar\.load\(\s*\'news\'\s*,\s*/', + $js, + 2 + ); + + if(count($js_tmp) > 1){ + + $json = + json_decode( + $this->fuckhtml + ->extract_json( + $js_tmp[1] + ), + true + ); + + if($json !== null){ + + foreach($json["results"] as $news){ + + if(isset($news["image"])){ + + $thumb = [ + "ratio" => "16:9", + "url" => $news["image"] + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["news"][] = [ + "title" => $news["title"], + "description" => + $this->fuckhtml + ->getTextContent( + $news["excerpt"] + ), + "date" => (int)$news["date"], + "thumb" => $thumb, + "url" => $news["url"] + ]; + } + } + } + + // + // Get related searches + // + $js_tmp = + preg_split( + '/DDG\.duckbar\.loadModule\(\s*\'related_searches\'\s*,\s*/', + $js, + 2 + ); + + if(count($js_tmp) > 1){ + + $json = + json_decode( + $this->fuckhtml + ->extract_json( + $js_tmp[1] + ), + true + ); + + if($json !== null){ + + foreach($json["results"] as $related){ + + $out["related"][] = $related["text"]; + } + } + } + + // + // Get instant answers + // + $js_tmp = + preg_split( + '/DDG\.duckbar\.add\(\s*/', + $html . $js, + 2 + ); + + if(count($js_tmp) > 1){ + + $json = + json_decode( + $this->fuckhtml + ->extract_json( + $js_tmp[1] + ), + true + ); + + if($json !== null){ + + $json = $json["data"]; + $table = []; + $sublinks = []; + $description = []; + + // get official website + if( + isset($json["OfficialWebsite"]) && + $json["OfficialWebsite"] !== null + ){ + + $sublinks["Website"] = $json["OfficialWebsite"]; + } + + // get sublinks & table elements + if(isset($json["Infobox"]["content"])){ + foreach($json["Infobox"]["content"] as $info){ + + if($info["data_type"] == "string"){ + + // add table element + $table[$info["label"]] = $info["value"]; + continue; + } + + if($info["data_type"] == "wd_description"){ + + $description[] = [ + "type" => "quote", + "value" => $info["value"] + ]; + continue; + } + + // add sublink + switch($info["data_type"]){ + + case "official_site": + case "official_website": + $type = "Website"; + break; + + case "wikipedia": $type = "Wikipedia"; break; + case "itunes": $type = "iTunes"; break; + case "amazon": $type = "Amazon"; break; + + case "imdb_title_id": + case "imdb_id": + case "imdb_name_id": + $type = "IMDb"; + $delim = substr($info["value"], 0, 2); + + if($delim == "nm"){ + + $prefix = "https://www.imdb.com/name/"; + }elseif($delim == "tt"){ + + $prefix = "https://www.imdb.com/title/"; + }elseif($delim == "co"){ + + $prefix = "https://www.imdb.com/search/title/?companies="; + }else{ + + $prefix = "https://www.imdb.com/title/"; + } + break; + + case "imdb_name_id": $prefix = "https://www.imdb.com/name/"; $type = "IMDb"; break; + case "twitter_profile": $prefix = "https://twitter.com/"; $type = "Twitter"; break; + case "instagram_profile": $prefix = "https://instagram.com/"; $type = "Instagram"; break; + case "facebook_profile": $prefix = "https://facebook.com/"; $type = "Facebook"; break; + case "spotify_artist_id": $prefix = "https://open.spotify.com/artist/"; $type = "Spotify"; break; + case "itunes_artist_id": $prefix = "https://music.apple.com/us/artist/"; $type = "iTunes"; break; + case "rotten_tomatoes": $prefix = "https://rottentomatoes.com/"; $type = "Rotten Tomatoes"; break; + case "youtube_channel": $prefix = "https://youtube.com/channel/"; $type = "YouTube"; break; + case "soundcloud_id": $prefix = "https://soundcloud.com/"; $type = "SoundCloud"; break; + + default: + $prefix = null; + $type = false; + } + + if($type !== false){ + + if($prefix === null){ + + $sublinks[$type] = $info["value"]; + }else{ + + $sublinks[$type] = $prefix . $info["value"]; + } + } + } + } + + if(isset($json["Abstract"])){ + + $description = $this->parse_rich_text($json["Abstract"]); + } + + if( + !isset($json["Image"]) || + $json["Image"] == "" || + $json["Image"] === null || + $json["Image"] == "https://duckduckgo.com/i/" + ){ + + $image = null; + }else{ + + if( + preg_match( + '/^https?:\/\//', + $json["Image"] + ) + ){ + + $image = $json["Image"]; + }else{ + + $image = "https://duckduckgo.com" . $json["Image"]; + } + } + + $out["answer"][] = [ + "title" => $json["Heading"], + "description" => $description, + "url" => $json["AbstractURL"], + "thumb" => $image, + "table" => $table, + "sublink" => $sublinks + ]; + } + } + + if($get["extendedsearch"] == "no"){ + + return $out; + } + + // + // Parse additional data endpoints + // + //nrj('/js/spice/dictionary/definition/create', null, null, null, null, 'dictionary_definition'); + + preg_match_all( + '/nrj\(\s*\'([^\']+)\'/', + $js, + $nrj + ); + + if(isset($nrj[1])){ + + foreach($nrj[1] as $potential_endpoint){ + + // + // Probe for wordnik definition + // + preg_match( + '/\/js\/spice\/dictionary\/definition\/([^\/]+)/', + $potential_endpoint, + $word + ); + + if(isset($word[1])){ + + $word = $word[1]; + + // found wordnik definition & word + try{ + $nik = + $this->get( + $proxy, + "https://duckduckgo.com/js/spice/dictionary/definition/" . $word, + [], + ddg::req_xhr + ); + + }catch(Exception $e){ + + // fail gracefully + return $out; + } + + // remove javascript + $js_tmp = + preg_split( + '/ddg_spice_dictionary_definition\(\s*/', + $nik, + 2 + ); + + if(count($js_tmp) > 1){ + + $nik = + json_decode( + $this->fuckhtml + ->extract_json( + $js_tmp[1] + ), + true + ); + } + + if($nik === null){ + + return $out; + } + + $answer_cat = []; + $answer = []; + + foreach($nik as $snippet){ + + if(!isset($snippet["partOfSpeech"])){ continue; } + + $push = []; + + // add text snippet + if(isset($snippet["text"])){ + + $push[] = [ + "type" => "text", + "value" => + $this->fuckhtml + ->getTextContent( + $snippet["text"] + ) + ]; + } + + // add example uses + if(isset($snippet["exampleUses"])){ + + foreach($snippet["exampleUses"] as $example){ + + $push[] = [ + "type" => "quote", + "value" => "\"" . + $this->fuckhtml + ->getTextContent( + $example["text"] + ) . "\"" + ]; + } + } + + // add citations + if(isset($snippet["citations"])){ + + foreach($snippet["citations"] as $citation){ + + if(!isset($citation["cite"])){ continue; } + + $text = + $this->fuckhtml + ->getTextContent( + $citation["cite"] + ); + + if(isset($citation["source"])){ + + $text .= + " - " . + $this->fuckhtml + ->getTextContent( + $citation["source"] + ); + } + + $push[] = [ + "type" => "quote", + "value" => $text + ]; + } + } + + // add related words + if(isset($snippet["relatedWords"])){ + + $relations = []; + + foreach($snippet["relatedWords"] as $related){ + + $words = []; + foreach($related["words"] as $wrd){ + + $words[] = + $this->fuckhtml + ->getTextContent( + $wrd + ); + } + + if( + count($words) !== 0 && + isset($related["relationshipType"]) + ){ + + $relations[ucfirst($related["relationshipType"]) . "s"] = + implode(", ", $words); + } + } + + foreach($relations as $relation_title => $relation_content){ + + $push[] = [ + "type" => "quote", + "value" => $relation_title . ": " . $relation_content + ]; + } + } + + + if(count($push) !== 0){ + + // push data to answer_cat + if(!isset($answer_cat[$snippet["partOfSpeech"]])){ + + $answer_cat[$snippet["partOfSpeech"]] = []; + } + + $answer_cat[$snippet["partOfSpeech"]] = + array_merge( + $answer_cat[$snippet["partOfSpeech"]], + $push + ); + } + } + + foreach($answer_cat as $answer_title => $answer_content){ + + $i = 0; + $answer[] = [ + "type" => "title", + "value" => $answer_title + ]; + + $old_type = $answer[count($answer) - 1]["type"]; + + foreach($answer_content as $ans){ + + if( + $ans["type"] == "text" && + $old_type == "text" + ){ + + $i++; + $c = count($answer) - 1; + + // append text to existing textfield + $answer[$c] = [ + "type" => "text", + "value" => $answer[$c]["value"] . "\n" . $i . ". " . $ans["value"] + ]; + + }elseif($ans["type"] == "text"){ + + $i++; + $answer[] = [ + "type" => "text", + "value" => $i . ". " . $ans["value"] + ]; + }else{ + + // append normally + $answer[] = $ans; + } + + $old_type = $ans["type"]; + } + } + + // yeah.. sometimes duckduckgo doesnt give us a definition back + if(count($answer) !== 0){ + + $out["answer"][] = [ + "title" => ucfirst($word), + "description" => $answer, + "url" => "https://www.wordnik.com/words/" . $word, + "thumb" => null, + "table" => [], + "sublink" => [] + ]; + } + } + + // + // Parse stackoverflow answer + // + if( + preg_match( + '/^\/a\.js.*src_id=stack_overflow/', + $potential_endpoint + ) + ){ + + // found stackoverflow answer + try{ + $json = + $this->get( + $proxy, + "https://duckduckgo.com" . $potential_endpoint, + [], + ddg::req_xhr + ); + + }catch(Exception $e){ + + // fail gracefully + return $out; + } + + $json = explode("DDG.duckbar.add_array(", $json, 2); + + if(count($json) === 2){ + + $json = + json_decode( + $this->fuckhtml + ->extract_json( + $json[1] + ), + true + ); + + if( + $json !== null && + isset($json[0]["data"]) + ){ + + $json = $json[0]["data"]; + + foreach($json as $answer){ + + if(isset($answer["Heading"])){ + + $title = $answer["Heading"]; + }elseif(isset($answer["title"])){ + + $title = $answer["title"]; + }else{ + + $title = null; + } + + if( + $title !== null && + isset($answer["Abstract"]) + ){ + + $description = $this->parse_rich_text($answer["Abstract"]); + + $out["answer"][] = [ + "title" => $title, + "description" => $description, + "url" => $answer["AbstractURL"], + "thumb" => null, + "table" => [], + "sublink" => [] + ]; + } + } + } + } + } + } + } + + return $out; + } + + public function image($get){ + + if($get["npt"]){ + + [$js_link, $proxy] = $this->backend->get($get["npt"], "images"); + + }else{ + if(strlen($get["s"]) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + + $filters = []; + + if($get["date"] != "any"){ $filters[] = "time:{$get["date"]}"; } + if($get["size"] != "any"){ $filters[] = "size:{$get["size"]}"; } + if($get["color"] != "any"){ $filters[] = "color:{$get["color"]}"; } + if($get["type"] != "any"){ $filters[] = "type:{$get["type"]}"; } + if($get["layout"] != "any"){ $filters[] = "layout:{$get["layout"]}"; } + if($get["license"] != "any"){ $filters[] = "license:{$get["license"]}"; } + + $filters = implode(",", $filters); + + $get_filters = [ + "q" => $get["s"], + "iax" => "images", + "ia" => "images" + ]; + + if($filters != ""){ + + $get_filters["iaf"] = $filters; + } + + $nsfw = $get["nsfw"] == "yes" ? "-1" : "1"; + $get_filters["kp"] = $nsfw; + + try{ + + $html = $this->get( + $proxy, + "https://duckduckgo.com", + $get_filters, + ddg::req_web + ); + }catch(Exception $err){ + + throw new Exception("Failed to fetch search page"); + } + + preg_match( + '/vqd="([0-9-]+)"/', + $html, + $vqd + ); + + if(!isset($vqd[1])){ + + throw new Exception("Failed to grep VQD token"); + } + + $js_link = + "i.js?" . + http_build_query([ + "l" => $get["country"], + "o" => "json", + "q" => $get["s"], + "vqd" => $vqd[1], + "f" => $filters, + "p" => $nsfw + ]); + } + + try{ + + $json = + $this->get( + $proxy, + "https://duckduckgo.com/" . $js_link, + [], + ddg::req_xhr + ); + }catch(Exception $error){ + + throw new Exception("Failed to get i.js"); + } + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + if(!isset($json["results"])){ + + return $out; + } + + // get npt + if( + isset($json["next"]) && + $json["next"] !== null + ){ + + $vqd = null; + + if(isset($vqd[1])){ + + $vqd = $vqd[1]; + }else{ + + $vqd = array_values($json["vqd"]); + + if(count($vqd) > 0){ + + $vqd = $vqd[0]; + } + } + + if($vqd !== null){ + + $out["npt"] = + $this->backend->store( + $json["next"] . "&vqd=" . $vqd, + "images", + $proxy + ); + } + } + + // get images + foreach($json["results"] as $image){ + + $ratio = + $this->bingratio( + (int)$image["width"], + (int)$image["height"] + ); + + $out["image"][] = [ + "title" => $this->titledots($image["title"]), + "source" => [ + [ + "url" => $image["image"], + "width" => (int)$image["width"], + "height" => (int)$image["height"] + ], + [ + "url" => $this->bingimg($image["thumbnail"]), + "width" => $ratio[0], + "height" => $ratio[1] + ] + ], + "url" => $this->unshiturl($image["url"]) + ]; + } + + return $out; + } + + public function video($get){ + + if($get["npt"]){ + + [$js_link, $proxy] = $this->backend->get($get["npt"], "videos"); + + }else{ + if(strlen($get["s"]) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + + $get_filters = [ + "q" => $get["s"], + "iax" => "videos", + "ia" => "videos" + ]; + + switch($get["nsfw"]){ + + case "yes": $nsfw = "-2"; break; + case "maybe": $nsfw = "-1"; break; + case "no": $nsfw = "1"; break; + } + + $filters = []; + + if($get["date"] != "any"){ $filters[] = "publishedAfter:{$date}"; } + if($get["resolution"] != "any"){ $filters[] = "videoDefinition:{$resolution}"; } + if($get["duration"] != "any"){ $filters[] = "videoDuration:{$duration}"; } + if($get["license"] != "any"){ $filters[] = "videoLicense:{$license}"; } + + $filters = implode(",", $filters); + + if($filters != ""){ + + $get_filters["iaf"] = $filters; + } + + try{ + + $html = + $this->get( + $proxy, + "https://duckduckgo.com/", + $get_filters, + ddg::req_web + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + preg_match( + '/vqd="([0-9-]+)"/', + $html, + $vqd + ); + + if(!isset($vqd[1])){ + + throw new Exception("Failed to grep VQD token"); + } + + $js_link = + "v.js?" . + http_build_query([ + "l" => $get["country"], + "o" => "json", + "sr" => "1", + "q" => $get["s"], + "vqd" => $vqd[1], + "f" => $filters, + "p" => $nsfw + ]); + } + + try{ + + $json = + $this->get( + $proxy, + "https://duckduckgo.com/" . $js_link, + [], + ddg::req_xhr + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + if(!isset($json["results"])){ + + return $out; + } + + // get NPT + if( + isset($json["next"]) && + $json["next"] !== null + ){ + + $out["npt"] = + $this->backend->store( + $json["next"], + "videos", + $proxy + ); + } + + foreach($json["results"] as $video){ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + + foreach(["large", "medium", "small"] as $contender){ + + if(isset($video["images"][$contender])){ + + $thumb = [ + "ratio" => "16:9", + "url" => $this->bingimg($video["images"][$contender]) + ]; + break; + } + } + + $out["video"][] = [ + "title" => $this->titledots($video["title"]), + "description" => $this->titledots($video["description"]), + "author" => [ + "name" => + ( + isset($video["uploader"]) && + $video["uploader"] != "" + ) ? + $video["uploader"] : null, + "url" => null, + "avatar" => null + ], + "date" => + ( + isset($video["published"]) && + $video["published"] != "" + ) ? + strtotime($video["published"]) : null, + "duration" => + ( + isset($video["duration"]) && + $video["duration"] != "" + ) ? + $this->hms2int($video["duration"]) : null, + "views" => + isset($video["statistics"]["viewCount"]) ? + (int)$video["statistics"]["viewCount"] : null, + "thumb" => $thumb, + "url" => $this->unshiturl($video["content"]) + ]; + } + + return $out; + } + + public function news($get){ + + if($get["npt"]){ + + [$js_link, $proxy] = $this->backend->get($get["npt"], "news"); + + }else{ + if(strlen($get["s"]) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + + $get_filters = [ + "q" => $get["s"], + "iar" => "news", + "ia" => "news" + ]; + + if($get["date"] != "any"){ + + $date = $get["date"]; + $get_filters["df"] = $date; + }else{ + + $date = ""; + } + + switch($get["nsfw"]){ + + case "yes": $get_filters["kp"] = "-2"; break; + case "maybe": $get_filters["kp"] = "-1"; break; + case "no": $get_filters["kp"] = "1"; break; + } + + try{ + + $html = + $this->get( + $proxy, + "https://duckduckgo.com/", + $get_filters, + ddg::req_web + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + preg_match( + '/vqd="([0-9-]+)"/', + $html, + $vqd + ); + + if(!isset($vqd[1])){ + + throw new Exception("Failed to grep VQD token"); + } + + $js_link = + "news.js?" . + http_build_query([ + "l" => $get["country"], + "o" => "json", + "noamp" => "1", + "m" => "30", + "q" => $get["s"], + "vqd" => $vqd[1], + "p" => $get_filters["kp"], + "df" => $date, + "u" => "bing" + ]); + } + + try{ + + $json = + $this->get( + $proxy, + "https://duckduckgo.com/" . $js_link, + [], + ddg::req_xhr + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "news" => [] + ]; + + if(!isset($json["results"])){ + + return $out; + } + + // get NPT + if( + isset($json["next"]) && + $json["next"] !== null + ){ + + $out["npt"] = + $this->backend->store( + $json["next"], + "news", + $proxy + ); + } + + foreach($json["results"] as $news){ + + if( + isset($news["image"]) && + $news["image"] != "" + ){ + + $thumb = [ + "ratio" => "16:9", + "url" => $news["image"] + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["news"][] = [ + "title" => $news["title"], + "author" => + ( + isset($news["source"]) && + $news["source"] != "" + ) ? + $news["source"] : null, + "description" => + ( + isset($news["excerpt"]) && + $news["excerpt"] != "" + ) ? + $this->fuckhtml + ->getTextContent( + $news["excerpt"] + ) : null, + "date" => + isset($news["date"]) ? + (int)$news["date"] : null, + "thumb" => $thumb, + "url" => $this->unshiturl($news["url"]) + ]; + } + + return $out; + } + + private function parse_rich_text($html){ + + $description = []; + + // pre-process the html, remove useless elements + $html = + strip_tags( + $html, + [ + "h1", "h2", "h3", "h4", "h5", "h6", "h7", + "pre", "code" + ] + ); + + $html = + preg_replace( + '/<(\/?)pre *[^>]*>\s*<\/?code *[^>]*>/i', + '<$1pre>', + $html + ); + + $this->fuckhtml->load($html); + + $tags = + $this->fuckhtml + ->getElementsByTagName( + "*" + ); + + if(count($tags) === 0){ + + $description[] = [ + "type" => "text", + "value" => + trim( + $this->fuckhtml + ->getTextContent( + $html, + true, + false + ) + ) + ]; + }else{ + + $start = 0; + $was_code_block = true; + foreach($tags as $tag){ + + $text = + $this->fuckhtml + ->getTextContent( + substr( + $html, + $start, + $tag["startPos"] - $start + ), + true, + false + ); + + if($was_code_block){ + + $text = ltrim($text); + $was_code_block = false; + } + + $description[] = [ + "type" => "text", + "value" => $text + ]; + + switch($tag["tagName"]){ + + case "pre": + $append = "code"; + $was_code_block = true; + $c = count($description) - 1; + $description[$c]["value"] = + rtrim($description[$c]["value"]); + break; + + case "code": + $append = "inline_code"; + $c = count($description) - 1; + $description[$c]["value"] = + rtrim($description[$c]["value"]) . " "; + break; + + case "h1": + case "h2": + case "h3": + case "h4": + case "h5": + case "h6": + case "h7": + $append = "title"; + $c = count($description) - 1; + $description[$c]["value"] = + rtrim($description[$c]["value"]); + break; + } + + $description[] = [ + "type" => $append, + "value" => + trim( + $this->fuckhtml + ->getTextContent( + $tag, + true, + false + ) + ) + ]; + + $start = $tag["endPos"]; + } + + // shit out remainder + $description[] = [ + "type" => "text", + "value" => + trim( + $this->fuckhtml + ->getTextContent( + substr( + $html, + $start + ), + true, + false + ) + ) + ]; + } + + return $description; + } + + private function titledots($title){ + + $substr = substr($title, -3); + + if( + $substr == "..." || + $substr == "…" + ){ + + return trim(substr($title, 0, -3)); + } + + return trim($title); + } + + private function hms2int($time){ + + $parts = explode(":", $time, 3); + $time = 0; + + if(count($parts) === 3){ + + // hours + $time = $time + ((int)$parts[0] * 3600); + array_shift($parts); + } + + if(count($parts) === 2){ + + // minutes + $time = $time + ((int)$parts[0] * 60); + array_shift($parts); + } + + // seconds + $time = $time + (int)$parts[0]; + + return $time; + } + + + private function unshiturl($url){ + + // check for domains w/out first short subdomain (ex: www.) + + $domain = parse_url($url, PHP_URL_HOST); + + $subdomain = preg_replace( + '/^[A-z0-9]{1,3}\./', + "", + $domain + ); + + switch($subdomain){ + case "ebay.com.au": + case "ebay.at": + case "ebay.ca": + case "ebay.fr": + case "ebay.de": + case "ebay.com.hk": + case "ebay.ie": + case "ebay.it": + case "ebay.com.my": + case "ebay.nl": + case "ebay.ph": + case "ebay.pl": + case "ebay.com.sg": + case "ebay.es": + case "ebay.ch": + case "ebay.co.uk": + case "cafr.ebay.ca": + case "ebay.com": + case "community.ebay.com": + case "pages.ebay.com": + + // remove ebay tracking elements + $old_params = parse_url($url, PHP_URL_QUERY); + parse_str($old_params, $params); + + if(isset($params["mkevt"])){ unset($params["mkevt"]); } + if(isset($params["mkcid"])){ unset($params["mkcid"]); } + if(isset($params["mkrid"])){ unset($params["mkrid"]); } + if(isset($params["campid"])){ unset($params["campid"]); } + if(isset($params["customid"])){ unset($params["customid"]); } + if(isset($params["toolid"])){ unset($params["toolid"]); } + if(isset($params["_sop"])){ unset($params["_sop"]); } + if(isset($params["_dcat"])){ unset($params["_dcat"]); } + if(isset($params["epid"])){ unset($params["epid"]); } + if(isset($params["epid"])){ unset($params["oid"]); } + + $params = http_build_query($params); + + if(strlen($params) === 0){ + $replace = "\?"; + }else{ + $replace = ""; + } + + $url = preg_replace( + "/" . $replace . preg_quote($old_params, "/") . "$/", + $params, + $url + ); + break; + } + + return $url; + } + + private function bingimg($url){ + + $image = parse_url($url); + + $id = null; + if(isset($image["query"])){ + + parse_str($image["query"], $str); + + if(isset($str["id"])){ + + $id = $str["id"]; + } + } + + if($id === null){ + + $id = explode("/th/id/", $image["path"], 2); + + if(count($id) !== 2){ + + // malformed + return $url; + } + + $id = $id[1]; + } + + return "https://" . $image["host"] . "/th?id=" . rawurlencode($id); + } + + private function bingratio($width, $height){ + + $ratio = [ + 474 / $width, + 474 / $height + ]; + + if($ratio[0] < $ratio[1]){ + + $ratio = $ratio[0]; + }else{ + + $ratio = $ratio[1]; + } + + return [ + floor($width * $ratio), + floor($height * $ratio) + ]; + } +} diff --git a/scraper/facebook.php b/scraper/facebook.php new file mode 100644 index 0000000..395a863 --- /dev/null +++ b/scraper/facebook.php @@ -0,0 +1,820 @@ +<?php + +class facebook{ + + const get = 0; + const post = 1; + + public function __construct(){ + + include "lib/nextpage.php"; + $this->nextpage = new nextpage("fb"); + + include "lib/proxy_pool.php"; + $this->proxy = new proxy_pool("facebook"); + } + + public function getfilters($page){ + + return [ + "sort" => [ + "display" => "Sort by", + "option" => [ + "relevance" => "Relevance", + "most_recent" => "Most recent" + ] + ], + "newer" => [ + "display" => "Newer than", + "option" => "_DATE" + ], + "older" => [ + "display" => "Older than", + "option" => "_DATE" + ], + "live" => [ + "display" => "Livestream", + "option" => [ + "no" => "No", + "yes" => "Yes" + ] + ] + ]; + } + + private function get($url, $get = [], $reqtype = self::get){ + + $curlproc = curl_init(); + + if($get !== []){ + + $get = http_build_query($get); + + if($reqtype === self::get){ + + $headers = [ + "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:115.0) Gecko/20100101 Firefox/115.0", + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1" + ]; + + $url .= "?" . $get; + }else{ + + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + $headers = [ + "User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:115.0) Gecko/20100101 Firefox/115.0", + "Accept: */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br", + "Content-Type: application/x-www-form-urlencoded", + "X-FB-Friendly-Name: SearchCometResultsPaginatedResultsQuery", + //"X-FB-LSD: AVptQC4a16c", + //"X-ASBD-ID: 129477", + "Content-Length: " . strlen($get), + "Origin: https://www.facebook.com", + "DNT: 1", + "Connection: keep-alive", + "Referer: https://www.facebook.com/watch/", + "Cookie: datr=__GMZCgwVF5BbyvAtfJojQwg; oo=v1%7C3%3A1691641171; wd=955x995", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-origin", + "TE: trailers" + ]; + + curl_setopt($curlproc, CURLOPT_POST, true); + curl_setopt($curlproc, CURLOPT_POSTFIELDS, $get); + } + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->proxy->assign_proxy($curlproc); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function video($get){ + + $search = $get["s"]; + $npt = $get["npt"]; + + $this->out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + if($get["npt"]){ + + $nextpage = + json_decode( + $this->nextpage->get( + $npt, + "videos" + ), + true + ); + + // parse next page + $this->video_nextpage($nextpage); + + return $this->out; + } + + // generate filter data + // { + // "rp_creation_time:0":"{\"name\":\"creation_time\",\"args\":\"{\\\"start_year\\\":\\\"2023\\\",\\\"start_month\\\":\\\"2023-08\\\",\\\"end_year\\\":\\\"2023\\\",\\\"end_month\\\":\\\"2023-08\\\",\\\"start_day\\\":\\\"2023-08-10\\\",\\\"end_day\\\":\\\"2023-08-10\\\"}\"}", + // "videos_sort_by:0":"{\"name\":\"videos_sort_by\",\"args\":\"Most Recent\"}", + // "videos_live:0":"{\"name\":\"videos_live\",\"args\":\"\"}" + // } + $filter = []; + $sort = $get["sort"]; + $live = $get["live"]; + $older = $get["older"]; + $newer = $get["newer"]; + + if( + $older !== false || + $newer !== false + ){ + + if($older === false){ + + $older = time(); + } + + if($newer === false){ + + $newer = 0; + } + + $filter["rp_creation_time:0"] = + json_encode( + [ + "name" => "creation_time", + "args" => + json_encode( + [ + "start_year" => date("Y", $newer), + "start_month" => date("Y-m", $newer), + "end_year" => date("Y", $older), + "end_month" => date("Y-m", $older), + "start_day" => date("Y-m-d", $newer), + "end_day" => date("Y-m-d", $older) + ] + ) + ] + ); + } + + if($sort != "relevance"){ + + $filter["videos_sort_by:0"] = + json_encode( + [ + "name" => "videos_sort_by", + "args" => "Most Recent" + ] + ); + } + + if($live != "no"){ + + $filter["videos_live:0"] = json_encode( + [ + "name" => "videos_live", + "args" => "" + ] + ); + } + + $req = [ + "q" => $search + ]; + + if(count($filter) !== 0){ + + $req["filters"] = + base64_encode( + json_encode( + $filter + ) + ); + } + /* + $html = + $this->get( + "https://www.facebook.com/watch/search/", + $req + );*/ + + $handle = fopen("scraper/facebook.html", "r"); + $html = fread($handle, filesize("scraper/facebook.html")); + fclose($handle); + + preg_match_all( + '/({"__bbox":.*,"sequence_number":0}})\]\]/', + $html, + $json + ); + + if(!isset($json[1][1])){ + + throw new Exception("Could not grep JSON body"); + } + + $json = json_decode($json[1][1], true); + + foreach( + $json + ["__bbox"] + ["result"] + ["data"] + ["serpResponse"] + ["results"] + ["edges"] + as $result + ){ + + $this->parse_edge($result); + } + + // get nextpage data + if( + $json + ["__bbox"] + ["result"] + ["data"] + ["serpResponse"] + ["results"] + ["page_info"] + ["has_next_page"] + == 1 + ){ + + preg_match( + '/handleWithCustomApplyEach\(ScheduledApplyEach,({.*})\);}\);}\);<\/script>/', + $html, + $nextpagedata + ); + + // [POST] https://www.facebook.com/api/graphql/ + // FORM data, not JSON! + + $nextpage = [ + "av" => "0", + "__user" => null, + "__a" => null, + "__req" => "2", + "__hs" => null, + "dpr" => "1", + "__ccg" => null, + "__rev" => null, + // another client side token + "__s" => $this->randomstring(6) . ":" . $this->randomstring(6) . ":" . $this->randomstring(6), + "__hsi" => null, + // tracking fingerprint (probably generated using webgl) + "__dyn" => "7xeUmwlE7ibwKBWo2vwAxu13w8CewSwMwNw9G2S0im3y4o0B-q1ew65xO2O1Vw8G1Qw5Mx61vw9m1YwBgao6C0Mo5W3S7Udo5q4U2zxe2Gew9O222SUbEaU2eU5O0GpovU19pobodEGdw46wbS1LwTwNwLw8O1pwr86C16w", + "__csr" => $this->randomstring(null), + "__comet_req" => null, + "lsd" => null, + "jazoest" => null, + "__spin_r" => null, + "__spin_b" => null, + "__spin_t" => null, + "fb_api_caller_class" => "RelayModern", + "fb_api_req_friendly_name" => "SearchCometResultsPaginatedResultsQuery", + "variables" => [ // this is json + "UFI2CommentsProvider_commentsKey" => "SearchCometResultsInitialResultsQuery", + "allow_streaming" => false, + "args" => [ + "callsite" => "comet:watch_search", + "config" => [ + "exact_match" => false, + "high_confidence_config" => null, + "intercept_config" => null, + "sts_disambiguation" => null, + "watch_config" => null + ], + "context" => [ + "bsid" => null, + "tsid" => null + ], + "experience" => [ + "encoded_server_defined_params" => null, + "fbid" => null, + "type" => "WATCH_TAB_GLOBAL" + ], + "filters" => [], + "text" => $search + ], + "count" => 5, + "cursor" => + $json + ["__bbox"] + ["result"] + ["data"] + ["serpResponse"] + ["results"] + ["page_info"] + ["end_cursor"], + "displayCommentsContextEnableComment" => false, + "displayCommentsContextIsAdPreview" => false, + "displayCommentsContextIsAggregatedShare" => false, + "displayCommentsContextIsStorySet" => false, + "displayCommentsFeedbackContext" => null, + "feedLocation" => "SEARCH", + "feedbackSource" => 23, + "fetch_filters" => true, + "focusCommentID" => null, + "locale" => null, + "privacySelectorRenderLocation" => "COMET_STREAM", + "renderLocation" => "search_results_page", + "scale" => 1, + "stream_initial_count" => 0, + "useDefaultActor" => false, + "__relay_internal__pv__IsWorkUserrelayprovider" => false, + "__relay_internal__pv__IsMergQAPollsrelayprovider" => false, + "__relay_internal__pv__StoriesArmadilloReplyEnabledrelayprovider" => false, + "__relay_internal__pv__StoriesRingrelayprovider" => false + ], + "server_timestamps" => "true", + "doc_id" => "6761275837251607" // is actually dynamic + ]; + + // append filters to nextpage + foreach($filter as $key => $value){ + + $nextpage["variables"]["args"]["filters"][] = + $value; + } + + $nextpagedata = json_decode($nextpagedata[1], true); + + // get bsid + foreach($nextpagedata["require"] as $key){ + + foreach($key as $innerkey){ + + if(is_array($innerkey)){ + foreach($innerkey as $inner_innerkey){ + + if(is_array($inner_innerkey)){ + foreach($inner_innerkey as $inner_inner_innerkey){ + + if( + isset( + $inner_inner_innerkey + ["variables"] + ["args"] + ["context"] + ["bsid"] + ) + ){ + + $nextpage + ["variables"] + ["args"] + ["context"] + ["bsid"] = + $inner_inner_innerkey + ["variables"] + ["args"] + ["context"] + ["bsid"]; + } + } + } + } + } + } + } + + foreach($nextpagedata["define"] as $key){ + + if(isset($key[2]["haste_session"])){ + + $nextpage["__hs"] = $key[2]["haste_session"]; + } + + if(isset($key[2]["connectionClass"])){ + + $nextpage["__ccg"] = $key[2]["connectionClass"]; + } + + if(isset($key[2]["__spin_r"])){ + + $nextpage["__spin_r"] = (string)$key[2]["__spin_r"]; + } + + if(isset($key[2]["hsi"])){ + + $nextpage["__hsi"] = (string)$key[2]["hsi"]; + } + + if( + isset($key[2]["token"]) && + !empty($key[2]["token"]) + ){ + + $nextpage["lsd"] = $key[2]["token"]; + } + + if(isset($key[2]["__spin_r"])){ + + $nextpage["__spin_r"] = (string)$key[2]["__spin_r"]; + $nextpage["__rev"] = $nextpage["__spin_r"]; + } + + if(isset($key[2]["__spin_b"])){ + + $nextpage["__spin_b"] = $key[2]["__spin_b"]; + } + + if(isset($key[2]["__spin_t"])){ + + $nextpage["__spin_t"] = (string)$key[2]["__spin_t"]; + } + } + + preg_match( + '/{"u":"\\\\\/ajax\\\\\/qm\\\\\/\?__a=([0-9]+)&__user=([0-9]+)&__comet_req=([0-9]+)&jazoest=([0-9]+)"/', + $html, + $ajaxparams + ); + + if(count($ajaxparams) !== 5){ + + throw new Exception("Could not grep the AJAX parameters"); + } + + $nextpage["__a"] = $ajaxparams[1]; + $nextpage["__user"] = $ajaxparams[2]; + $nextpage["__comet_req"] = $ajaxparams[3]; + $nextpage["jazoest"] = $ajaxparams[4]; + + /* + $handle = fopen("scraper/facebook-nextpage.json", "r"); + $json = fread($handle, filesize("scraper/facebook-nextpage.json")); + fclose($handle);*/ + + $nextpage["variables"] = json_encode($nextpage["variables"]); + + $this->video_nextpage($nextpage); + } + + return $this->out; + } + + private function video_nextpage($nextpage, $getcursor = false){ + + $json = + $this->get( + "https://www.facebook.com/api/graphql/", + $nextpage, + self::post + ); + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to decode next page JSON"); + } + + foreach( + $json + ["data"] + ["serpResponse"] + ["results"] + ["edges"] + as $result + ){ + + $this->parse_edge($result); + } + + if( + $json + ["data"] + ["serpResponse"] + ["results"] + ["page_info"] + ["has_next_page"] == 1 + ){ + + $nextpage["variables"] = json_decode($nextpage["variables"], true); + + $nextpage["variables"]["cursor"] = + $json + ["data"] + ["serpResponse"] + ["results"] + ["page_info"] + ["end_cursor"]; + + $nextpage["variables"] = json_encode($nextpage["variables"]); + + //change this for second call. after, it's static. + // TODO: csr also updates to longer string + $nextpage["__dyn"] = "7xeUmwlEnwn8K2WnFw9-2i5U4e0yoW3q322aew9G2S0zU20xi3y4o0B-q1ew65xOfxO1Vw8G11xmfz81s8hwGwQw9m1YwBgao6C2O0B85W3S7Udo5qfK0EUjwGzE2swwwJK2W2K0zK5o4q0GpovU19pobodEGdw46wbS1LwTwNwLw8O1pwr86C16w"; + + // TODO: change this on third and 6th call + //$nextpage["__s"] = $this->randomstring(6) . ":" . explode(":", $nextpage["__s"], 2)[1]; + + $this->out["npt"] = $this->nextpage->store(json_encode($nextpage), "videos"); + } + } + + private function parse_edge($edge){ + + $append = "video"; + $edge = + $edge + ["relay_rendering_strategy"] + ["view_model"]; + + if( + strtolower( + $edge + ["video_metadata_model"] + ["video_broadcast_status"] + ) + == "live" + ){ + + // handle livestream + $duration = "_LIVE"; + $append = "livestream"; + $timetext = null; + $views = + (int)$edge + ["video_metadata_model"] + ["relative_time_string"]; + + $url_prefix = "https://www.facebook.com/watch/live/?v="; + + }elseif( + stripos( + $edge + ["video_metadata_model"] + ["video_broadcast_status"], + "vod" + ) !== false + ){ + + // handle VOD format + $timetext = null; + $views = + (int)$edge + ["video_metadata_model"] + ["relative_time_string"]; + + $duration = + $this->hms2int( + $edge + ["video_thumbnail_model"] + ["video_duration_text"] + ); + + $url_prefix = "https://www.facebook.com/watch/live/?v="; + + }else{ + + // handle normal format + $timetext = + explode( + " · ", + $edge + ["video_metadata_model"] + ["relative_time_string"], + 2 + ); + + if(count($timetext) === 2){ + + $views = $this->truncatedcount2int($timetext[1]); + }else{ + + $views = null; + } + + $timetext = strtotime($timetext[0]); + + $duration = + $this->hms2int( + $edge + ["video_thumbnail_model"] + ["video_duration_text"] + ); + + $url_prefix = "https://www.facebook.com/watch/?v="; + } + + if( + isset( + $edge + ["video_metadata_model"] + ["video_owner_profile"] + ["uri_token"] + ) + ){ + + $profileurl = + "https://www.facebook.com/watch/" . + $edge + ["video_metadata_model"] + ["video_owner_profile"] + ["uri_token"]; + }else{ + + $profileurl = + $edge + ["video_metadata_model"] + ["video_owner_profile"] + ["url"]; + } + + $this->out[$append][] = [ + "title" => + $this->limitstrlen( + str_replace( + "\n", + " ", + $edge + ["video_metadata_model"] + ["title"] + ), + 100 + ), + "description" => + empty( + $edge + ["video_metadata_model"] + ["save_description"] + ) ? + null : + str_replace( + "\n", + " ", + $this->limitstrlen( + $edge + ["video_metadata_model"] + ["save_description"] + ) + ), + "author" => [ + "name" => + $edge + ["video_metadata_model"] + ["video_owner_profile"] + ["name"], + "url" => $profileurl, + "avatar" => null + ], + "date" => $timetext, + "duration" => $duration, + "views" => $views, + "thumb" => + [ + "url" => + $edge + ["video_thumbnail_model"] + ["thumbnail_image"] + ["uri"], + "ratio" => "16:9" + ], + "url" => + $url_prefix . + $edge + ["video_click_model"] + ["click_metadata_model"] + ["video_id"] + ]; + } + + private function randomstring($len){ + + if($len === null){ + + $str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789-"; + $len = rand(141, 145); + $c = 61; + }else{ + + $str = "abcdefghijklmnopqrstuvwxyz123456789"; + $c = 34; + } + + $out = null; + for($i=0; $i<$len; $i++){ + + $out .= $str[rand(0, $c)]; + } + + return $out; + } + + private function limitstrlen($text, $len = 300){ + + return explode("\n", wordwrap($text, $len, "\n"))[0]; + } + + private function hms2int($time){ + + $parts = explode(":", $time, 3); + $time = 0; + + if(count($parts) === 3){ + + // hours + $time = $time + ((int)$parts[0] * 3600); + array_shift($parts); + } + + if(count($parts) === 2){ + + // minutes + $time = $time + ((int)$parts[0] * 60); + array_shift($parts); + } + + // seconds + $time = $time + (int)$parts[0]; + + return $time; + } + + private function truncatedcount2int($number){ + + // decimal should always be 1 number long + $number = explode(" ", $number, 2); + $number = $number[0]; + + $unit = strtolower($number[strlen($number) - 1]); + + $tmp = explode(".", $number, 2); + $number = (int)$number; + + if(count($tmp) === 2){ + + $decimal = (int)$tmp[1]; + }else{ + + $decimal = 0; + } + + switch($unit){ + + case "k": + $exponant = 1000; + break; + + case "m": + $exponant = 1000000; + break; + + case "b"; + $exponant = 1000000000; + break; + + default: + $exponant = 1; + break; + } + + return ($number * $exponant) + ($decimal * ($exponant / 10)); + } +} diff --git a/scraper/fivehpx.php b/scraper/fivehpx.php new file mode 100644 index 0000000..8a600df --- /dev/null +++ b/scraper/fivehpx.php @@ -0,0 +1,262 @@ +<?php + +class fivehpx{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("fivehpx"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + return [ + "sort" => [ + "display" => "Sort", + "option" => [ + "relevance" => "Relevance", + "pulse" => "Pulse", + "newest" => "Newest" + ] + ] + ]; + } + + private function get($proxy, $url, $get = [], $post_data = null){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + if($post_data === null){ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: same-origin", + "Sec-Fetch-User: ?1", + "Priority: u=0, i", + "TE: trailers"] + ); + }else{ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Referer: https://500px.com/", + "content-type: application/json", + //"x-csrf-token: undefined", + "x-500px-source: Search", + "Content-Length: " . strlen($post_data), + "Origin: https://500px.com", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + // "Cookie: _pin_unauth, _fbp, _sharedID, _sharedID_cst", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-site", + "Priority: u=4", + "TE: trailers"] + ); + + // set post data + curl_setopt($curlproc, CURLOPT_POST, true); + curl_setopt($curlproc, CURLOPT_POSTFIELDS, $post_data); + } + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + // http2 bypass + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function image($get){ + + if($get["npt"]){ + + [$pagination, $proxy] = + $this->backend->get( + $get["npt"], "images" + ); + + $pagination = json_decode($pagination, true); + $search = $pagination["search"]; + + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + $pagination = [ + "sort" => strtoupper($get["sort"]), + "search" => $search, + "filters" => [], + "nlp" => false, + ]; + } + + try{ + + $json = + $this->get( + $proxy, + "https://api.500px.com/graphql", + [], + json_encode([ + "operationName" => "PhotoSearchPaginationContainerQuery", + "variables" => $pagination, + "query" => + 'query PhotoSearchPaginationContainerQuery(' . + (isset($pagination["cursor"]) ? '$cursor: String, ' : "") . + '$sort: PhotoSort, $search: String!, $filters: [PhotoSearchFilter!], $nlp: Boolean) { ...PhotoSearchPaginationContainer_query_1vzAZD} fragment PhotoSearchPaginationContainer_query_1vzAZD on Query { photoSearch(sort: $sort, first: 100, ' . + (isset($pagination["cursor"]) ? 'after: $cursor, ' : "") . + 'search: $search, filters: $filters, nlp: $nlp) { edges { node { id legacyId canonicalPath name description width height images(sizes: [33, 36]) { size url id } } } totalCount pageInfo { endCursor hasNextPage } }}' + ]) + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch graphQL object"); + } + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to decode graphQL object"); + } + + if(isset($json["errors"][0]["message"])){ + + throw new Exception("500px returned an API error: " . $json["errors"][0]["message"]); + } + + if(!isset($json["data"]["photoSearch"]["edges"])){ + + throw new Exception("No edges returned by API"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + foreach($json["data"]["photoSearch"]["edges"] as $image){ + + $image = $image["node"]; + $title = + trim( + $this->fuckhtml + ->getTextContent( + $image["name"] + ) . ": " . + $this->fuckhtml + ->getTextContent( + $image["description"] + ) + , " :" + ); + + $small = $this->image_ratio(600, $image["width"], $image["height"]); + $large = $this->image_ratio(2048, $image["width"], $image["height"]); + + $out["image"][] = [ + "title" => $title, + "source" => [ + [ + "url" => $image["images"][1]["url"], + "width" => $large[0], + "height" => $large[1] + ], + [ + "url" => $image["images"][0]["url"], + "width" => $small[0], + "height" => $small[1] + ] + ], + "url" => "https://500px.com" . $image["canonicalPath"] + ]; + } + + // get NPT token + if($json["data"]["photoSearch"]["pageInfo"]["hasNextPage"] === true){ + + $out["npt"] = + $this->backend->store( + json_encode([ + "cursor" => $json["data"]["photoSearch"]["pageInfo"]["endCursor"], + "search" => $search, + "sort" => $pagination["sort"], + "filters" => [], + "nlp" => false + ]), + "images", + $proxy + ); + } + + return $out; + } + + private function image_ratio($longest_edge, $width, $height){ + + $ratio = [ + $longest_edge / $width, + $longest_edge / $height + ]; + + if($ratio[0] < $ratio[1]){ + + $ratio = $ratio[0]; + }else{ + + $ratio = $ratio[1]; + } + + return [ + floor($width * $ratio), + floor($height * $ratio) + ]; + } +} diff --git a/scraper/flickr.php b/scraper/flickr.php new file mode 100644 index 0000000..71656ee --- /dev/null +++ b/scraper/flickr.php @@ -0,0 +1,415 @@ +<?php + +class flickr{ + + const req_web = 0; + const req_xhr = 1; + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("flickr"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + return [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "maybe" => "Maybe", + "no" => "No", + ] + ], + "sort" => [ + "display" => "Sort by", + "option" => [ + "relevance" => "Relevance", + "date-posted-desc" => "Newest uploads", + "date-posted-asc" => "Oldest uploads", + "date-taken-desc" => "Newest taken", + "date-taken-asc" => "Oldest taken", + "interestingness-desc" => "Interesting" + ] + ], + "color" => [ + "display" => "Color", + "option" => [ + "any" => "Any color", + // color_codes= + "0" => "Red", + "1" => "Brown", + "2" => "Orange", + "b" => "Pink", + "4" => "Yellow", + "3" => "Golden", + "5" => "Lime", + "6" => "Green", + "7" => "Sky blue", + "8" => "Blue", + "9" => "Purple", + "a" => "Hot pink", + "c" => "White", + "d" => "Gray", + "e" => "Black", + // styles= override + "blackandwhite" => "Black & white", + ] + ], + "style" => [ // styles= + "display" => "Style", + "option" => [ + "any" => "Any style", + "depthoffield" => "Depth of field", + "minimalism" => "Minimalism", + "pattern" => "Patterns" + ] + ], + "license" => [ + "display" => "License", + "option" => [ + "any" => "Any license", + "1,2,3,4,5,6,9,11,12,13,14,15,16" => "All creative commons", + "4,5,6,9,10,11,12,13" => "Commercial use allowed", + "1,2,4,5,9,10,11,12,14,15" => "Modifications allowed", + "4,5,9,10,11,12" => "Commercial use & mods allowed", + "7,9,10" => "No known copyright restrictions", + "8" => "U.S Government works" + ] + ] + ]; + } + + private function get($proxy, $url, $get = [], $reqtype){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + if($reqtype === flickr::req_web){ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: same-origin", + "Sec-Fetch-User: ?1", + "Priority: u=0, i", + "TE: trailers"] + ); + }else{ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Origin: https://www.flickr.com", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Referer: https://www.flickr.com/", + // Cookie: + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-site", + "TE: trailers"] + ); + } + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + // http2 bypass + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function image($get){ + + if($get["npt"]){ + + [$filters, $proxy] = + $this->backend->get( + $get["npt"], "images" + ); + + $filters = json_decode($filters, true); + + // Workaround for the future, if flickr deprecates &page argument on html page + /* + try{ + + $json = + $this->get( + $proxy, + "https://api.flickr.com/services/rest", + [ + "sort" => $data["sort"], + "parse_tags" => 1, + // url_s,url_n,url_w,url_m,url_z,url_c,url_l,url_h,url_k,url_3k,url_4k,url_5k,url_6k,url_o + "extras" => "can_comment,can_print,count_comments,count_faves,description,isfavorite,license,media,needs_interstitial,owner_name,path_alias,realname,rotation,url_sq,url_q,url_t,url_s,url_n,url_w,url_m,url_z,url_c,url_l", + "per_page" => 100, + "page" => $data["page"], + "lang" => "en-US", + "text" => $data["search"], + "viewerNSID" => "", + "method" => "flickr.photos.search", + "csrf" => "", + "api_key" => $data["api_key"], + "format" => "json", + "hermes" => 1, + "hermesClient" => 1, + "reqId" => $data["reqId"], + "nojsoncallback" => 1 + ] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + }*/ + + }else{ + + if(strlen($get["s"]) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + + // compute filters + $filters = [ + "page" => 1, + "sort" => $get["sort"] + ]; + + if($get["style"] != "any"){ + + $filters["styles"] = $get["style"]; + } + + if($get["color"] != "any"){ + + if($get["color"] != "blackandwhite"){ + + $filters["color_codes"] = $get["color"]; + }else{ + + $filters["styles"] = "blackandwhite"; + } + } + + if($get["license"] != "any"){ + + $filters["license"] = $get["license"]; + } + + switch($get["nsfw"]){ + + case "yes": $filters["safe_search"] = 0; break; + case "maybe": $filters["safe_search"] = 2; break; + case "no": $filters["safe_search"] = 1; break; + } + } + + $get_params = [ + "text" => $get["s"], + "per_page" => 50, + // scrape highest resolution + "extras" => "url_s,url_n,url_w,url_m,url_z,url_c,url_l,url_h,url_k,url_3k,url_4k,url_5k,url_6k,url_o", + "view_all" => 1 + ]; + + $get_params = array_merge($get_params, $filters); + + $html = + $this->get( + $proxy, + "https://www.flickr.com/search/", + $get_params, + flickr::req_web + ); + + // @TODO + // get api_key and reqId, if flickr deprecates &page + + $this->fuckhtml->load($html); + + // + // get response JSON + // + $scripts = + $this->fuckhtml + ->getElementsByClassName( + "modelExport", + "script" + ); + + $found = false; + foreach($scripts as $script){ + + $json = + preg_split( + '/modelExport: ?/', + $script["innerHTML"], + 2 + ); + + if(count($json) !== 0){ + + $found = true; + $json = $json[1]; + break; + } + } + + if($found === false){ + + throw new Exception("Failed to grep JSON"); + } + + $json = + json_decode( + $this->fuckhtml + ->extract_json( + $json + ), + true + ); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + if(!isset($json["main"]["search-photos-lite-models"][0]["data"]["photos"]["data"]["_data"])){ + + throw new Exception("Failed to access data object"); + } + + foreach($json["main"]["search-photos-lite-models"][0]["data"]["photos"]["data"]["_data"] as $image){ + + if(!isset($image["data"])){ + + // flickr likes to gives us empty array objects + continue; + } + + $image = $image["data"]; + + $title = []; + + if(isset($image["title"])){ + + $title[] = + $this->fuckhtml + ->getTextContent( + $image["title"] + ); + } + + if(isset($image["description"])){ + + $title[] = + $this->fuckhtml + ->getTextContent( + str_replace( + "\n", + " ", + $image["description"] + ) + ); + } + + $title = implode(": ", $title); + + $sources = array_values($image["sizes"]["data"]); + + $suitable_sizes = ["n", "m", "w", "s"]; + + $thumb = &$sources[0]["data"]; + foreach($suitable_sizes as $testing_size){ + + if(isset($image["sizes"]["data"][$testing_size])){ + + $thumb = &$image["sizes"]["data"][$testing_size]["data"]; + break; + } + } + + $og = &$sources[count($sources) - 1]["data"]; + + $out["image"][] = [ + "title" => $title, + "source" => [ + [ + "url" => "https:" . $og["displayUrl"], + "width" => (int)$og["width"], + "height" => (int)$og["height"] + ], + [ + "url" => "https:" . $thumb["displayUrl"], + "width" => (int)$thumb["width"], + "height" => (int)$thumb["height"] + ] + ], + "url" => "https://www.flickr.com/photos/" . $image["ownerNsid"] . "/" . $image["id"] . "/" + ]; + } + + $total_items = (int)$json["main"]["search-photos-lite-models"][0]["data"]["photos"]["data"]["totalItems"]; + + if(($filters["page"]) * 50 < $total_items){ + + $filters["page"]++; + + $out["npt"] = + $this->backend->store( + json_encode($filters), + "images", + $proxy + ); + } + + return $out; + } +} diff --git a/scraper/ftm.php b/scraper/ftm.php new file mode 100644 index 0000000..470c13e --- /dev/null +++ b/scraper/ftm.php @@ -0,0 +1,161 @@ +<?php + +class ftm{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("ftm"); + } + + public function getfilters($page){ + + return []; + } + + private function get($proxy, $url, $search, $offset){ + + $curlproc = curl_init(); + + curl_setopt($curlproc, CURLOPT_URL, $url); + + $payload = + json_encode( + [ + "search" => $search, + "offset" => $offset + ] + ); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Content-Length: " . strlen($payload), + "Content-Type: application/json", + "DNT: 1", + "Connection: keep-alive", + "Origin: https://findthatmeme.com", + "Referer: https://findthatmeme.com/?search=" . urlencode($search), + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1", + "X-Auth-Key: undefined", + "X-CSRF-Validation-Header: true"] + ); + + curl_setopt($curlproc, CURLOPT_POST, true); + curl_setopt($curlproc, CURLOPT_POSTFIELDS, $payload); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function image($get){ + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + if($get["npt"]){ + + [$data, $proxy] = $this->backend->get($get["npt"], "images"); + $data = json_decode($data, true); + + $count = $data["count"]; + $search = $data["search"]; + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $count = 0; + $proxy = $this->backend->get_ip(); + } + + try{ + $json = + json_decode( + $this->get( + $proxy, + "https://findthatmeme.com/api/v1/search", + $search, + $count + ), + true + ); + + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + foreach($json as $item){ + + $count++; + + if($item["type"] == "VIDEO"){ + + $thumb = "thumb/" . $item["thumbnail"]; + }else{ + + $thumb = $item["image_path"]; + } + + $out["image"][] = [ + "title" => date("jS \of F Y @ g:ia", strtotime($item["created_at"])), + "source" => [ + [ + "url" => + "https://s3.thehackerblog.com/findthatmeme/" . + $thumb, + "width" => null, + "height" => null + ] + ], + "url" => $item["source_page_url"] + ]; + } + + $out["npt"] = + $this->backend->store( + json_encode([ + "count" => $count, + "search" => $search + ]), + "images", + $proxy + ); + + return $out; + } +} diff --git a/scraper/ghostery.php b/scraper/ghostery.php new file mode 100644 index 0000000..394756e --- /dev/null +++ b/scraper/ghostery.php @@ -0,0 +1,320 @@ +<?php + +class ghostery{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("ghostery"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + if($page != "web"){ + + return []; + } + + return [ + "country" => [ + "display" => "Country", + "option" => [ + "any" => "All regions", + "AR" => "Argentina", + "AU" => "Australia", + "AT" => "Austria", + "BE" => "Belgium", + "BR" => "Brazil", + "CA" => "Canada", + "CL" => "Chile", + "DK" => "Denmark", + "FI" => "Finland", + "FR" => "France", + "DE" => "Germany", + "HK" => "Hong Kong", + "IN" => "India", + "ID" => "Indonesia", + "IT" => "Italy", + "JP" => "Japan", + "KR" => "Korea", + "MY" => "Malaysia", + "MX" => "Mexico", + "NL" => "Netherlands", + "NZ" => "New Zealand", + "NO" => "Norway", + "CN" => "People's Republic of China", + "PL" => "Poland", + "PT" => "Portugal", + "PH" => "Republic of the Philippines", + "RU" => "Russia", + "SA" => "Saudi Arabia", + "ZA" => "South Africa", + "ES" => "Spain", + "SE" => "Sweden", + "CH" => "Switzerland", + "TW" => "Taiwan", + "TR" => "Turkey", + "GB" => "United Kingdom", + "US" => "United States" + ] + ] + ]; + } + + private function get($proxy, $url, $get = [], $country){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Referer: https://ghosterysearch.com", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Cookie: ctry=" . ($country == "any" ? "--" : $country) . "; noads=true", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: same-origin", + "Sec-Fetch-User: ?1", + "Priority: u=0, i"] + ); + + // http2 bypass + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function web($get){ + + if($get["npt"]){ + + [$query, $proxy] = $this->backend->get($get["npt"], "web"); + + parse_str($query, $query); + + // country + $country = $query["c"]; + unset($query["c"]); + + $query = http_build_query($query); + + try{ + + $html = + $this->get( + $proxy, + "https://ghosterysearch.com/search?" . $query, + [], + $country + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + }else{ + + $proxy = $this->backend->get_ip(); + + try{ + + $html = + $this->get( + $proxy, + "https://ghosterysearch.com/search", + [ + "q" => $get["s"] + ], + $get["country"] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + $this->fuckhtml->load($html); + + $results_wrapper = + $this->fuckhtml + ->getElementsByClassName( + "results", + "section" + ); + + if(count($results_wrapper) === 0){ + + throw new Exception("Failed to grep result section"); + } + + $this->fuckhtml->load($results_wrapper[0]); + + // get search results + $results = + $this->fuckhtml + ->getElementsByClassName( + "result", + "li" + ); + + if(count($results) === 0){ + + return $out; + } + + foreach($results as $result){ + + $this->fuckhtml->load($result); + + $a = + $this->fuckhtml + ->getElementsByClassName( + "url", + "a" + ); + + if(count($a) === 0){ + + continue; + } + + $a = $a[0]; + + $out["web"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByTagName( + "h2" + )[0] + ) + ), + "description" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByTagName( + "p" + )[0] + ) + ), + "url" => + $this->fuckhtml + ->getTextContent( + $a + ["attributes"] + ["href"] + ), + "date" => null, + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => [], + "table" => [] + ]; + } + + $this->fuckhtml->load($html); + + // get pagination token + $pagination_wrapper = + $this->fuckhtml + ->getElementsByClassName( + "pagination", + "div" + ); + + if(count($pagination_wrapper) !== 0){ + + // found next page! + $this->fuckhtml->load($pagination_wrapper[0]); + + $a = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + if(count($a) !== 0){ + + $q = + parse_url( + $this->fuckhtml + ->getTextContent( + $a[count($a) - 1] + ["attributes"] + ["href"] + ), + PHP_URL_QUERY + ); + + $out["npt"] = + $this->backend + ->store( + $q . "&c=" . $get["country"], + "web", + $proxy + ); + } + } + + return $out; + } + + private function titledots($title){ + + return trim($title, " .\t\n\r\0\x0B…"); + } +} diff --git a/scraper/google.php b/scraper/google.php new file mode 100644 index 0000000..0c73ea0 --- /dev/null +++ b/scraper/google.php @@ -0,0 +1,2989 @@ +<?php + +// @TODO check for consent.google.com page, if need be + +class google{ + + public function __construct(){ + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + + include "lib/backend.php"; + $this->backend = new backend("google"); + } + + public function getfilters($page){ + + $base = [ + "country" => [ // gl=<country> (image: cr=countryAF) + "display" => "Country", + "option" => [ + "any" => "Instance's country", + "af" => "Afghanistan", + "al" => "Albania", + "dz" => "Algeria", + "as" => "American Samoa", + "ad" => "Andorra", + "ao" => "Angola", + "ai" => "Anguilla", + "aq" => "Antarctica", + "ag" => "Antigua and Barbuda", + "ar" => "Argentina", + "am" => "Armenia", + "aw" => "Aruba", + "au" => "Australia", + "at" => "Austria", + "az" => "Azerbaijan", + "bs" => "Bahamas", + "bh" => "Bahrain", + "bd" => "Bangladesh", + "bb" => "Barbados", + "by" => "Belarus", + "be" => "Belgium", + "bz" => "Belize", + "bj" => "Benin", + "bm" => "Bermuda", + "bt" => "Bhutan", + "bo" => "Bolivia", + "ba" => "Bosnia and Herzegovina", + "bw" => "Botswana", + "bv" => "Bouvet Island", + "br" => "Brazil", + "io" => "British Indian Ocean Territory", + "bn" => "Brunei Darussalam", + "bg" => "Bulgaria", + "bf" => "Burkina Faso", + "bi" => "Burundi", + "kh" => "Cambodia", + "cm" => "Cameroon", + "ca" => "Canada", + "cv" => "Cape Verde", + "ky" => "Cayman Islands", + "cf" => "Central African Republic", + "td" => "Chad", + "cl" => "Chile", + "cn" => "China", + "cx" => "Christmas Island", + "cc" => "Cocos (Keeling) Islands", + "co" => "Colombia", + "km" => "Comoros", + "cg" => "Congo", + "cd" => "Congo, the Democratic Republic", + "ck" => "Cook Islands", + "cr" => "Costa Rica", + "ci" => "Cote D'ivoire", + "hr" => "Croatia", + "cu" => "Cuba", + "cy" => "Cyprus", + "cz" => "Czech Republic", + "dk" => "Denmark", + "dj" => "Djibouti", + "dm" => "Dominica", + "do" => "Dominican Republic", + "ec" => "Ecuador", + "eg" => "Egypt", + "sv" => "El Salvador", + "gq" => "Equatorial Guinea", + "er" => "Eritrea", + "ee" => "Estonia", + "et" => "Ethiopia", + "fk" => "Falkland Islands (Malvinas)", + "fo" => "Faroe Islands", + "fj" => "Fiji", + "fi" => "Finland", + "fr" => "France", + "gf" => "French Guiana", + "pf" => "French Polynesia", + "tf" => "French Southern Territories", + "ga" => "Gabon", + "gm" => "Gambia", + "ge" => "Georgia", + "de" => "Germany", + "gh" => "Ghana", + "gi" => "Gibraltar", + "gr" => "Greece", + "gl" => "Greenland", + "gd" => "Grenada", + "gp" => "Guadeloupe", + "gu" => "Guam", + "gt" => "Guatemala", + "gn" => "Guinea", + "gw" => "Guinea-Bissau", + "gy" => "Guyana", + "ht" => "Haiti", + "hm" => "Heard Island and Mcdonald Islands", + "va" => "Holy See (Vatican City State)", + "hn" => "Honduras", + "hk" => "Hong Kong", + "hu" => "Hungary", + "is" => "Iceland", + "in" => "India", + "id" => "Indonesia", + "ir" => "Iran, Islamic Republic", + "iq" => "Iraq", + "ie" => "Ireland", + "il" => "Israel", + "it" => "Italy", + "jm" => "Jamaica", + "jp" => "Japan", + "jo" => "Jordan", + "kz" => "Kazakhstan", + "ke" => "Kenya", + "ki" => "Kiribati", + "kp" => "Korea, Democratic People's Republic", + "kr" => "Korea, Republic", + "kw" => "Kuwait", + "kg" => "Kyrgyzstan", + "la" => "Lao People's Democratic Republic", + "lv" => "Latvia", + "lb" => "Lebanon", + "ls" => "Lesotho", + "lr" => "Liberia", + "ly" => "Libyan Arab Jamahiriya", + "li" => "Liechtenstein", + "lt" => "Lithuania", + "lu" => "Luxembourg", + "mo" => "Macao", + "mk" => "Macedonia, the Former Yugosalv Republic", + "mg" => "Madagascar", + "mw" => "Malawi", + "my" => "Malaysia", + "mv" => "Maldives", + "ml" => "Mali", + "mt" => "Malta", + "mh" => "Marshall Islands", + "mq" => "Martinique", + "mr" => "Mauritania", + "mu" => "Mauritius", + "yt" => "Mayotte", + "mx" => "Mexico", + "fm" => "Micronesia, Federated States", + "md" => "Moldova, Republic", + "mc" => "Monaco", + "mn" => "Mongolia", + "ms" => "Montserrat", + "ma" => "Morocco", + "mz" => "Mozambique", + "mm" => "Myanmar", + "na" => "Namibia", + "nr" => "Nauru", + "np" => "Nepal", + "nl" => "Netherlands", + "an" => "Netherlands Antilles", + "nc" => "New Caledonia", + "nz" => "New Zealand", + "ni" => "Nicaragua", + "ne" => "Niger", + "ng" => "Nigeria", + "nu" => "Niue", + "nf" => "Norfolk Island", + "mp" => "Northern Mariana Islands", + "no" => "Norway", + "om" => "Oman", + "pk" => "Pakistan", + "pw" => "Palau", + "ps" => "Palestinian Territory, Occupied", + "pa" => "Panama", + "pg" => "Papua New Guinea", + "py" => "Paraguay", + "pe" => "Peru", + "ph" => "Philippines", + "pn" => "Pitcairn", + "pl" => "Poland", + "pt" => "Portugal", + "pr" => "Puerto Rico", + "qa" => "Qatar", + "re" => "Reunion", + "ro" => "Romania", + "ru" => "Russian Federation", + "rw" => "Rwanda", + "sh" => "Saint Helena", + "kn" => "Saint Kitts and Nevis", + "lc" => "Saint Lucia", + "pm" => "Saint Pierre and Miquelon", + "vc" => "Saint Vincent and the Grenadines", + "ws" => "Samoa", + "sm" => "San Marino", + "st" => "Sao Tome and Principe", + "sa" => "Saudi Arabia", + "sn" => "Senegal", + "cs" => "Serbia and Montenegro", + "sc" => "Seychelles", + "sl" => "Sierra Leone", + "sg" => "Singapore", + "sk" => "Slovakia", + "si" => "Slovenia", + "sb" => "Solomon Islands", + "so" => "Somalia", + "za" => "South Africa", + "gs" => "South Georgia and the South Sandwich Islands", + "es" => "Spain", + "lk" => "Sri Lanka", + "sd" => "Sudan", + "sr" => "Suriname", + "sj" => "Svalbard and Jan Mayen", + "sz" => "Swaziland", + "se" => "Sweden", + "ch" => "Switzerland", + "sy" => "Syrian Arab Republic", + "tw" => "Taiwan, Province of China", + "tj" => "Tajikistan", + "tz" => "Tanzania, United Republic", + "th" => "Thailand", + "tl" => "Timor-Leste", + "tg" => "Togo", + "tk" => "Tokelau", + "to" => "Tonga", + "tt" => "Trinidad and Tobago", + "tn" => "Tunisia", + "tr" => "Turkey", + "tm" => "Turkmenistan", + "tc" => "Turks and Caicos Islands", + "tv" => "Tuvalu", + "ug" => "Uganda", + "ua" => "Ukraine", + "ae" => "United Arab Emirates", + "uk" => "United Kingdom", + "us" => "United States", + "um" => "United States Minor Outlying Islands", + "uy" => "Uruguay", + "uz" => "Uzbekistan", + "vu" => "Vanuatu", + "ve" => "Venezuela", + "vn" => "Viet Nam", + "vg" => "Virgin Islands, British", + "vi" => "Virgin Islands, U.S.", + "wf" => "Wallis and Futuna", + "eh" => "Western Sahara", + "ye" => "Yemen", + "zm" => "Zambia", + "zw" => "Zimbabwe" + ] + ], + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", // safe=active + "no" => "No" // safe=off + ] + ] + ]; + + switch($page){ + + case "web": + return array_merge( + $base, + [ + "lang" => [ // lr=<lang> (prefix lang with "lang_") + "display" => "Language", + "option" => [ + "any" => "Any language", + "ar" => "Arabic", + "bg" => "Bulgarian", + "ca" => "Catalan", + "cs" => "Czech", + "da" => "Danish", + "de" => "German", + "el" => "Greek", + "en" => "English", + "es" => "Spanish", + "et" => "Estonian", + "fi" => "Finnish", + "fr" => "French", + "hr" => "Croatian", + "hu" => "Hungarian", + "id" => "Indonesian", + "is" => "Icelandic", + "it" => "Italian", + "iw" => "Hebrew", + "ja" => "Japanese", + "ko" => "Korean", + "lt" => "Lithuanian", + "lv" => "Latvian", + "nl" => "Dutch", + "no" => "Norwegian", + "pl" => "Polish", + "pt" => "Portuguese", + "ro" => "Romanian", + "ru" => "Russian", + "sk" => "Slovak", + "sl" => "Slovenian", + "sr" => "Serbian", + "sv" => "Swedish", + "tr" => "Turkish", + "zh-CN" => "Chinese (Simplified)", + "zh-TW" => "Chinese (Traditional)" + ] + ], + "newer" => [ // tbs + "display" => "Newer than", + "option" => "_DATE" + ], + "older" => [ + "display" => "Older than", + "option" => "_DATE" + ], + "spellcheck" => [ + "display" => "Spellcheck", + "option" => [ + "yes" => "Yes", + "no" => "No" + ] + ] + ] + ); + break; + + case "images": + return array_merge( + $base, + [ + "time" => [ // tbs=qdr:<time> + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "d" => "Past 24 hours", + "w" => "Past week", + "m" => "Past month", + "y" => "Past year" + ] + ], + "size" => [ // imgsz + "display" => "Size", + "option" => [ + "any" => "Any size", + "l" => "Large", + "m" => "Medium", + "i" => "Icon", + "qsvga" => "Larger than 400x300", + "vga" => "Larger than 640x480", + "svga" => "Larger than 800x600", + "xga" => "Larger than 1024x768", + "2mp" => "Larger than 2MP", + "4mp" => "Larger than 4MP", + "6mp" => "Larger than 6MP", + "8mp" => "Larger than 8MP", + "10mp" => "Larger than 10MP", + "12mp" => "Larger than 12MP", + "15mp" => "Larger than 15MP", + "20mp" => "Larger than 20MP", + "40mp" => "Larger than 40MP", + "70mp" => "Larger than 70MP" + ] + ], + "ratio" => [ // imgar + "display" => "Aspect ratio", + "option" => [ + "any" => "Any ratio", + "t|xt" => "Tall", + "s" => "Square", + "w" => "Wide", + "xw" => "Panoramic" + ] + ], + "color" => [ // imgc + "display" => "Color", + "option" => [ + "any" => "Any color", + "color" => "Full color", + "bnw" => "Black & white", + "trans" => "Transparent", + // from here, imgcolor + "red" => "Red", + "orange" => "Orange", + "yellow" => "Yellow", + "green" => "Green", + "teal" => "Teal", + "blue" => "Blue", + "purple" => "Purple", + "pink" => "Pink", + "white" => "White", + "gray" => "Gray", + "black" => "Black", + "brown" => "Brown" + ] + ], + "type" => [ // tbs=itp:<type> + "display" => "Type", + "option" => [ + "any" => "Any type", + "clipart" => "Clip Art", + "lineart" => "Line Drawing", + "animated" => "Animated" + ] + ], + "format" => [ // as_filetype + "display" => "Format", + "option" => [ + "any" => "Any format", + "jpg" => "JPG", + "gif" => "GIF", + "png" => "PNG", + "bmp" => "BMP", + "svg" => "SVG", + "webp" => "WEBP", + "ico" => "ICO", + "craw" => "RAW" + ] + ], + "rights" => [ // tbs=sur:<rights> + "display" => "Usage rights", + "option" => [ + "any" => "Any license", + "cl" => "Creative Commons licenses", + "ol" => "Commercial & other licenses" + ] + ] + ] + ); + break; + + case "videos": + return array_merge( + $base, + [ + "newer" => [ // tbs + "display" => "Newer than", + "option" => "_DATE" + ], + "older" => [ + "display" => "Older than", + "option" => "_DATE" + ], + "duration" => [ + "display" => "Duration", + "option" => [ + "any" => "Any duration", + "s" => "Short (0-4min)", // tbs=dur:s + "m" => "Medium (4-20min)", // tbs=dur:m + "l" => "Long (20+ min)" // tbs=dur:l + ] + ], + "quality" => [ + "display" => "Quality", + "option" => [ + "any" => "Any quality", + "h" => "High quality" // tbs=hq:h + ] + ], + "captions" => [ + "display" => "Captions", + "option" => [ + "any" => "No preference", + "yes" => "Closed captioned" // tbs=cc:1 + ] + ] + ] + ); + break; + + case "news": + return array_merge( + $base, + [ + "newer" => [ // tbs + "display" => "Newer than", + "option" => "_DATE" + ], + "older" => [ + "display" => "Older than", + "option" => "_DATE" + ], + "sort" => [ + "display" => "Sort", + "option" => [ + "relevance" => "Relevance", + "date" => "Date" // sbd:1 + ] + ] + ] + ); + break; + } + } + + private function get($proxy, $url, $get = [], $use_lynx = false){ + + $curlproc = curl_init(); + + if($use_lynx === false){ + + $headers = [ + "User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + //"Cookie: SOCS=CAESNQgCEitib3FfaWRlbnRpdHlmcm9udGVuZHVpc2VydmVyXzIwMjQwMzE3LjA4X3AwGgJlbiAEGgYIgM7orwY", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1", + "Priority: u=1", + "TE: trailers" + ]; + + // use http2 + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + }else{ + + $headers = [ + "Accept: text/html, text/plain, text/sgml, */*;q=0.01", + "Accept-Encoding: gzip, compress, bzip2", + "Accept-Language: en", + "User-Agent: Lynx/2.9.0dev.12 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/3.7.8" + ]; + } + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + // follow redirects + curl_setopt($curlproc, CURLOPT_FOLLOWLOCATION, true); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + + if($use_lynx){ + + return mb_convert_encoding($data, "UTF-8", "ISO-8859-1"); + } + + return $data; + } + + + private function scrape_dimg($html){ + + // get images loaded through javascript + $this->dimg = []; + + preg_match_all( + '/function\(\){google\.ldi=({.*?});/', + $html, + $dimg + ); + + if(isset($dimg[1])){ + + foreach($dimg[1] as $i){ + + $tmp = json_decode($i, true); + foreach($tmp as $key => $value){ + + $this->dimg[$key] = + $this->unshit_thumb( + $value + ); + } + } + } + + // get additional javascript base64 images + preg_match_all( + '/var s=\'(data:image\/[^\']+)\';var ii=\[((?:\'[^\']+\',?)+)\];/', + $html, + $dimg + ); + + if(isset($dimg[1])){ + + for($i=0; $i<count($dimg[1]); $i++){ + + $delims = explode(",", $dimg[2][$i]); + $string = + $this->fuckhtml + ->parseJsString( + $dimg[1][$i] + ); + + foreach($delims as $delim){ + + $this->dimg[trim($delim, "'")] = $string; + } + } + } + } + + + private function scrape_imagearr($html){ + // get image links arrays + preg_match_all( + '/\[[0-9]+,"([^"]+)",\["([^"]+)\",([0-9]+),([0-9]+)\],\["([^"]+)",([0-9]+),([0-9]+)\]/', + $html, + $image_arr + ); + + $this->image_arr = []; + if(isset($image_arr[1])){ + + for($i=0; $i<count($image_arr[1]); $i++){ + + $original = + $this->fuckhtml + ->parseJsString( + $image_arr[5][$i] + ); + + if( + preg_match( + '/^x-raw-image/', + $original + ) + ){ + + // only add thumbnail, google doesnt have OG resolution + $this->image_arr[$image_arr[1][$i]] = [ + [ + "url" => + $this->unshit_thumb( + $this->fuckhtml + ->parseJsString( + $image_arr[2][$i] + ) + ), + "width" => (int)$image_arr[7][$i], // pass the OG image width & height + "height" => (int)$image_arr[6][$i] + ] + ]; + + continue; + } + + $this->image_arr[$image_arr[1][$i]] = + [ + [ + "url" => $original, + "width" => (int)$image_arr[7][$i], + "height" => (int)$image_arr[6][$i] + ], + [ + "url" => + $this->unshit_thumb( + $this->fuckhtml + ->parseJsString( + $image_arr[2][$i] + ) + ), + "width" => (int)$image_arr[4][$i], + "height" => (int)$image_arr[3][$i] + ] + ]; + } + } + } + + + private function getdimg($dimg){ + + return isset($this->dimg[$dimg]) ? $this->dimg[$dimg] : null; + } + + + private function unshit_thumb($url){ + // https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQINE2vbnNLHXqoZr3RVsaEJFyOsj1_BiBnJch-e1nyz3oia7Aj5xVj + // https://i.ytimg.com/vi/PZVIyA5ER3Y/mqdefault.jpg?sqp=-oaymwEFCJQBEFM&rs=AMzJL3nXeaCpdIar-ltNwl82Y82cIJfphA + + $parts = parse_url($url); + + if( + isset($parts["host"]) && + preg_match( + '/tbn.*\.gstatic\.com/', + $parts["host"] + ) + ){ + + parse_str($parts["query"], $params); + + if(isset($params["q"])){ + + return "https://" . $parts["host"] . "/images?q=" . $params["q"]; + } + } + + return $url; + } + + + private function parsestyles(){ + + $styles = []; + + $style_div = + $this->fuckhtml + ->getElementsByTagName( + "style" + ); + + $raw_styles = ""; + + foreach($style_div as $style){ + + $raw_styles .= $style["innerHTML"]; + } + + // filter out media/keyframe queries + $raw_styles = + preg_replace( + '/@\s*(?!font-face)[^{]+\s*{[\S\s]+?}\s*}/', + "", + $raw_styles + ); + + // get styles + preg_match_all( + '/(.+?){([\S\s]*?)}/', + $raw_styles, + $matches + ); + + for($i=0; $i<count($matches[1]); $i++){ + + // get style values + preg_match_all( + '/([^:;]+):([^;]*?(?:\([^)]+\)[^;]*?)?)(?:;|$)/', + $matches[2][$i], + $values_regex + ); + + $values = []; + for($k=0; $k<count($values_regex[1]); $k++){ + + $values[trim($values_regex[1][$k])] = + strtolower(trim($values_regex[2][$k])); + } + + $names = explode(",", $matches[1][$i]); + + // h1,h2,h3 will each get their own array index + foreach($names as $name){ + + $name = trim($name, "}\t\n\r\0\x0B"); + + foreach($values as $key => $value){ + + $styles[$name][$key] = $value; + } + } + } + + foreach($styles as $key => $values){ + + $styles[$key]["_c"] = count($values); + } + + $this->styles = $styles; + + // get CSS colors + $this->css_colors = []; + + if(isset($this->styles[":root"])){ + + foreach($this->styles[":root"] as $key => $value){ + + $this->css_colors[$value] = strtolower($key); + } + } + } + + + + private function getstyle($styles){ + + $styles["_c"] = count($styles); + + foreach($this->styles as $style_key => $style_values){ + + if(count(array_intersect_assoc($style_values, $styles)) === $styles["_c"] + 1){ + + $style_key = + explode(" ", $style_key); + + $style_key = $style_key[count($style_key) - 1]; + + return + ltrim( + str_replace( + [".", "#"], + " ", + $style_key + ) + ); + } + } + + return false; + } + + + + private function getcolorvar($color){ + + if(isset($this->css_colors[$color])){ + + return $this->css_colors[$color]; + } + + return null; + } + + + + public function web($get){ + + if($get["npt"]){ + + [$get, $proxy] = $this->backend->get($get["npt"], "web"); + + try{ + $html = + $this->get( + $proxy, + "https://www.google.com" . $get, + [], + true + ); + }catch(Exception $error){ + + throw new Exception("Failed to get HTML"); + } + + }else{ + $search = $get["s"]; + $country = $get["country"]; + $nsfw = $get["nsfw"]; + $lang = $get["lang"]; + $older = $get["older"]; + $newer = $get["newer"]; + $spellcheck = $get["spellcheck"]; + $proxy = $this->backend->get_ip(); + + $offset = 0; + + $params = [ + "q" => $search, + "hl" => "en", + "num" => 20 + ]; + + // country + if($country != "any"){ + + $params["gl"] = $country; + } + + // nsfw + $params["safe"] = $nsfw == "yes" ? "off" : "active"; + + // language + if($lang != "any"){ + + $params["lr"] = "lang_" . $lang; + } + + // generate tbs + $tbs = []; + + // get date + $older = $older === false ? null : date("m/d/Y", $older); + $newer = $newer === false ? null : date("m/d/Y", $newer); + + if( + $older !== null || + $newer !== null + ){ + + $tbs["cdr"] = "1"; + $tbs["cd_min"] = $newer; + $tbs["cd_max"] = $older; + } + + // spellcheck filter + if($spellcheck == "no"){ + + $params["nfpr"] = "1"; + } + + if(count($tbs) !== 0){ + + $params["tbs"] = ""; + + foreach($tbs as $key => $value){ + + $params["tbs"] .= $key . ":" . $value . ","; + } + + $params["tbs"] = rtrim($params["tbs"], ","); + } + + try{ + $html = + $this->get( + $proxy, + "https://www.google.com/search", + $params, + true + ); + }catch(Exception $error){ + + throw new Exception("Failed to get HTML"); + } + + //$html = file_get_contents("scraper/google.html"); + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + $this->fuckhtml->load($html); + $this->detect_sorry(); + + $this->parsestyles(); + + $boxes = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "border" => "thin solid #dadce0", + "padding" => "12px 16px 12px 16px", + "margin-bottom" => "10px", + "font-family" => "sans-serif" + ]), + "div" + ); + + $skip_next = false; + + // get next page token + $npt = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "border" => "thin solid #dadce0", + "color" => "#70757a", + "font-size" => "14px", + "text-align" => "center", + "table-layout" => "fixed", + "width" => "100%" + ]), + "table" + ); + + if(count($npt) !== 0){ + + $this->fuckhtml->load($npt[0]); + + $as = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + foreach($as as $a){ + + $text = + $this->fuckhtml + ->getTextContent( + $a + ); + + if( + $text == "Next >" || + $text == ">" + ){ + + $out["npt"] = + $this->backend->store( + $this->fuckhtml + ->getTextContent( + $a["attributes"]["href"] + ), + "web", + $proxy + ); + } + } + + $this->fuckhtml->load($html); + } + + $first_box = true; + foreach($boxes as $box){ + + $this->fuckhtml->load($box); + + if($first_box){ + + // + // Probe for word correction + // + $first_box = false; + + $txt = + $this->fuckhtml + ->getTextContent($box); + + if( + preg_match( + '/^Showing results for /', + $txt + ) + ){ + + $as = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + if(count($as) === 2){ + + $out["spelling"] = [ + "type" => "including", + "using" => + $this->fuckhtml + ->getTextContent( + $as[0] + ), + "correction" => + $this->fuckhtml + ->getTextContent( + $as[1] + ) + ]; + } + continue; + } + } + + // probe for custom container + $container_title = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "font-weight" => "bold" + ]) + ); + + if(count($container_title) !== 0){ + + $container_title = + strtolower( + $this->fuckhtml + ->getTextContent( + $container_title[0] + ) + ); + + if($container_title == "images"){ + + // + // Parse image carousel + // + $images = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "display" => "inline-block", + "padding" => "2px", + "padding-bottom" => "4px" + ]), + "a" + ); + + foreach($images as $image){ + + $this->fuckhtml->load($image); + + $image_data = + $this->unshiturl( + $image["attributes"]["href"], + true + ); + + $img = + $this->fuckhtml + ->getElementsByTagName( + "img" + )[0]; + + $out["image"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $img["attributes"]["alt"] + ) + ), + "source" => [ + [ + "url" => $image_data["url"], + "width" => $image_data["image_width"], + "height" => $image_data["image_height"] + ], + [ + "url" => + $this->fuckhtml + ->getTextContent( + $img["attributes"]["src"] + ), + "width" => $image_data["thumb_width"], + "height" => $image_data["thumb_height"] + ] + ], + "url" => $image_data["ref"] + ]; + } + + continue; + } + + if( + $container_title == "related searches" || + $container_title == "people also search for" + ){ + + $as = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "color" => "#202124", + "font-size" => "13px", + "line-height" => "20px" + ]), + "span" + ); + + foreach($as as $a){ + + $out["related"][] = + $this->fuckhtml + ->getTextContent( + $a + ); + } + continue; + } + } + + // probe for website link + $link = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "color" => "#1967d2", + "font-size" => "18px", + "line-height" => "24px" + ]), + "a" + ); + + if(count($link) !== 0){ + + // + // Parse search result + // + + $this->fuckhtml->load($link[0]); + + $title = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "color" => "#1967d2", + "font-size" => "18px", + "line-height" => "24px" + ]), + "span" + ); + + if(count($title) === 0){ + + continue; + } + + $this->fuckhtml->load($box); + + $sublinks = []; + $table = []; + + $categories = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "color" => "#202124", + "font-size" => "13px", + "line-height" => "20px" + ]), + "span" + ); + + $i = 0; + foreach($categories as $category){ + + $this->fuckhtml->load($category); + + // probe for sublinks + $subs = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "color" => "#1967d2" + ]), + "a" + ); + + if(count($subs) !== 0){ + + foreach($subs as $sub){ + + $url = + $this->unshiturl( + $this->fuckhtml + ->getTextContent( + $sub["attributes"]["href"] + ) + ); + + if( + preg_match( + '/^https?:\/\//', + $url + ) + ){ + + $sublinks[] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $sub + ) + ), + "description" => null, + "url" => + $this->unshiturl( + $this->fuckhtml + ->getTextContent( + $sub["attributes"]["href"] + ) + ), + "date" => null + ]; + } + } + + unset($categories[$i]); + } + + $i++; + } + + // get description & date + $date = null; + + $categories = array_values($categories); + + //print_r($categories); + + $c = count($categories) - 1; + + $description = + $this->fuckhtml + ->getTextContent( + $categories[$c] + ); + + // remove last category since we're done with it + unset($categories[$c]); + + // probe for date + $description_tmp = explode("·", $description, 2); + $date_tmp = strtotime(trim($description_tmp[0])); + + if( + count($description_tmp) === 2 && + strlen($description_tmp[0]) <= 20 && + $date_tmp !== false + ){ + + $description = + ltrim( + $this->titledots( + $description_tmp[1] + ) + ); + $date = $date_tmp; + }else{ + + $description = + $this->titledots( + $description + ); + } + + // remaining categories should all be greytext + if(count($categories) !== 0){ + + $texts = + explode( + "·", + preg_replace( + '/\s+/', + " ", + $this->fuckhtml + ->getTextContent( + $categories[0] + ) + ) + ); + + foreach($texts as $text){ + + $text = trim($text); + + if( + preg_match( + '/^Rating ([0-9.]+)(?: \(([0-9,]+)\))?/', + $text, + $rating + ) + ){ + + $table["Rating"] = $rating[1]; + if(isset($rating[2])){ + + $table["Rating"] .= " (" . $rating[2] . " votes)"; + } + + continue; + } + + if(stripos($text, "stock") !== false){ + + $table["Stock"] = $text; + continue; + } + } + } + + $out["web"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $title[0] + ) + ), + "description" => $description, + "url" => + $this->unshiturl( + $link[0]["attributes"]["href"] + ), + "date" => $date, + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => $sublinks, + "table" => $table + ]; + + continue; + } + + // parse wikipedia heads + $wiki_title = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "color" => "#202124", + "font-size" => "18px", + "line-height" => "24px" + ]), + "span" + ); + + if(count($wiki_title) !== 0){ + + $wiki_title = + $this->fuckhtml + ->getTextContent( + $wiki_title[0] + ); + + if($wiki_title == "See results about"){ + + // ignore + continue; + } + + if($wiki_title == "Top stories"){ + + // + // Parse news + // + $tds = + $this->fuckhtml + ->getElementsByTagName( + "td" + ); + + foreach($tds as $td){ + + $this->fuckhtml->load($td); + + $a = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + if(count($a) === 0){ + + continue; + } + + $title = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "color" => "#1967d2" + ]), + "span" + ); + + if(count($title) === 0){ + + continue; + } + + $date = null; + + $meta_div = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "color" => "#70757a", + "font-size" => "13px", + "line-height" => "20px" + ]), + "span" + ); + + $meta_div = + explode( + "·", + $this->fuckhtml + ->getTextContent( + $meta_div[count($meta_div) - 1] + ), + 2 + ); + + if(count($meta_div) === 2){ + + $date = strtotime($meta_div[count($meta_div) - 1]); + + if($date === false){ + + $date = null; + } + } + + $out["news"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $title[0] + ) + ), + "description" => null, + "date" => $date, + "thumb" => [ + "url" => null, + "ratio" => null + ], + "url" => + $this->unshiturl( + $a[0]["attributes"]["href"] + ) + ]; + } + continue; + } + + // + // Parse wikipedia heads + // + + $table_div = + $this->fuckhtml + ->getElementsByTagName( + "table" + ); + + if(count($table_div) === 0){ + + continue; + } + + $this->fuckhtml->load($table_div[0]); + + // remove table from box + $box["innerHTML"] = + str_replace( + $table_div[0]["outerHTML"], + "", + $box["innerHTML"] + ); + + // find wiki image + $thumb = null; + + $img = + $this->fuckhtml + ->getElementsByTagName( + "img" + ); + + if(count($img) !== 0){ + + $thumb = + $this->fuckhtml + ->getTextContent( + $img[0]["attributes"]["src"] + ); + } + + $tds = + $this->fuckhtml + ->getElementsByTagName( + "td" + ); + + $description = []; + + foreach($tds as $td){ + + // probe for subtitle + $this->fuckhtml->load($td); + + $subtext = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "color" => "#70757a", + "font-size" => "13px", + "line-height" => "20px" + ]) + ); + + if(count($subtext) !== 0){ + + $description[] = [ + "type" => "quote", + "value" => + $this->fuckhtml + ->getTextContent( + $subtext[0] + ) + ]; + break; + } + } + + $this->fuckhtml->load($box); + + // probe for word definition + $lists = + $this->fuckhtml + ->getElementsByTagName( + "ol" + ); + + if(count($lists) !== 0){ + + $description = []; + + foreach($lists as $list){ + + $box["innerHTML"] = + explode( + $list["outerHTML"], + $box["innerHTML"], + 2 + ); + + if( + count($box["innerHTML"]) === 1 || + trim($box["innerHTML"][0]) == "" + ){ + + break; + } + + $description[] = [ + "type" => "title", + "value" => + $this->fuckhtml + ->getTextContent( + $box["innerHTML"][0] + ) + ]; + + $this->fuckhtml->load($list); + + $lis = + $this->fuckhtml + ->getElementsByTagName( + "li" + ); + + $increment = 1; + + foreach($lis as $li){ + + $this->fuckhtml->load($li); + + $list_items = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "color" => "#202124", + "font-size" => "13px", + "line-height" => "20px" + ]) + ); + + $first_item = true; + foreach($list_items as $it){ + + if($first_item){ + + $first_item = false; + $c = count($description); + + if( + $c !== 0 && + $description[$c - 1]["type"] == "text" + ){ + + $description[$c - 1]["value"] .= + "\n\n" . + $increment . ". " . $this->fuckhtml + ->getTextContent( + $it + ); + }else{ + + $description[] = [ + "type" => "text", + "value" => + $increment . ". " . $this->fuckhtml + ->getTextContent( + $it + ) + ]; + } + }else{ + + $description[] = [ + "type" => "quote", + "value" => + $this->fuckhtml + ->getTextContent( + $it + ) + ]; + } + + $increment++; + } + } + + $box["innerHTML"] = $box["innerHTML"][1]; + } + + $out["answer"][] = [ + "title" => $wiki_title, + "description" => $description, + "url" => null, + "thumb" => null, + "table" => [], + "sublink" => [] + ]; + + continue; + } + + // get separator between description and facts + $separator = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "height" => "4px" + ]), + "div" + ); + + $box_html = []; + $table = []; + + if(count($separator) !== 0){ + + $box_html = + explode( + $separator[0]["outerHTML"], + $box["innerHTML"], + 2 + ); + + if(count($box_html) === 2){ + + $box["innerHTML"] = $box_html[0]; + } + + $this->fuckhtml->load($box_html[1]); + + // get all facts + $facts = + $this->fuckhtml + ->getElementsByTagName( + "div" + ); + + foreach($facts as $fact){ + + if($fact["level"] !== 1){ continue; } + + $fact = + explode( + ":", + $this->fuckhtml + ->getTextContent( + $fact + ) + ); + + $table[trim(preg_replace('/\s+/', " ", $fact[0]))] = + trim(preg_replace('/\s+/', " ", $fact[1])); + } + + $this->fuckhtml->load($box); + } + + // remove wikipedia link + $wiki_link = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "color" => "#1967d2" + ]), + "a" + ); + + $url = null; + if(count($wiki_link) !== 0){ + + foreach($wiki_link as $link){ + + if( + strtolower( + $this->fuckhtml + ->getTextContent( + $link + ) + ) == "wikipedia" + ){ + + $box["innerHTML"] = + str_replace( + $link["outerHTML"], + "", + $box["innerHTML"] + ); + + $url = + $this->unshiturl( + $link["attributes"]["href"] + ); + + $this->fuckhtml->load($box); + break; + } + } + } + + // remains of box should be description + $description[] = [ + "type" => "text", + "value" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $box + ) + ) + ]; + + $out["answer"][] = [ + "title" => $wiki_title, + "description" => $description, + "url" => $url, + "thumb" => $thumb, + "table" => $table, + "sublink" => [] + ]; + } + } + + return $out; + } + + + + public function video($get){ + + if($get["npt"]){ + + [$params, $proxy] = $this->backend->get($get["npt"], "video"); + $params = json_decode($params, true); + + }else{ + $search = $get["s"]; + $country = $get["country"]; + $nsfw = $get["nsfw"]; + $older = $get["older"]; + $newer = $get["newer"]; + $duration = $get["duration"]; + $quality = $get["quality"]; + $captions = $get["captions"]; + $proxy = $this->backend->get_ip(); + + $params = [ + "q" => $search, + "udm" => "7", + "hl" => "en", + "num" => 20 + ]; + + // country + if($country != "any"){ + + $params["gl"] = $country; + } + + // nsfw + $params["safe"] = $nsfw == "yes" ? "off" : "active"; + + $tbs = []; + + // get date + $older = $older === false ? null : date("m/d/Y", $older); + $newer = $newer === false ? null : date("m/d/Y", $newer); + + if( + $older !== null || + $newer !== null + ){ + + $tbs["cdr"] = "1"; + $tbs["cd_min"] = $newer; + $tbs["cd_max"] = $older; + } + + // duration + if($duration != "any"){ + + $tbs[] = "dur:" . $duration; + } + + // quality + if($quality != "any"){ + + $tbs[] = "hq:" . $quality; + } + + // captions + if($captions != "any"){ + + $tbs[] = "cc:" . $captions; + } + + // append tbs + if(count($tbs) !== 0){ + + $params["tbs"] = + implode(",", $tbs); + } + } + + try{ + $html = + $this->get( + $proxy, + "https://www.google.com/search", + $params + ); + }catch(Exception $error){ + + throw new Exception("Failed to get HTML"); + } + + if(!isset($params["start"])){ + + $params["start"] = 0; + } + $params["start"] += 20; + + $this->fuckhtml->load($html); + + // + // Parse web video page + // + $this->detect_sorry(); + + // parse all <style> tags + $this->parsestyles(); + + // get javascript images + $this->scrape_dimg($html); + + $this->scrape_imagearr($html); + + $out = [ + "status" => "ok", + "npt" => + $this->backend->store( + json_encode($params), + "videos", + $proxy + ), + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + $search_div = + $this->fuckhtml + ->getElementById( + "center_col" + ); + + if($search_div === false){ + + throw new Exception("Failed to grep search div"); + } + + $this->fuckhtml->load($search_div); + + $results = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "margin" => "0px 0px 30px" + ]), + "div" + ); + + foreach($results as $result){ + + $this->fuckhtml->load($result); + + $url = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + if(count($url) === 0){ + + // no url, weird, continue + continue; + } + + $title = + $this->fuckhtml + ->getElementsByTagName( + "h3" + ); + + if(count($title) === 0){ + + // no title, weird, continue + continue; + } + + // get description + $description = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "-webkit-box-orient" => "vertical", + "display" => "-webkit-box", + "-webkit-line-clamp" => "2", + "overflow" => "hidden", + "word-break" => "break-word" + ]), + "div" + ); + + if(count($description) === 0){ + + $description = null; + }else{ + + $description = + html_entity_decode( + $this->titledots( + $this->fuckhtml + ->getTextContent( + $description[0] + ) + ) + ); + } + + // get author + date posted + $metadiv = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "margin-top" => "12px" + ]), + "div" + ); + + $author = null; + $date = null; + + if(count($metadiv) !== 0){ + + $metadiv = + explode( + "·", + $this->fuckhtml + ->getTextContent( + $metadiv[0] + ) + ); + + if(count($metadiv) === 3){ + + $author = trim($metadiv[1]); + $date = strtotime(trim($metadiv[2])); + }elseif(count($metadiv) === 2){ + + $author = trim($metadiv[0]); + $date = strtotime(trim($metadiv[1])); + } + } + + $thumb = [ + "url" => null, + "ratio" => null + ]; + + $image = + $this->fuckhtml + ->getElementsByTagName( + "img" + ); + + $duration = null; + + if( + count($image) !== 0 && + isset($image[0]["attributes"]["id"]) + ){ + + $thumb = [ + "url" => $this->getdimg($image[0]["attributes"]["id"]), + "ratio" => "16:9" + ]; + + // get duration + $duration = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle([ + "background-color" => "rgba(0,0,0,0.6)", + "color" => "#fff", + "fill" => "#fff" + ]) + ); + + if(count($duration) !== 0){ + + $duration = + $this->hms2int( + $this->fuckhtml + ->getTextContent( + $duration[0] + )); + }else{ + + $duration = null; + } + } + + $out["video"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $title[0] + ) + ), + "description" => $description, + "author" => [ + "name" => $author, + "url" => null, + "avatar" => null + ], + "date" => $date, + "duration" => $duration, + "views" => null, + "thumb" => $thumb, + "url" => + $this->fuckhtml + ->getTextContent( + $url[0]["attributes"]["href"] + ) + ]; + } + + return $out; + } + + + + public function news($get){ + + if($get["npt"]){ + + [$req, $proxy] = $this->backend->get($get["npt"], "news"); + /*parse_str( + parse_url($req, PHP_URL_QUERY), + $search + );*/ + + try{ + + $html = + $this->get( + $proxy, + "https://www.google.com" . $req, + [] + ); + }catch(Exception $error){ + + throw new Exception("Failed to get HTML"); + } + + }else{ + $search = $get["s"]; + $country = $get["country"]; + $nsfw = $get["nsfw"]; + $older = $get["older"]; + $newer = $get["newer"]; + $sort = $get["sort"]; + $proxy = $this->backend->get_ip(); + + $params = [ + "q" => $search, + "tbm" => "nws", + "hl" => "en", + "num" => "20" + ]; + + // country + if($country != "any"){ + + $params["gl"] = $country; + } + + // nsfw + $params["safe"] = $nsfw == "yes" ? "off" : "active"; + + $tbs = []; + + // get date + $older = $older === false ? null : date("m/d/Y", $older); + $newer = $newer === false ? null : date("m/d/Y", $newer); + + if( + $older !== null || + $newer !== null + ){ + + $tbs["cdr"] = "1"; + $tbs["cd_min"] = $newer; + $tbs["cd_max"] = $older; + } + + // relevance + if($sort == "date"){ + + $tbs["sbd"] = "1"; + } + + // append tbs + if(count($tbs) !== 0){ + + $params["tbs"] = ""; + + foreach($tbs as $key => $value){ + + $params["tbs"] .= $key . ":" . $value . ","; + } + + $params["tbs"] = rtrim($params["tbs"], ","); + } + + //$html = file_get_contents("scraper/google-news.html"); + + $html = + $this->get( + $proxy, + "https://www.google.com/search", + $params + ); + } + + $out = [ + "status" => "ok", + "npt" => null, + "news" => [] + ]; + + $this->fuckhtml->load($html); + + $this->detect_sorry(); + + // get images + $this->scrape_dimg($html); + + // parse styles + $this->parsestyles(); + + $center_col = + $this->fuckhtml + ->getElementById( + "center_col", + "div" + ); + + if($center_col === null){ + + throw new Exception("Could not grep result div"); + } + + $this->fuckhtml->load($center_col); + + // get next page + $npt = + $this->fuckhtml + ->getElementById( + "pnnext", + "a" + ); + + if($npt !== false){ + + $out["npt"] = + $this->backend->store( + $this->fuckhtml + ->getTextContent( + $npt["attributes"] + ["href"] + ), + "news", + $proxy + ); + } + + $as = + $this->fuckhtml + ->getElementsByAttributeName( + "jsname", + "a" + ); + + foreach($as as $a){ + + $this->fuckhtml->load($a); + + // get title + $title = + $this->fuckhtml + ->getElementsByAttributeValue( + "role", + "heading", + "div" + ); + + if(count($title) === 0){ + + continue; + } + + $title = + $this->titledots( + $this->fuckhtml + ->getTextContent( + $title[0] + ) + ); + + // get thumbnail + $image = + $this->fuckhtml + ->getElementsByAttributeName( + "id", + "img" + ); + + // check for padded title node, if found, we're inside a carousel + $probe = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle( + [ + "padding" => "16px 16px 40px 16px" + ] + ), + "div" + ); + + if(count($probe) !== 0){ + + $probe = true; + }else{ + + $probe = false; + } + + if( + count($image) !== 0 && + !isset($image[0]["attributes"]["width"]) + ){ + + $thumb = [ + "url" => + $this->getdimg( + $image[0]["attributes"]["id"] + ), + "ratio" => $probe === true ? "16:9" : "1:1" + ]; + }else{ + + $thumb = [ + "url" => null, + "ratio" => null + ]; + } + + $description = null; + + if($probe === false){ + + $desc_divs = + $this->fuckhtml + ->getElementsByAttributeName( + "style", + "div" + ); + + foreach($desc_divs as $desc){ + + if( + strpos( + $desc["attributes"]["style"], + "margin-top:" + ) !== false + ){ + + $description = + $this->titledots( + $this->fuckhtml + ->getTextContent( + $desc + ) + ); + break; + } + } + } + + // get author + $author = + $this->fuckhtml + ->getElementsByClassName( + $this->getstyle( + [ + "overflow" => "hidden", + "text-align" => "left", + "text-overflow" => "ellipsis", + "white-space" => "nowrap", + "margin-bottom" => "8px" + ] + ), + "div" + ); + + if(count($author) !== 0){ + + $author = + $this->fuckhtml + ->getTextContent( + $author[0] + ); + }else{ + + $author = null; + } + + // get date + $date = null; + + $date_div = + $this->fuckhtml + ->getElementsByAttributeName( + "style", + "div" + ); + + foreach($date_div as $d){ + + $this->fuckhtml->load($d); + + $span = + $this->fuckhtml + ->getElementsByTagName( + "span" + ); + + if( + strpos( + $d["attributes"]["style"], + "bottom:" + ) !== false + ){ + + $date = + strtotime( + $this->fuckhtml + ->getTextContent( + $span[count($span) - 1] + ) + ); + break; + } + } + + $out["news"][] = [ + "title" => $title, + "author" => $author, + "description" => $description, + "date" => $date, + "thumb" => $thumb, + "url" => + $this->unshiturl( + $a["attributes"] + ["href"] + ) + ]; + } + + return $out; + } + + + + + public function image($get){ + + // generate parameters + if($get["npt"]){ + + [$params, $proxy] = + $this->backend->get( + $get["npt"], + "images" + ); + + $params = json_decode($params, true); + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + $country = $get["country"]; + $nsfw = $get["nsfw"]; + $time = $get["time"]; + $size = $get["size"]; + $ratio = $get["ratio"]; + $color = $get["color"]; + $type = $get["type"]; + $format = $get["format"]; + $rights = $get["rights"]; + + $params = [ + "q" => $search, + "udm" => "2" // get images + ]; + + // country (image search uses cr instead of gl) + if($country != "any"){ + + $params["cr"] = "country" . strtoupper($country); + } + + // nsfw + $params["safe"] = $nsfw == "yes" ? "off" : "active"; + + // generate tbs + $tbs = []; + + // time + if($time != "any"){ + + $tbs["qdr"] = $time; + } + + // size + if($size != "any"){ + + $params["imgsz"] = $size; + } + + // ratio + if($ratio != "any"){ + + $params["imgar"] = $ratio; + } + + // color + if($color != "any"){ + + if( + $color == "color" || + $color == "trans" + ){ + + $params["imgc"] = $color; + }elseif($color == "bnw"){ + + $params["imgc"] = "gray"; + }else{ + + $tbs["ic"] = "specific"; + $tbs["isc"] = $color; + } + } + + // type + if($type != "any"){ + + $tbs["itp"] = $type; + } + + // format + if($format != "any"){ + + $params["as_filetype"] = $format; + } + + // rights (tbs) + if($rights != "any"){ + + $tbs["sur"] = $rights; + } + + // append tbs + if(count($tbs) !== 0){ + + $params["tbs"] = ""; + + foreach($tbs as $key => $value){ + + $params["tbs"] .= $key . ":" . $value . ","; + } + + $params["tbs"] = rtrim($params["tbs"], ","); + } + } + /* + $handle = fopen("scraper/page.html", "r"); + $html = fread($handle, filesize("scraper/page.html")); + fclose($handle);*/ + + try{ + $html = + $this->get( + $proxy, + "https://www.google.com/search", + $params + ); + }catch(Exception $error){ + + throw new Exception("Failed to get search page"); + } + + $this->fuckhtml->load($html); + + $this->detect_sorry(); + + // get javascript images + $this->scrape_imagearr($html); + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + $images = + $this->fuckhtml + ->getElementsByClassName( + "ivg-i", + "div" + ); + + foreach($images as $div){ + + $this->fuckhtml->load($div); + + $image = + $this->fuckhtml + ->getElementsByTagName("img")[0]; + + // make sure we dont attempt to show an image we dont have data for + if( + isset($div["attributes"]["data-docid"]) && + isset($this->image_arr[$div["attributes"]["data-docid"]]) + ){ + + $source = + $this->image_arr[ + $div["attributes"]["data-docid"] + ]; + }else{ + + continue; + } + + $out["image"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $image["attributes"]["alt"] + ) + ), + "source" => $source, + "url" => + $this->fuckhtml + ->getTextContent( + $div["attributes"]["data-lpage"] + ) + ]; + } + + // as usual, no way to check if there is a next page reliably + if(count($out["image"]) > 50){ + + if(!isset($params["start"])){ + + $params["start"] = 10; + }else{ + + $params["start"] += 10; + } + + $out["npt"] = + $this->backend + ->store( + json_encode($params), + "image", + $proxy + ); + } + + return $out; + } + + private function unshiturl($url, $return_size = false){ + + // decode + $url = + $this->fuckhtml + ->getTextContent( + $url + ); + + $url_parts = parse_url($url); + + if(isset($url_parts["query"])){ + + parse_str($url_parts["query"], $query); + }else{ + + $query = []; + } + + if( + !isset( + $url_parts["host"] + ) || + stripos($url_parts["host"], "google.") !== false + ){ + + // no host, we have a tracking url + if(isset($query["imgurl"])){ + + $url = $query["imgurl"]; + } + elseif(isset($query["q"])){ + + $url = $query["q"]; + } + } + + // rewrite URLs to remove extra tracking parameters + $domain = parse_url($url, PHP_URL_HOST); + + if( + preg_match( + '/wikipedia.org$/', + $domain + ) + ){ + + // rewrite wikipedia mobile URLs to desktop + $url = + $this->replacedomain( + $url, + preg_replace( + '/([a-z0-9]+)(\.m\.)/', + '$1.', + $domain + ) + ); + } + + elseif( + preg_match( + '/imdb\.com$|youtube\.[^.]+$/', + $domain + ) + ){ + + // rewrite imdb and youtube mobile URLs too + $url = + $this->replacedomain( + $url, + preg_replace( + '/^m\./', + "", + $domain + ) + ); + + } + + elseif( + preg_match( + '/play\.google\.[^.]+$/', + $domain + ) + ){ + + // remove referrers from play.google.com + $u_query = parse_url($url, PHP_URL_QUERY); + if($u_query !== null){ + + parse_str($u_query, $u_query); + if(isset($u_query["referrer"])){ unset($u_query["referrer"]); } + if(isset($u_query["hl"])){ unset($u_query["hl"]); } + if(isset($u_query["gl"])){ unset($u_query["gl"]); } + + $query = http_build_query($query); + + $url = + str_replace( + $u_query, + $u_query, + $url + ); + } + } + + elseif( + preg_match( + '/twitter\.com$/', + $domain + ) + ){ + // remove more referrers from twitter.com + $u_query = parse_url($url, PHP_URL_QUERY); + if($u_query !== null){ + + parse_str($u_query, $u_query); + if(isset($u_query["ref_src"])){ unset($u_query["ref_src"]); } + + $u_query = http_build_query($u_query); + + $url = + str_replace( + $oldquery, + $u_query, + $url + ); + } + } + + elseif( + preg_match( + '/maps\.google\.[^.]+/', + $domain + ) + ){ + + if(stripos($url, "maps?") !== false){ + + $u_query = parse_url($url, PHP_URL_QUERY); + + if($u_query !== null){ + + parse_str($u_query, $u_query); + + if(isset($u_query["daddr"])){ + + $url = + "https://maps.google.com/maps?daddr=" . + urlencode($u_query["daddr"]); + } + } + } + } + + if($return_size){ + + return [ + "url" => $url, + "ref" => isset($query["imgrefurl"]) ? $query["imgrefurl"] : null, + "thumb_width" => isset($query["tbnw"]) ? (int)$query["tbnw"] : null, + "thumb_height" => isset($query["tbnh"]) ? (int)$query["tbnh"] : null, + "image_width" => isset($query["w"]) ? (int)$query["w"] : null, + "image_height" => isset($query["h"]) ? (int)$query["h"] : null + ]; + } + + return $url; + } + + private function replacedomain($url, $domain){ + + return + preg_replace( + '/(https?:\/\/)([^\/]+)/', + '$1' . $domain, + $url + ); + } + + private function titledots($title){ + + return trim($title, " .\t\n\r\0\x0B…"); + } + + private function hms2int($time){ + + $parts = explode(":", $time, 3); + $time = 0; + + if(count($parts) === 3){ + + // hours + $time = $time + ((int)$parts[0] * 3600); + array_shift($parts); + } + + if(count($parts) === 2){ + + // minutes + $time = $time + ((int)$parts[0] * 60); + array_shift($parts); + } + + // seconds + $time = $time + (int)$parts[0]; + + return $time; + } + + private function detect_sorry(){ + + $captcha_form = + $this->fuckhtml + ->getElementById( + "captcha-form", + "form" + ); + + if($captcha_form !== false){ + + throw new Exception("Google returned a captcha"); + } + } +} diff --git a/scraper/google_cse.php b/scraper/google_cse.php new file mode 100644 index 0000000..02ab462 --- /dev/null +++ b/scraper/google_cse.php @@ -0,0 +1,1054 @@ +<?php + +class google_cse{ + + public const req_html = 0; + public const req_js = 1; + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("google_cse"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + $base = [ + "country" => [ // gl=<country> (image: cr=countryAF) + "display" => "Country", + "option" => [ + "any" => "Any country", + "af" => "Afghanistan", + "al" => "Albania", + "dz" => "Algeria", + "as" => "American Samoa", + "ad" => "Andorra", + "ao" => "Angola", + "ai" => "Anguilla", + "aq" => "Antarctica", + "ag" => "Antigua and Barbuda", + "ar" => "Argentina", + "am" => "Armenia", + "aw" => "Aruba", + "au" => "Australia", + "at" => "Austria", + "az" => "Azerbaijan", + "bs" => "Bahamas", + "bh" => "Bahrain", + "bd" => "Bangladesh", + "bb" => "Barbados", + "by" => "Belarus", + "be" => "Belgium", + "bz" => "Belize", + "bj" => "Benin", + "bm" => "Bermuda", + "bt" => "Bhutan", + "bo" => "Bolivia", + "ba" => "Bosnia and Herzegovina", + "bw" => "Botswana", + "bv" => "Bouvet Island", + "br" => "Brazil", + "io" => "British Indian Ocean Territory", + "bn" => "Brunei Darussalam", + "bg" => "Bulgaria", + "bf" => "Burkina Faso", + "bi" => "Burundi", + "kh" => "Cambodia", + "cm" => "Cameroon", + "ca" => "Canada", + "cv" => "Cape Verde", + "ky" => "Cayman Islands", + "cf" => "Central African Republic", + "td" => "Chad", + "cl" => "Chile", + "cn" => "China", + "cx" => "Christmas Island", + "cc" => "Cocos (Keeling) Islands", + "co" => "Colombia", + "km" => "Comoros", + "cg" => "Congo", + "cd" => "Congo, the Democratic Republic", + "ck" => "Cook Islands", + "cr" => "Costa Rica", + "ci" => "Cote D'ivoire", + "hr" => "Croatia", + "cu" => "Cuba", + "cy" => "Cyprus", + "cz" => "Czech Republic", + "dk" => "Denmark", + "dj" => "Djibouti", + "dm" => "Dominica", + "do" => "Dominican Republic", + "ec" => "Ecuador", + "eg" => "Egypt", + "sv" => "El Salvador", + "gq" => "Equatorial Guinea", + "er" => "Eritrea", + "ee" => "Estonia", + "et" => "Ethiopia", + "fk" => "Falkland Islands (Malvinas)", + "fo" => "Faroe Islands", + "fj" => "Fiji", + "fi" => "Finland", + "fr" => "France", + "gf" => "French Guiana", + "pf" => "French Polynesia", + "tf" => "French Southern Territories", + "ga" => "Gabon", + "gm" => "Gambia", + "ge" => "Georgia", + "de" => "Germany", + "gh" => "Ghana", + "gi" => "Gibraltar", + "gr" => "Greece", + "gl" => "Greenland", + "gd" => "Grenada", + "gp" => "Guadeloupe", + "gu" => "Guam", + "gt" => "Guatemala", + "gn" => "Guinea", + "gw" => "Guinea-Bissau", + "gy" => "Guyana", + "ht" => "Haiti", + "hm" => "Heard Island and Mcdonald Islands", + "va" => "Holy See (Vatican City State)", + "hn" => "Honduras", + "hk" => "Hong Kong", + "hu" => "Hungary", + "is" => "Iceland", + "in" => "India", + "id" => "Indonesia", + "ir" => "Iran, Islamic Republic", + "iq" => "Iraq", + "ie" => "Ireland", + "il" => "Israel", + "it" => "Italy", + "jm" => "Jamaica", + "jp" => "Japan", + "jo" => "Jordan", + "kz" => "Kazakhstan", + "ke" => "Kenya", + "ki" => "Kiribati", + "kp" => "Korea, Democratic People's Republic", + "kr" => "Korea, Republic", + "kw" => "Kuwait", + "kg" => "Kyrgyzstan", + "la" => "Lao People's Democratic Republic", + "lv" => "Latvia", + "lb" => "Lebanon", + "ls" => "Lesotho", + "lr" => "Liberia", + "ly" => "Libyan Arab Jamahiriya", + "li" => "Liechtenstein", + "lt" => "Lithuania", + "lu" => "Luxembourg", + "mo" => "Macao", + "mk" => "Macedonia, the Former Yugosalv Republic", + "mg" => "Madagascar", + "mw" => "Malawi", + "my" => "Malaysia", + "mv" => "Maldives", + "ml" => "Mali", + "mt" => "Malta", + "mh" => "Marshall Islands", + "mq" => "Martinique", + "mr" => "Mauritania", + "mu" => "Mauritius", + "yt" => "Mayotte", + "mx" => "Mexico", + "fm" => "Micronesia, Federated States", + "md" => "Moldova, Republic", + "mc" => "Monaco", + "mn" => "Mongolia", + "ms" => "Montserrat", + "ma" => "Morocco", + "mz" => "Mozambique", + "mm" => "Myanmar", + "na" => "Namibia", + "nr" => "Nauru", + "np" => "Nepal", + "nl" => "Netherlands", + "an" => "Netherlands Antilles", + "nc" => "New Caledonia", + "nz" => "New Zealand", + "ni" => "Nicaragua", + "ne" => "Niger", + "ng" => "Nigeria", + "nu" => "Niue", + "nf" => "Norfolk Island", + "mp" => "Northern Mariana Islands", + "no" => "Norway", + "om" => "Oman", + "pk" => "Pakistan", + "pw" => "Palau", + "ps" => "Palestinian Territory, Occupied", + "pa" => "Panama", + "pg" => "Papua New Guinea", + "py" => "Paraguay", + "pe" => "Peru", + "ph" => "Philippines", + "pn" => "Pitcairn", + "pl" => "Poland", + "pt" => "Portugal", + "pr" => "Puerto Rico", + "qa" => "Qatar", + "re" => "Reunion", + "ro" => "Romania", + "ru" => "Russian Federation", + "rw" => "Rwanda", + "sh" => "Saint Helena", + "kn" => "Saint Kitts and Nevis", + "lc" => "Saint Lucia", + "pm" => "Saint Pierre and Miquelon", + "vc" => "Saint Vincent and the Grenadines", + "ws" => "Samoa", + "sm" => "San Marino", + "st" => "Sao Tome and Principe", + "sa" => "Saudi Arabia", + "sn" => "Senegal", + "cs" => "Serbia and Montenegro", + "sc" => "Seychelles", + "sl" => "Sierra Leone", + "sg" => "Singapore", + "sk" => "Slovakia", + "si" => "Slovenia", + "sb" => "Solomon Islands", + "so" => "Somalia", + "za" => "South Africa", + "gs" => "South Georgia and the South Sandwich Islands", + "es" => "Spain", + "lk" => "Sri Lanka", + "sd" => "Sudan", + "sr" => "Suriname", + "sj" => "Svalbard and Jan Mayen", + "sz" => "Swaziland", + "se" => "Sweden", + "ch" => "Switzerland", + "sy" => "Syrian Arab Republic", + "tw" => "Taiwan, Province of China", + "tj" => "Tajikistan", + "tz" => "Tanzania, United Republic", + "th" => "Thailand", + "tl" => "Timor-Leste", + "tg" => "Togo", + "tk" => "Tokelau", + "to" => "Tonga", + "tt" => "Trinidad and Tobago", + "tn" => "Tunisia", + "tr" => "Turkey", + "tm" => "Turkmenistan", + "tc" => "Turks and Caicos Islands", + "tv" => "Tuvalu", + "ug" => "Uganda", + "ua" => "Ukraine", + "ae" => "United Arab Emirates", + "uk" => "United Kingdom", + "us" => "United States", + "um" => "United States Minor Outlying Islands", + "uy" => "Uruguay", + "uz" => "Uzbekistan", + "vu" => "Vanuatu", + "ve" => "Venezuela", + "vn" => "Viet Nam", + "vg" => "Virgin Islands, British", + "vi" => "Virgin Islands, U.S.", + "wf" => "Wallis and Futuna", + "eh" => "Western Sahara", + "ye" => "Yemen", + "zm" => "Zambia", + "zw" => "Zimbabwe" + ] + ], + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", // safe=active + "no" => "No" // safe=off + ] + ], + "spellcheck" => [ + // display undefined + "option" => [ + "yes" => "Yes", + "no" => "No" + ] + ] + ]; + + switch($page){ + + case "web": + return array_merge( + $base, + [ + "lang" => [ // lr=<lang> (prefix lang with "lang_") + "display" => "Language", + "option" => [ + "any" => "Any language", + "ar" => "Arabic", + "bg" => "Bulgarian", + "ca" => "Catalan", + "cs" => "Czech", + "da" => "Danish", + "de" => "German", + "el" => "Greek", + "en" => "English", + "es" => "Spanish", + "et" => "Estonian", + "fi" => "Finnish", + "fr" => "French", + "hr" => "Croatian", + "hu" => "Hungarian", + "id" => "Indonesian", + "is" => "Icelandic", + "it" => "Italian", + "iw" => "Hebrew", + "ja" => "Japanese", + "ko" => "Korean", + "lt" => "Lithuanian", + "lv" => "Latvian", + "nl" => "Dutch", + "no" => "Norwegian", + "pl" => "Polish", + "pt" => "Portuguese", + "ro" => "Romanian", + "ru" => "Russian", + "sk" => "Slovak", + "sl" => "Slovenian", + "sr" => "Serbian", + "sv" => "Swedish", + "tr" => "Turkish", + "zh-CN" => "Chinese (Simplified)", + "zh-TW" => "Chinese (Traditional)" + ] + ], + "sort" => [ + "display" => "Sort by", + "option" => [ + "relevance" => "Relevance", + "date" => "Date" + ] + ], + "redundant" => [ + "display" => "Remove redundant", + "option" => [ + "yes" => "Yes", + "no" => "No", + ] + ] + ] + ); + break; + + case "images": + return array_merge( + $base, + [ + "size" => [ // imgsz + "display" => "Size", + "option" => [ + "any" => "Any size", + "l" => "Large", + "m" => "Medium", + "i" => "Icon", + "qsvga" => "Larger than 400x300", + "vga" => "Larger than 640x480", + "svga" => "Larger than 800x600", + "xga" => "Larger than 1024x768", + "2mp" => "Larger than 2MP", + "4mp" => "Larger than 4MP", + "6mp" => "Larger than 6MP", + "8mp" => "Larger than 8MP", + "10mp" => "Larger than 10MP", + "12mp" => "Larger than 12MP", + "15mp" => "Larger than 15MP", + "20mp" => "Larger than 20MP", + "40mp" => "Larger than 40MP", + "70mp" => "Larger than 70MP" + ] + ], + "color" => [ // imgc + "display" => "Color", + "option" => [ + "any" => "Any color", + "color" => "Full color", + "bnw" => "Black & white", + "trans" => "Transparent", + // from here, imgcolor + "red" => "Red", + "orange" => "Orange", + "yellow" => "Yellow", + "green" => "Green", + "teal" => "Teal", + "blue" => "Blue", + "purple" => "Purple", + "pink" => "Pink", + "white" => "White", + "gray" => "Gray", + "black" => "Black", + "brown" => "Brown" + ] + ], + "format" => [ // as_filetype + "display" => "Format", + "option" => [ + "any" => "Any format", + "jpg" => "JPG", + "gif" => "GIF", + "png" => "PNG", + "bmp" => "BMP", + "svg" => "SVG", + "webp" => "WEBP", + "ico" => "ICO", + "craw" => "RAW" + ] + ] + ] + ); + break; + } + } + + private function get($proxy, $url, $get = [], $reqtype = self::req_js){ + + $curlproc = curl_init(); + + if($get !== []){ + + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + // http2 bypass + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + if($reqtype === self::req_js){ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Sec-GPC: 1", + "Alt-Used: cse.google.com", + "Connection: keep-alive", + "Referer: https://cse.google.com/cse?cx=" . config::GOOGLE_CX_ENDPOINT, + "Sec-Fetch-Dest: script", + "Sec-Fetch-Mode: no-cors", + "Sec-Fetch-Site: same-origin", + "TE: trailers"] + ); + }else{ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1", + "Priority: u=0, i"] + ); + } + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function web($get){ + + // page 1 + // https://cse.google.com/cse/element/v1?rsz=filtered_cse&num=10&hl=en&source=gcsc&cselibv=8fa85d58e016b414&cx=d4e68b99b876541f0&q=asmr&safe=active&cse_tok=AB-tC_6RPUTmB4XK0lE9e1AFFC5r%3A1729563832926&lr=&cr=&gl=&filter=0&sort=&as_oq=&as_sitesearch=&exp=cc%2Capo&oq=asmr&gs_l=partner-web.3..0i512i433j0i512i433i131l2j0i512i433j0i512i433i131j0i512i433j0i512i433i131l2j0i512l2.10902.266627.5.267157.11.10.0.0.0.0.188.1108.2j7.9.0.csems%2Cnrl%3D10...0....1.34.partner-web..42.14.1500.WJQvMvfXkx4&cseclient=hosted-page-client&callback=google.search.cse.api8223&rurl=https%3A%2F%2Fcse.google.com%2Fcse%3Fcx%3Dd4e68b99b876541f0%23gsc.tab%3D0%26gsc.q%3Dtest%26gsc.sort%3D + + // page 2 + // https://cse.google.com/cse/element/v1?rsz=filtered_cse&num=10&hl=en&source=gcsc&start=10&cselibv=8fa85d58e016b414&cx=d4e68b99b876541f0&q=asmr&safe=active&cse_tok=AB-tC_6RPUTmB4XK0lE9e1AFFC5r%3A1729563832926&lr=&cr=&gl=&filter=0&sort=&as_oq=&as_sitesearch=&exp=cc%2Capo&callback=google.search.cse.api3595&rurl=https%3A%2F%2Fcse.google.com%2Fcse%3Fcx%3Dd4e68b99b876541f0%23gsc.tab%3D0%26gsc.q%3Dtest%26gsc.sort%3D + + if($get["npt"]){ + + [$req_params, $proxy] = + $this->backend->get( + $get["npt"], + "web" + ); + + $req_params = + json_decode( + $req_params, + true + ); + + $json = + $this->get( + $proxy, + "https://cse.google.com/cse/element/v1", + $req_params, + self::req_js + ); + + }else{ + + $proxy = $this->backend->get_ip(); + $params = $this->generate_token($proxy); + + //$json = file_get_contents("scraper/google_cse.txt"); + $req_params = [ + "rsz" => "filtered_cse", + "num" => 20, + "hl" => "en", + "source" => "gcsc", + "cselibv" => $params["lib"], + "cx" => config::GOOGLE_CX_ENDPOINT, + "q" => $get["s"], + "safe" => $get["nsfw"] == "yes" ? "off" : "active", + "cse_tok" => $params["token"], + "lr" => $get["lang"] == "any" ? "" : "lang_" . $get["lang"], + "cr" => $get["country"] == "any" ? "" : "country" . strtoupper($get["country"]), + "gl" => "", + "filter" => $get["redundant"] == "yes" ? "1" : "0", + "sort" => $get["sort"] == "relevance" ? "" : "date", + "as_oq" => "", + "as_sitesearch" => "", + "exp" => "cc,apo", + "oq" => $get["s"], + "gs_l" => "partner-web.3...33294.34225.3.34597.26.11.0.0.0.0.201.1132.6j4j1.11.0.csems,nrl=10...0....1.34.partner-web..34.19.1897.FKEeG5yh2iw", + "cseclient" => "hosted-page-client", + "callback" => "google.search.cse.api" . random_int(4000, 99999), + "rurl" => "https://cse.google.com/cse?cx=" . config::GOOGLE_CX_ENDPOINT . "#gsc.tab=0&gsc.q=" . $get["s"] . "&gsc.sort=" + ]; + + if($get["spellcheck"] == "no"){ + + $req_params["nfpr"] = "1"; + } + + $json = + $this->get( + $proxy, + "https://cse.google.com/cse/element/v1", + $req_params, + self::req_js + ); + + unset($req_params["gs_l"]); + $req_params["start"] = 0; + } + + $req_params["start"] += 20; + + if( + !preg_match( + '/google\.search\.cse\.[A-Za-z0-9]+\(([\S\s]*)\);/i', + $json, + $json + ) + ){ + + throw new Exception("Failed to grep JSON"); + } + + $json = json_decode($json[1], true); + + if(isset($json["error"])){ + + if(isset($json["error"]["errors"][0]["message"])){ + + throw new Exception("Google returned an error: " . $json["error"]["errors"][0]["message"]); + } + + if(isset($json["error"]["message"])){ + + throw new Exception("Google returned an error: " . $json["error"]["message"]); + } + + throw new Exception("Google returned an error object"); + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + // detect word correction + if(isset($json["spelling"]["type"])){ + + switch($json["spelling"]["type"]){ + + case "DYM": // did you mean? @TODO fix wording + $type = "including"; + break; + + case "SPELL_CORRECTED_RESULTS": // not many results for + $type = "not_many"; + break; + + default: + $type = "not_many"; + } + + if(isset($json["spelling"]["originalQuery"])){ + + $using = $json["spelling"]["originalQuery"]; + } + elseif(isset($json["spelling"]["anchor"])){ + + $using = html_entity_decode(strip_tags($json["spelling"]["anchor"])); + }elseif(isset($json["spelling"]["originalAnchor"])){ + + $using = html_entity_decode(strip_tags($json["spelling"]["originalAnchor"])); + } + + $out["spelling"] = [ + "type" => $type, + "using" => $using, + "correction" => $json["spelling"]["correctedQuery"] + ]; + } + + if(!isset($json["results"])){ + + return $out; + } + + foreach($json["results"] as $result){ + + // get date from description + $description = + explode( + "...", + trim($result["contentNoFormatting"], " ."), + 2 + ); + + if(count($description) === 2){ + + if($date = strtotime($description[0])){ + + $description = ltrim($description[1]); + }else{ + + $date = null; + $description = implode("...", $description); + } + }else{ + + $description = implode("...", $description); + $date = null; + } + + $description = trim($description, " ."); + + // get thumbnails + if(isset($result["richSnippet"]["cseThumbnail"]["src"])){ + + $thumb = [ + "url" => $this->unshit_thumb($result["richSnippet"]["cseThumbnail"]["src"]), + "ratio" => "1:1" + ]; + } + elseif(isset($result["richSnippet"]["cseImage"]["src"])){ + + $thumb = [ + "url" => $result["richSnippet"]["cseImage"]["src"], + "ratio" => "1:1" + ]; + }else{ + + $thumb = [ + "url" => null, + "ratio" => null + ]; + } + + if($thumb["url"] !== null){ + + $found_size = false; + + // find correct ratio + + if( + isset($result["richSnippet"]["cseThumbnail"]["width"]) && + isset($result["richSnippet"]["cseThumbnail"]["height"]) + ){ + $found_size = true; + $width = (int)$result["richSnippet"]["cseThumbnail"]["width"]; + $height = (int)$result["richSnippet"]["cseThumbnail"]["height"]; + } + elseif( + isset($result["richSnippet"]["metatags"]["ogImageWidth"]) && + isset($result["richSnippet"]["metatags"]["ogImageHeight"]) + ){ + $found_size = true; + $width = (int)$result["richSnippet"]["metatags"]["ogImageWidth"]; + $height = (int)$result["richSnippet"]["metatags"]["ogImageHeight"]; + } + + // calculate rounded ratio + if($found_size){ + + $aspect_ratio = $width / $height; + + if($aspect_ratio >= 1.5){ + + $thumb["ratio"] = "16:9"; + } + elseif($aspect_ratio >= 0.8){ + + $thumb["ratio"] = "1:1"; + }else{ + + $thumb["ratio"] = "9:16"; + } + } + } + + $out["web"][] = [ + "title" => rtrim($result["titleNoFormatting"], " ."), + "description" => $description, + "url" => $result["unescapedUrl"], + "date" => $date, + "type" => "web", + "thumb" => $thumb, + "sublink" => [], + "table" => [] + ]; + } + + // detect next page + if( + isset($json["cursor"]["isExactTotalResults"]) || // detects last page + !isset($json["cursor"]["pages"]) // detects no results on page + ){ + + return $out; + } + + // get next page + $out["npt"] = + $this->backend->store( + json_encode( + $req_params + ), + "web", + $proxy + ); + + return $out; + } + + public function image($get){ + + if($get["npt"]){ + + [$req_params, $proxy] = + $this->backend->get( + $get["npt"], + "images" + ); + + $req_params = + json_decode( + $req_params, + true + ); + + $json = + $this->get( + $proxy, + "https://cse.google.com/cse/element/v1", + $req_params, + self::req_js + ); + + }else{ + + $proxy = $this->backend->get_ip(); + $params = $this->generate_token($proxy); + + //$json = file_get_contents("scraper/google_cse.txt"); + $req_params = [ + "rsz" => "filtered_cse", + "num" => 20, + "hl" => "en", + "source" => "gcsc", + "cselibv" => $params["lib"], + "searchtype" => "image", + "cx" => config::GOOGLE_CX_ENDPOINT, + "q" => $get["s"], + "safe" => $get["nsfw"] == "yes" ? "off" : "active", + "cse_tok" => $params["token"], + "exp" => "cc,apo", + "cseclient" => "hosted-page-client", + "callback" => "google.search.cse.api" . random_int(4000, 99999), + "rurl" => "https://cse.google.com/cse?cx=" . config::GOOGLE_CX_ENDPOINT . "#gsc.tab=1&gsc.q=" . $get["s"] . "&gsc.sort=" + ]; + + // add additional hidden filters + + // country (image search uses cr instead of gl) + if($get["country"] != "any"){ + + $req_params["cr"] = "country" . strtoupper($get["country"]); + } + + // nsfw + $req_params["safe"] = $get["nsfw"] == "yes" ? "off" : "active"; + + // size + if($get["size"] != "any"){ + + $req_params["imgsz"] = $get["size"]; + } + + // format + if($get["format"] != "any"){ + + $req_params["as_filetype"] = $get["format"]; + } + + // color + if($get["color"] != "any"){ + + if( + $get["color"] == "color" || + $get["color"] == "trans" + ){ + + $req_params["imgc"] = $get["color"]; + }elseif($get["color"] == "bnw"){ + + $req_params["imgc"] = "gray"; + }else{ + + $req_params["imgcolor"] = $get["color"]; + } + } + + $json = + $this->get( + $proxy, + "https://cse.google.com/cse/element/v1", + $req_params, + self::req_js + ); + + $req_params["start"] = 0; + } + + $req_params["start"] += 20; + + if( + !preg_match( + '/google\.search\.cse\.[A-Za-z0-9]+\(([\S\s]*)\);/i', + $json, + $json + ) + ){ + + throw new Exception("Failed to grep JSON"); + } + + $json = json_decode($json[1], true); + + if(isset($json["error"])){ + + if(isset($json["error"]["errors"][0]["message"])){ + + throw new Exception("Google returned an error: " . $json["error"]["errors"][0]["message"]); + } + + if(isset($json["error"]["message"])){ + + throw new Exception("Google returned an error: " . $json["error"]["message"]); + } + + throw new Exception("Google returned an error object"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + // detect next page + if( + isset($json["cursor"]["isExactTotalResults"]) || // detects last page + !isset($json["cursor"]["pages"]) // detects no results on page + ){ + + return $out; + } + + foreach($json["results"] as $result){ + + $out["image"][] = [ + "title" => rtrim($result["titleNoFormatting"], " ."), + "source" => [ + [ + "url" => $result["unescapedUrl"], + "width" => (int)$result["width"], + "height" => (int)$result["height"] + ], + [ + "url" => $result["tbLargeUrl"], + "width" => (int)$result["tbLargeWidth"], + "height" => (int)$result["tbLargeHeight"] + ] + ], + "url" => $result["originalContextUrl"] + ]; + } + + // get next page + $out["npt"] = + $this->backend->store( + json_encode( + $req_params + ), + "images", + $proxy + ); + + return $out; + } + + private function generate_token($proxy){ + + $html = + $this->get( + $proxy, + "https://cse.google.com/cse", + [ + "cx" => config::GOOGLE_CX_ENDPOINT + ], + self::req_html + ); + + // detect captcha + $this->fuckhtml->load($html); + + $title = + $this->fuckhtml + ->getElementsByTagName( + "title" + ); + + if( + count($title) !== 0 && + $title[0]["innerHTML"] == "302 Moved" + ){ + + throw new Exception("Google returned a captcha"); + } + + // get token + preg_match( + '/relativeUrl=\'([^\']+)\';/i', + $html, + $js_uri + ); + + if(!isset($js_uri[1])){ + + throw new Exception("Failed to grep search token"); + } + + $js_uri = + $this->fuckhtml + ->parseJsString( + $js_uri[1] + ); + + // get parameters + $js = + $this->get( + $proxy, + "https://cse.google.com" . $js_uri, + [], + self::req_js + ); + + preg_match( + '/}\)\(({[\S\s]+})\);/', + $js, + $json + ); + + if(!isset($json[1])){ + + throw new Exception("Failed to grep JSON parameters"); + } + + $json = json_decode($json[1], true); + + return [ + "token" => $json["cse_token"], + "lib" => $json["cselibVersion"] + ]; + } + + private function unshit_thumb($url){ + // https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQINE2vbnNLHXqoZr3RVsaEJFyOsj1_BiBnJch-e1nyz3oia7Aj5xVj + // https://i.ytimg.com/vi/PZVIyA5ER3Y/mqdefault.jpg?sqp=-oaymwEFCJQBEFM&rs=AMzJL3nXeaCpdIar-ltNwl82Y82cIJfphA + + $parts = parse_url($url); + + if( + isset($parts["host"]) && + preg_match( + '/tbn.*\.gstatic\.com/', + $parts["host"] + ) + ){ + + parse_str($parts["query"], $params); + + if(isset($params["q"])){ + + return "https://" . $parts["host"] . "/images?q=" . $params["q"]; + } + } + + return $url; + } +} diff --git a/scraper/greppr.php b/scraper/greppr.php new file mode 100644 index 0000000..fc8511c --- /dev/null +++ b/scraper/greppr.php @@ -0,0 +1,435 @@ +<?php + +class greppr{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("greppr"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + return []; + } + + private function get($proxy, $url, $get = [], $cookie = false, $post){ + + $curlproc = curl_init(); + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + if($post === false){ + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + if($cookie === false){ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1"] + ); + }else{ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Referer: https://greppr.org/search", + "Cookie: PHPSESSID=$cookie", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: same-origin", + "Sec-Fetch-User: ?1", + "Priority: u=0, i"] + ); + } + }else{ + + $get = http_build_query($get); + + curl_setopt($curlproc, CURLOPT_POST, true); + curl_setopt($curlproc, CURLOPT_POSTFIELDS, $get); + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + "Content-Type: application/x-www-form-urlencoded", + "Content-Length: " . strlen($get), + "Origin: https://greppr.org", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Referer: https://greppr.org/", + "Cookie: PHPSESSID=$cookie", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: same-origin", + "Sec-Fetch-User: ?1", + "Priority: u=0, i"] + ); + } + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $headers = []; + + curl_setopt( + $curlproc, + CURLOPT_HEADERFUNCTION, + function($curlproc, $header) use (&$headers){ + + $len = strlen($header); + $header = explode(':', $header, 2); + + if(count($header) < 2){ + + // ignore invalid headers + return $len; + } + + $headers[strtolower(trim($header[0]))] = trim($header[1]); + + return $len; + } + ); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + + return [ + "headers" => $headers, + "data" => $data + ]; + } + + public function web($get, $first_attempt = true){ + + if($get["npt"]){ + + [$q, $proxy] = $this->backend->get($get["npt"], "web"); + + $tokens = json_decode($q, true); + + // + // Get paginated page + // + try{ + + $html = $this->get( + $proxy, + "https://greppr.org" . $tokens["get"], + [], + $tokens["cookie"], + false + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + + // + // get token + // + try{ + + $html = + $this->get( + $proxy, + "https://greppr.org", + [], + false, + false + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search tokens"); + } + + // + // Parse token + // + $this->fuckhtml->load($html["data"]); + + $tokens = []; + + $inputs = + $this->fuckhtml + ->getElementsByTagName( + "input" + ); + + foreach($inputs as $input){ + + if(!isset($input["attributes"]["name"])){ + + continue; + } + + switch($input["attributes"]["name"]){ + + case "var1": + case "var2": + case "n": + $tokens[$input["attributes"]["name"]] = + $this->fuckhtml + ->getTextContent( + $input["attributes"]["value"] + ); + break; + + default: + $tokens["req"] = + $this->fuckhtml + ->getTextContent( + $input["attributes"]["name"] + ); + break; + } + } + + // get cookie + preg_match( + '/PHPSESSID=([^;]+)/', + $html["headers"]["set-cookie"], + $cookie + ); + + if(!isset($cookie[1])){ + + // server sent an unexpected cookie + throw new Exception("Got malformed cookie"); + } + + $tokens["cookie"] = $cookie[1]; + + if($tokens === false){ + + throw new Exception("Failed to grep search tokens"); + } + + // + // Get initial search page + // + try{ + + $html = $this->get( + $proxy, + "https://greppr.org/search", + [ + "var1" => $tokens["var1"], + "var2" => $tokens["var2"], + $tokens["req"] => $search, + "n" => $tokens["n"] + ], + $tokens["cookie"], + true + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + } + + //$html = file_get_contents("scraper/greppr.html"); + //$this->fuckhtml->load($html); + $this->fuckhtml->load($html["data"]); + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + // get results for later + $results = + $this->fuckhtml + ->getElementsByClassName( + "result", + "div" + ); + + // check for next page + $next_elem = + $this->fuckhtml + ->getElementsByClassName( + "pagination", + "ul" + ); + + if(count($next_elem) !== 0){ + + $this->fuckhtml->load($next_elem[0]); + + $as = + $this->fuckhtml + ->getElementsByClassName( + "page-link", + "a" + ); + + $break = false; + foreach($as as $a){ + + if($break === true){ + + $out["npt"] = + $this->backend->store( + json_encode([ + "get" => + $this->fuckhtml + ->getTextContent( + $a["attributes"]["href"] + ), + "cookie" => $tokens["cookie"] + ]), + "web", + $proxy + ); + break; + } + + if($a["attributes"]["href"] == "#"){ + + $break = true; + } + } + } + + // scrape results + foreach($results as $result){ + + $this->fuckhtml->load($result); + + $a = + $this->fuckhtml + ->getElementsByTagName( + "a" + )[0]; + + $description = + $this->fuckhtml + ->getElementsByClassName( + "highlightedDesc", + "p" + ); + + if(count($description) === 0){ + + $description = null; + }else{ + + $description = + $this->limitstrlen( + $this->fuckhtml + ->getTextContent( + $description[0] + ) + ); + } + + $date = + $this->fuckhtml + ->getElementsByTagName( + "p" + ); + + $date = + strtotime( + explode( + ":", + $this->fuckhtml + ->getTextContent( + $date[count($date) - 1]["innerHTML"] + ) + )[1] + ); + + $out["web"][] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $a["innerHTML"] + ), + "description" => $description, + "url" => + $this->fuckhtml + ->getTextContent( + $a["attributes"]["href"] + ), + "date" => $date, + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => [], + "table" => [] + ]; + } + + return $out; + } + + private function limitstrlen($text){ + + return explode("\n", wordwrap($text, 300, "\n"))[0]; + } +} diff --git a/scraper/imgur.php b/scraper/imgur.php new file mode 100644 index 0000000..e41f4c2 --- /dev/null +++ b/scraper/imgur.php @@ -0,0 +1,282 @@ +<?php + +class imgur{ + + public function __construct(){ + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + + include "lib/backend.php"; + $this->backend = new backend("imgur"); + } + + public function getfilters($page){ + + return [ + "sort" => [ // /score/ + "display" => "Sort by", + "option" => [ + "score" => "Highest scoring", + "relevance" => "Most relevant", + "time" => "Newest first" + ] + ], + "time" => [ // /score/day/ + "display" => "Time posted", + "option" => [ + "all" => "All time", + "day" => "Today", + "week" => "This week", + "month" => "This month", + "year" => "This year" + ] + ], + "format" => [ // q_type + "display" => "Format", + "option" => [ + "any" => "Any format", + "jpg" => "JPG", + "png" => "PNG", + "gif" => "GIF", + "anigif" => "Animated GIF", + "album" => "Albums" + ] + ], + "size" => [ // q_size_px + "display" => "Size", + "option" => [ + "any" => "Any size", + "small" => "Small (500px or less)", + "med" => "Medium (500px to 2000px)", + "big" => "Big (2000px to 5000px)", + "lrg" => "Large (5000px to 10000px)", + "huge" => "Huge (10000px and above)" + ] + ] + ]; + } + + private function get($proxy, $url, $get = []){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?scrolled&" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Referer: https://imgur.com/search/", + "Connection: keep-alive", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-origin", + "TE: trailers", + "X-Requested-With: XMLHttpRequest"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function image($get){ + + if($get["npt"]){ + + [$filter, $proxy] = + $this->backend->get( + $get["npt"], + "images" + ); + + $filter = json_decode($filter, true); + + $search = $filter["s"]; + unset($filter["s"]); + + $sort = $filter["sort"]; + unset($filter["sort"]); + + $time = $filter["time"]; + unset($filter["time"]); + + $format = $filter["format"]; + unset($filter["format"]); + + $size = $filter["size"]; + unset($filter["size"]); + + $page = $filter["page"]; + unset($filter["page"]); + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + $sort = $get["sort"]; + $time = $get["time"]; + $format = $get["format"]; + $size = $get["size"]; + $page = 0; + + $filter = [ + "q" => $search + ]; + + if($format != "any"){ + + $filter["q_type"] = $format; + } + + if($size != "any"){ + + $filter["q_size_px"] = $size; + $filter["q_size_is_mpx"] = "off"; + } + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + try{ + $html = + $this->get( + $proxy, + "https://imgur.com/search/$sort/$time/page/$page", + $filter + ); + + }catch(Exception $error){ + + throw new Exception("Failed to fetch HTML"); + } + + $json = json_decode($html, true); + + if($json){ + + // {"data":{"error":"Imgur is temporarily over capacity. Please try again later."},"success":false,"status":403} + + if(isset($json["data"]["error"])){ + + if(stripos($json["data"]["error"], "capacity")){ + + throw new Exception("Imgur IP blocked this 4get instance or request proxy. Try again"); + } + } + + throw new Exception("Imgur returned an unknown error (IP ban?)"); + } + + $this->fuckhtml->load($html); + + $posts = + $this->fuckhtml + ->getElementsByClassName( + "post", + "div" + ); + + foreach($posts as $post){ + + $this->fuckhtml->load($post); + + $image = + $this->fuckhtml + ->getElementsByTagName("img"); + + if(count($image) === 0){ + + continue; + } + + $image = $image[0]; + + $image_url = "https:" . substr($this->fuckhtml->getTextContent($image["attributes"]["src"]), 0, -5); + + $out["image"][] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $image["attributes"]["alt"] + ), + "source" => [ + [ + "url" => $image_url . ".jpg", + "width" => null, + "height" => null + ], + [ + "url" => $image_url . "m.jpg", + "width" => null, + "height" => null + ] + ], + "url" => + "https://imgur.com" . + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByClassName( + "image-list-link", + "a" + ) + [0] + ["attributes"] + ["href"] + ) + ]; + } + + if(isset($out["image"][0])){ + + // store nextpage + $filter["s"] = $search; + $filter["sort"] = $sort; + $filter["time"] = $time; + $filter["format"] = $format; + $filter["size"] = $size; + $filter["page"] = $page + 1; + + $out["npt"] = + $this->backend->store( + json_encode($filter), + "images", + $proxy + ); + } + + return $out; + } +} diff --git a/scraper/marginalia.php b/scraper/marginalia.php new file mode 100644 index 0000000..8fcd9fc --- /dev/null +++ b/scraper/marginalia.php @@ -0,0 +1,580 @@ +<?php + +class marginalia{ + public function __construct(){ + + include "lib/anubis.php"; + $this->anubis = new anubis(); + + include_once "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + + include "lib/backend.php"; + $this->backend = new backend("marginalia"); + } + + public function getfilters($page){ + + if(config::MARGINALIA_API_KEY === null){ + + $base = [ + "adtech" => [ + "display" => "Reduce adtech", + "option" => [ + "no" => "No", + "yes" => "Yes" + ] + ], + "recent" => [ + "display" => "Recent results", + "option" => [ + "no" => "No", + "yes" => "Yes" + ] + ], + "intitle" => [ + "display" => "Search in title", + "option" => [ + "no" => "No", + "yes" => "Yes" + ] + ] + ]; + }else{ + + $base = []; + } + + return array_merge( + $base, + [ + "format" => [ + "display" => "Format", + "option" => [ + "any" => "Any format", + "html5" => "html5", + "xhtml" => "xhtml", + "html123" => "html123" + ] + ], + "file" => [ + "display" => "Filetype", + "option" => [ + "any" => "Any filetype", + "nomedia" => "Deny media", + "media" => "Contains media", + "audio" => "Contains audio", + "video" => "Contains video", + "archive" => "Contains archive", + "document" => "Contains document" + ] + ], + "javascript" => [ + "display" => "Javascript", + "option" => [ + "any" => "Allow JS", + "deny" => "Deny JS", + "require" => "Require JS" + ] + ], + "trackers" => [ + "display" => "Trackers", + "option" => [ + "any" => "Allow trackers", + "deny" => "Deny trackers", + "require" => "Require trackers" + ] + ], + "cookies" => [ + "display" => "Cookies", + "option" => [ + "any" => "Allow cookies", + "deny" => "Deny cookies", + "require" => "Require cookies" + ] + ], + "affiliate" => [ + "display" => "Affiliate links in body", + "option" => [ + "any" => "Allow affiliate links", + "deny" => "Deny affiliate links", + "require" => "Require affiliate links" + ] + ] + ] + ); + } + + private function get($proxy, $url, $get = [], $get_cookies = 1){ + + $curlproc = curl_init(); + + switch($get_cookies){ + + case 0: + $cookies = ""; + $cookies_tmp = []; + curl_setopt($curlproc, CURLOPT_HEADERFUNCTION, function($curlproc, $header) use (&$cookies_tmp){ + + $length = strlen($header); + + $header = explode(":", $header, 2); + + if(trim(strtolower($header[0])) == "set-cookie"){ + + $cookie_tmp = explode("=", trim($header[1]), 2); + + $cookies_tmp[trim($cookie_tmp[0])] = + explode(";", $cookie_tmp[1], 2)[0]; + } + + return $length; + }); + break; + + case 1: + $cookies = ""; + break; + + default: + $cookies = "Cookie: " . $get_cookies; + } + + $headers = [ + "User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + $cookies, + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1" + ]; + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + if($get_cookies === 0){ + + $cookie = []; + + foreach($cookies_tmp as $key => $value){ + + $cookie[] = $key . "=" . $value; + } + + curl_close($curlproc); + return implode(";", $cookie); + } + + return $data; + } + + public function web($get){ + + $search = [$get["s"]]; + if(strlen($get["s"]) === 0){ + + throw new Exception("Search term is empty!"); + } + + $format = $get["format"]; + $file = $get["file"]; + + foreach( + [ + "javascript" => $get["javascript"], + "trackers" => $get["trackers"], + "cookies" => $get["cookies"], + "affiliate" => $get["affiliate"] + ] + as $key => $value + ){ + + if($value == "any"){ continue; } + + switch($key){ + + case "javascript": $str = "js:true"; break; + case "trackers": $str = "special:tracking"; break; + case "cookies": $str = "special:cookies"; break; + case "affiliate": $str = "special:affiliate"; break; + } + + if($value == "deny"){ + $str = "-" . $str; + } + + $search[] = $str; + } + + if($format != "any"){ + + $search[] = "format:$format"; + } + + switch($file){ + + case "any": break; + case "nomedia": $search[] = "-special:media"; break; + case "media": $search[] = "special:media"; break; + + default: + $search[] = "file:$file"; + } + + $search = implode(" ", $search); + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + // API scraper + if(config::MARGINALIA_API_KEY !== null){ + + try{ + $json = + $this->get( + $this->backend->get_ip(), // no nextpage + "https://api.marginalia-search.com/" . config::MARGINALIA_API_KEY . "/search/" . urlencode($search), + [ + "count" => 20 + ] + ); + }catch(Exception $error){ + + throw new Exception("Failed to get JSON"); + } + + if($json == "Slow down"){ + + throw new Exception("The API key used is rate limited. Please try again in a few minutes."); + } + + $json = json_decode($json, true); + + foreach($json["results"] as $result){ + + $out["web"][] = [ + "title" => $result["title"], + "description" => str_replace("\n", " ", $result["description"]), + "url" => $result["url"], + "date" => null, + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => [], + "table" => [] + ]; + } + + return $out; + } + + // HTML parser + $proxy = $this->backend->get_ip(); + + // + // Bypass anubis check + // + /* + if(($anubis_key = apcu_fetch("marginalia_cookie")) === false){ + + try{ + $html = + $this->get( + $proxy, + "https://old-search.marginalia.nu/search", + [ + "query" => $search + ] + ); + + }catch(Exception $error){ + + throw new Exception("Failed to get anubis challenge"); + } + + try{ + + $anubis_data = $this->anubis->scrape($html); + }catch(Exception $error){ + + throw new Exception($error); + } + + // send anubis response & get cookies + // https://old-search.marginalia.nu/.within.website/x/cmd/anubis/api/pass-challenge?response=0000018966b086834f738bacba6031028adb5aa875974ead197a8b75778baf3a&nonce=39947&redir=https%3A%2F%2Fold-search.marginalia.nu%2F&elapsedTime=1164 + + try{ + + $anubis_key = + $this->get( + $proxy, + "https://old-search.marginalia.nu/.within.website/x/cmd/anubis/api/pass-challenge", + [ + "response" => $anubis_data["response"], + "nonce" => $anubis_data["nonce"], + "redir" => "https://old-search.marginalia.nu/", + "elapsedTime" => random_int(1000, 2000) + ], + 0 + ); + }catch(Exception $error){ + + throw new Exception("Failed to submit anubis challenge"); + } + + apcu_store("marginalia_cookie", $anubis_key); + }*/ + + if($get["npt"]){ + + [$params, $proxy] = + $this->backend->get( + $get["npt"], + "web" + ); + + try{ + $html = + $this->get( + $proxy, + "https://old-search.marginalia.nu/search?" . $params, + [], + //$anubis_key + ); + }catch(Exception $error){ + + throw new Exception("Failed to get HTML"); + } + + }else{ + $params = [ + "query" => $search + ]; + + foreach(["adtech", "recent", "intitle"] as $v){ + + if($get[$v] == "yes"){ + + switch($v){ + + case "adtech": $params["adtech"] = "reduce"; break; + case "recent": $params["recent"] = "recent"; break; + case "adtech": $params["searchTitle"] = "title"; break; + } + } + } + + try{ + $html = + $this->get( + $proxy, + "https://old-search.marginalia.nu/search", + $params, + //$anubis_key + ); + }catch(Exception $error){ + + throw new Exception("Failed to get HTML"); + } + } + + $this->fuckhtml->load($html); + + $sections = + $this->fuckhtml + ->getElementsByClassName( + "card search-result", + "section" + ); + + foreach($sections as $section){ + + $this->fuckhtml->load($section); + + $title = + $this->fuckhtml + ->getElementsByClassName( + "title", + "a" + )[0]; + + $description = + $this->fuckhtml + ->getElementsByClassName( + "description", + "p" + ); + + if(count($description) !== 0){ + + $description = + $this->fuckhtml + ->getTextContent( + $description[0] + ); + }else{ + + $description = null; + } + + $sublinks = []; + $sublink_html = + $this->fuckhtml + ->getElementsByClassName("additional-results"); + + if(count($sublink_html) !== 0){ + + $this->fuckhtml->load($sublink_html[0]); + + $links = + $this->fuckhtml + ->getElementsByTagName("a"); + + foreach($links as $link){ + + $sublinks[] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $link + ), + "date" => null, + "description" => null, + "url" => + $this->fuckhtml + ->getTextContent( + $link["attributes"]["href"] + ) + ]; + } + } + + $out["web"][] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $title + ), + "description" => $description, + "url" => + $this->fuckhtml + ->getTextContent( + $title["attributes"]["href"] + ), + "date" => null, + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => $sublinks, + "table" => [] + ]; + } + + // get next page + $this->fuckhtml->load($html); + + $pagination = + $this->fuckhtml + ->getElementsByAttributeValue( + "aria-label", + "pagination", + "nav" + ); + + if(count($pagination) === 0){ + + // no pagination + return $out; + } + + $this->fuckhtml->load($pagination[0]); + + $pages = + $this->fuckhtml + ->getElementsByClassName( + "page-link", + "a" + ); + + $found_current_page = false; + + foreach($pages as $page){ + + if( + stripos( + $page["attributes"]["class"], + "active" + ) !== false + ){ + + $found_current_page = true; + continue; + } + + if($found_current_page){ + + // we found current page index, and we iterated over + // the next page <a> + + $out["npt"] = + $this->backend->store( + parse_url( + $page["attributes"]["href"], + PHP_URL_QUERY + ), + "web", + $proxy + ); + break; + } + } + + return $out; + } +} + diff --git a/scraper/mojeek.php b/scraper/mojeek.php new file mode 100644 index 0000000..2939be5 --- /dev/null +++ b/scraper/mojeek.php @@ -0,0 +1,1194 @@ +<?php + +class mojeek{ + public function __construct(){ + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + + include "lib/backend.php"; + $this->backend = new backend("mojeek"); + } + + public function getfilters($page){ + + switch($page){ + + case "web": + return [ + "focus" => [ + "display" => "Focus", + "option" => [ + "any" => "No focus", + "blogs" => "Blogs", + "Dictionary" => "Dictionary", + "Recipes" => "Recipes", + "Time" => "Time", + "Weather" => "Weather" + ] + ], + "lang" => [ + "display" => "Language", + "option" => [ + "any" => "Any language", + "af" => "Afrikaans", + "sq" => "Albanian", + "an" => "Aragonese", + "ay" => "Aymara", + "bi" => "Bislama", + "br" => "Breton", + "ca" => "Catalan", + "kw" => "Cornish", + "co" => "Corsican", + "hr" => "Croatian", + "da" => "Danish", + "nl" => "Dutch", + "dz" => "Dzongkha", + "en" => "English", + "fj" => "Fijian", + "fi" => "Finnish", + "fr" => "French", + "gd" => "Gaelic", + "gl" => "Galician", + "de" => "German", + "ht" => "Haitian", + "io" => "Ido", + "id" => "Indonesian", + "ia" => "Interlingua", + "ie" => "Interlingue", + "ga" => "Irish", + "it" => "Italian", + "rw" => "Kinyarwanda", + "la" => "Latin", + "li" => "Limburgish", + "lb" => "Luxembourgish", + "no" => "Norwegian", + "nb" => "Norwegian Bokmål", + "nn" => "Norwegian Nynorsk", + "oc" => "Occitan (post 1500)", + "pl" => "Polish", + "pt" => "Portuguese", + "rm" => "Romansh", + "rn" => "Rundi", + "sg" => "Sango", + "so" => "Somali", + "es" => "Spanish", + "sw" => "Swahili", + "ss" => "Swati", + "sv" => "Swedish", + "ty" => "Tahitian", + "to" => "Tonga (Tonga Islands)", + "ts" => "Tsonga", + "vo" => "Volapük", + "wa" => "Walloon", + "cy" => "Welsh", + "xh" => "Xhosa", + "zu" => "Zulu" + ] + ], + "country" => [ + "display" => "Country", + "option" => [ + "any" => "No location bias", + "af" => "Afghanistan", + "ax" => "Åland Islands", + "al" => "Albania", + "dz" => "Algeria", + "as" => "American Samoa", + "ad" => "Andorra", + "ao" => "Angola", + "ai" => "Anguilla", + "aq" => "Antarctica", + "ag" => "Antigua and Barbuda", + "ar" => "Argentina", + "am" => "Armenia", + "aw" => "Aruba", + "au" => "Australia", + "at" => "Austria", + "az" => "Azerbaijan", + "bs" => "Bahamas", + "bh" => "Bahrain", + "bd" => "Bangladesh", + "bb" => "Barbados", + "by" => "Belarus", + "be" => "Belgium", + "bz" => "Belize", + "bj" => "Benin", + "bm" => "Bermuda", + "bt" => "Bhutan", + "bo" => "Bolivia (Plurinational State of)", + "bq" => "Bonaire, Sint Eustatius and Saba", + "ba" => "Bosnia and Herzegovina", + "bw" => "Botswana", + "bv" => "Bouvet Island", + "br" => "Brazil", + "io" => "British Indian Ocean Territory", + "bn" => "Brunei Darussalam", + "bg" => "Bulgaria", + "bf" => "Burkina Faso", + "bi" => "Burundi", + "cv" => "Cabo Verde", + "kh" => "Cambodia", + "cm" => "Cameroon", + "ca" => "Canada", + "ky" => "Cayman Islands", + "cf" => "Central African Republic", + "td" => "Chad", + "cl" => "Chile", + "cn" => "China", + "cx" => "Christmas Island", + "cc" => "Cocos (Keeling) Islands", + "co" => "Colombia", + "km" => "Comoros", + "cg" => "Congo", + "cd" => "Congo (Democratic Republic of the)", + "ck" => "Cook Islands", + "cr" => "Costa Rica", + "ci" => "Côte d'Ivoire", + "hr" => "Croatia", + "cu" => "Cuba", + "cw" => "Curaçao", + "cy" => "Cyprus", + "cz" => "Czechia", + "dk" => "Denmark", + "dj" => "Djibouti", + "dm" => "Dominica", + "do" => "Dominican Republic", + "ec" => "Ecuador", + "eg" => "Egypt", + "sv" => "El Salvador", + "gq" => "Equatorial Guinea", + "er" => "Eritrea", + "ee" => "Estonia", + "et" => "Ethiopia", + "fk" => "Falkland Islands (Malvinas)", + "fo" => "Faroe Islands", + "fj" => "Fiji", + "fi" => "Finland", + "fr" => "France", + "gf" => "French Guiana", + "pf" => "French Polynesia", + "tf" => "French Southern Territories", + "ga" => "Gabon", + "gm" => "Gambia", + "ge" => "Georgia", + "de" => "Germany", + "gh" => "Ghana", + "gi" => "Gibraltar", + "gr" => "Greece", + "gl" => "Greenland", + "gd" => "Grenada", + "gp" => "Guadeloupe", + "gu" => "Guam", + "gt" => "Guatemala", + "gg" => "Guernsey", + "gn" => "Guinea", + "gw" => "Guinea-Bissau", + "gy" => "Guyana", + "ht" => "Haiti", + "hm" => "Heard Island and McDonald Islands", + "va" => "Holy See", + "hn" => "Honduras", + "hk" => "Hong Kong", + "hu" => "Hungary", + "is" => "Iceland", + "in" => "India", + "id" => "Indonesia", + "ir" => "Iran (Islamic Republic of)", + "iq" => "Iraq", + "ie" => "Ireland", + "im" => "Isle of Man", + "il" => "Israel", + "it" => "Italy", + "jm" => "Jamaica", + "jp" => "Japan", + "je" => "Jersey", + "jo" => "Jordan", + "kz" => "Kazakhstan", + "ke" => "Kenya", + "ki" => "Kiribati", + "kp" => "Korea (Democratic People's Republic of)", + "kr" => "Korea (Republic of)", + "kw" => "Kuwait", + "kg" => "Kyrgyzstan", + "la" => "Lao People's Democratic Republic", + "lv" => "Latvia", + "lb" => "Lebanon", + "ls" => "Lesotho", + "lr" => "Liberia", + "ly" => "Libya", + "li" => "Liechtenstein", + "lt" => "Lithuania", + "lu" => "Luxembourg", + "mo" => "Macao", + "mk" => "Macedonia (the former Yugoslav Republic of)", + "mg" => "Madagascar", + "mw" => "Malawi", + "my" => "Malaysia", + "mv" => "Maldives", + "ml" => "Mali", + "mt" => "Malta", + "mh" => "Marshall Islands", + "mq" => "Martinique", + "mr" => "Mauritania", + "mu" => "Mauritius", + "yt" => "Mayotte", + "mx" => "Mexico", + "fm" => "Micronesia (Federated States of)", + "md" => "Moldova (Republic of)", + "mc" => "Monaco", + "mn" => "Mongolia", + "me" => "Montenegro", + "ms" => "Montserrat", + "ma" => "Morocco", + "mz" => "Mozambique", + "mm" => "Myanmar", + "na" => "Namibia", + "nr" => "Nauru", + "np" => "Nepal", + "nl" => "Netherlands", + "nc" => "New Caledonia", + "nz" => "New Zealand", + "ni" => "Nicaragua", + "ne" => "Niger", + "ng" => "Nigeria", + "nu" => "Niue", + "nf" => "Norfolk Island", + "mp" => "Northern Mariana Islands", + "no" => "Norway", + "om" => "Oman", + "pk" => "Pakistan", + "pw" => "Palau", + "ps" => "Palestine, State of", + "pa" => "Panama", + "pg" => "Papua New Guinea", + "py" => "Paraguay", + "pe" => "Peru", + "ph" => "Philippines", + "pn" => "Pitcairn", + "pl" => "Poland", + "pt" => "Portugal", + "pr" => "Puerto Rico", + "qa" => "Qatar", + "re" => "Réunion", + "ro" => "Romania", + "ru" => "Russian Federation", + "rw" => "Rwanda", + "bl" => "Saint Barthélemy", + "sh" => "Saint Helena, Ascension and Tristan da Cunha", + "kn" => "Saint Kitts and Nevis", + "lc" => "Saint Lucia", + "mf" => "Saint Martin (French part)", + "pm" => "Saint Pierre and Miquelon", + "vc" => "Saint Vincent and the Grenadines", + "ws" => "Samoa", + "sm" => "San Marino", + "st" => "Sao Tome and Principe", + "sa" => "Saudi Arabia", + "sn" => "Senegal", + "rs" => "Serbia", + "sc" => "Seychelles", + "sl" => "Sierra Leone", + "sg" => "Singapore", + "sx" => "Sint Maarten (Dutch part)", + "sk" => "Slovakia", + "si" => "Slovenia", + "sb" => "Solomon Islands", + "so" => "Somalia", + "za" => "South Africa", + "gs" => "South Georgia and South Sandwich Islands", + "ss" => "South Sudan", + "es" => "Spain", + "lk" => "Sri Lanka", + "sd" => "Sudan", + "sr" => "Suriname", + "sj" => "Svalbard and Jan Mayen", + "sz" => "Swaziland", + "se" => "Sweden", + "ch" => "Switzerland", + "sy" => "Syrian Arab Republic", + "tw" => "Taiwan", + "tj" => "Tajikistan", + "tz" => "Tanzania, United Republic of", + "th" => "Thailand", + "tl" => "Timor-Leste", + "tg" => "Togo", + "tk" => "Tokelau", + "to" => "Tonga", + "tt" => "Trinidad and Tobago", + "tn" => "Tunisia", + "tr" => "Turkey", + "tm" => "Turkmenistan", + "tc" => "Turks and Caicos Islands", + "tv" => "Tuvalu", + "ug" => "Uganda", + "ua" => "Ukraine", + "ae" => "United Arab Emirates", + "gb" => "United Kingdom", + "us" => "United States of America", + "um" => "United States Minor Outlying Islands", + "uy" => "Uruguay", + "uz" => "Uzbekistan", + "vu" => "Vanuatu", + "ve" => "Venezuela (Bolivarian Republic of)", + "vn" => "Viet Nam", + "vg" => "Virgin Islands (British)", + "vi" => "Virgin Islands (U.S.)", + "wf" => "Wallis and Futuna", + "eh" => "Western Sahara", + "ye" => "Yemen", + "zm" => "Zambia", + "zw" => "Zimbabwe" + ] + ], + "region" => [ + "display" => "Region", + "option" => [ + "any" => "Any region", + "eu" => "European Union", + "de" => "Germany", + "fr" => "France", + "uk" => "United Kingdom" + ] + ], + "domain" => [ + "display" => "Results per domain", + "option" => [ + "1" => "1 result", + "2" => "2 results", + "3" => "3 results", + "4" => "4 results", + "5" => "5 results", + "10" => "10 results", + "0" => "Unlimited", + ] + ] + ]; + break; + + case "news": + return []; + } + } + + private function get($proxy, $url, $get = []){ + + $headers = [ + "User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1" + ]; + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function web($get){ + + if($get["npt"]){ + + [$token, $proxy] = $this->backend->get($get["npt"], "web"); + + try{ + $html = + $this->get( + $proxy, + "https://www.mojeek.com" . $token, + [] + ); + }catch(Exception $error){ + + throw new Exception("Failed to get HTML"); + } + + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + $lang = $get["lang"]; + $country = $get["country"]; + $region = $get["region"]; + $domain = $get["domain"]; + $focus = $get["focus"]; + + $params = [ + "q" => $search, + "t" => 20, // number of results/page + "tn" => 7, // number of news results/page + "date" => 1, // show date + "tlen" => 128, // max length of title + //"dlen" => 511, // max length of description + "arc" => ($country == "any" ? "none" : $country) // location. don't use autodetect! + ]; + + switch($focus){ + + case "any": break; + + case "blogs": + $params["fmt"] = "sst"; + $params["sst"] = "1"; + break; + + default: + $params["foc_t"] = $focus; + break; + } + + if($lang != "any"){ + + $params["lb"] = $lang; + } + + if($region != "any"){ + + $params["reg"] = $region; + } + + if($domain != "1"){ + + $params["si"] = $domain; + } + + try{ + $html = + $this->get( + $proxy, + "https://www.mojeek.com/search", + $params + ); + }catch(Exception $error){ + + throw new Exception("Failed to get HTML"); + } + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + $this->fuckhtml->load($html); + + $this->detect_block(); + + $results = + $this->fuckhtml + ->getElementsByClassName("results-standard", "ul"); + + if(count($results) === 0){ + + return $out; + } + + /* + Get all search result divs + */ + foreach($results as $container){ + + $this->fuckhtml->load($container); + $results = + $this->fuckhtml + ->getElementsByTagName("li"); + + foreach($results as $result){ + + $data = [ + "title" => null, + "description" => null, + "url" => null, + "date" => null, + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => [], + "table" => [] + ]; + + $this->fuckhtml->load($result); + + $title = + $this->fuckhtml + ->getElementsByClassName("title", "a")[0]; + + $data["title"] = + html_entity_decode( + $this->fuckhtml + ->getTextContent( + $title["innerHTML"] + ) + ); + + $data["url"] = + html_entity_decode( + $this->fuckhtml + ->getTextContent( + $title["attributes"]["href"] + ) + ); + + $description = + $this->fuckhtml + ->getElementsByClassName( + "s", "p" + ); + + if(count($description) !== 0){ + + $data["description"] = + $this->titledots( + html_entity_decode( + $this->fuckhtml + ->getTextContent( + $description[0] + ) + ) + ); + } + + $date = + $this->fuckhtml + ->getElementsByClassName( + "mdate", + "span" + ); + + if(count($date) !== 0){ + + $data["date"] = + strtotime( + $this->fuckhtml + ->getTextContent( + $date[0] + ) + ); + } + + $out["web"][] = $data; + } + } + + /* + Get instant answers + */ + $this->fuckhtml->load($html); + + $infoboxes = + $this->fuckhtml + ->getElementsByClassName( + "infobox infobox-top", + "div" + ); + + foreach($infoboxes as $infobox){ + + $answer = [ + "title" => null, + "description" => [], + "url" => null, + "thumb" => null, + "table" => [], + "sublink" => [] + ]; + + // load first part with title + short definition + $infobox_html = + explode( + "<hr>", + $infobox["innerHTML"] + ); + + $this->fuckhtml->load($infobox_html[0]); + + // title + $answer["title"] = + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByTagName("h1")[0] + ); + + // short definition + $definition = + $this->fuckhtml + ->getElementsByTagName( + "p" + ); + + if(count($definition) !== 0){ + + $answer["description"][] = [ + "type" => "quote", + "value" => + $this->fuckhtml + ->getTextContent( + $definition[0] + ) + ]; + } + + // get thumbnail, if it exists + $this->fuckhtml->load($infobox_html[1]); + + $thumb = + $this->fuckhtml + ->getElementsByClassName("float-right", "img"); + + if(count($thumb) !== 0){ + + preg_match( + '/\/image\?img=([^&]+)/i', + $thumb[0]["attributes"]["src"], + $matches + ); + + if(count($matches) === 2){ + + // for some reason, if we dont get the image from mojeek + // it sometimes fail to fetch the right image URL + $answer["thumb"] = + "https://mojeek.com" . + $this->fuckhtml + ->getTextContent( + $thumb[0]["attributes"]["src"] + ); + } + } + + // get description + $ps = + $this->fuckhtml + ->getElementsByTagName("p"); + + $first_tag = true; + foreach($ps as $p){ + + $this->fuckhtml->load($p); + + if( + preg_match( + '/^\s*<strong>/i', + $p["innerHTML"] + ) + ){ + + /* + Parse table + */ + + $strong = + $this->fuckhtml + ->getElementsByTagName("strong")[0]; + + $p["innerHTML"] = + str_replace($strong["innerHTML"], "", $p["innerHTML"]); + + $strong = + preg_replace( + '/:$/', + "", + ucfirst( + $this->fuckhtml + ->getTextContent( + $strong + ) + ) + ); + + $answer["table"][trim($strong)] = + trim( + $this->fuckhtml + ->getTextContent( + $p + ) + ); + + continue; + } + + $as = + $this->fuckhtml + ->getElementsByClassName("svg-icon"); + + if(count($as) !== 0){ + + /* + Parse websites + */ + foreach($as as $a){ + + $answer["sublink"][ + ucfirst(explode(" ", $a["attributes"]["class"], 2)[1]) + ] = + $this->fuckhtml + ->getTextContent( + $a["attributes"]["href"] + ); + } + + continue; + } + + /* + Parse text content + */ + $tags = + $this->fuckhtml + ->getElementsByTagName("*"); + + $i = 0; + foreach($tags as $tag){ + + $c = count($answer["description"]); + + // remove tag from innerHTML + $p["innerHTML"] = + explode($tag["outerHTML"], $p["innerHTML"], 2); + + if(count($p["innerHTML"]) === 2){ + + if( + $i === 0 && + $c !== 0 && + $answer["description"][$c - 1]["type"] == "link" + ){ + + $append = "\n\n"; + }else{ + + $append = ""; + } + + if($p["innerHTML"][0] != ""){ + $answer["description"][] = [ + "type" => "text", + "value" => $append . trim($p["innerHTML"][0]) + ]; + } + + $p["innerHTML"] = $p["innerHTML"][1]; + }else{ + + $p["innerHTML"] = $p["innerHTML"][0]; + } + + switch($tag["tagName"]){ + + case "a": + + $value = + $this->fuckhtml + ->getTextContent( + $tag + ); + + if(strtolower($value) == "wikipedia"){ + + if($c !== 0){ + $answer["description"][$c - 1]["value"] = + rtrim($answer["description"][$c - 1]["value"]); + } + break; + } + + $answer["description"][] = [ + "type" => "link", + "url" => + $this->fuckhtml + ->getTextContent( + $tag["attributes"]["href"] + ), + "value" => + $this->fuckhtml + ->getTextContent( + $tag + ) + ]; + break; + } + + $i++; + } + } + + // get URL + $this->fuckhtml->load($infobox_html[2]); + + $answer["url"] = + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByTagName( + "a" + )[0] + ["attributes"] + ["href"] + ); + + // append answer + $out["answer"][] = $answer; + } + + /* + Get news + */ + $this->fuckhtml->load($html); + + $news = + $this->fuckhtml + ->getElementsByClassName( + "results news-results", + "div" + ); + + if(count($news) !== 0){ + + $this->fuckhtml->load($news[0]); + + $lis = + $this->fuckhtml + ->getElementsByTagName("li"); + + foreach($lis as $li){ + + $this->fuckhtml->load($li); + + $a = + $this->fuckhtml + ->getElementsByClassName( + "ob", + "a" + ); + + if(count($a) === 0){ + + continue; + } + + $a = $a[0]; + + $date = + explode( + " - ", + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByTagName( + "span" + )[0] + ) + ); + + $date = + strtotime( + $date[count($date) - 1] + ); + + $out["news"][] = [ + "title" => + html_entity_decode( + $this->fuckhtml + ->getTextContent( + $a + ) + ), + "description" => null, + "date" => $date, + "thumb" => [ + "url" => null, + "ratio" => null + ], + "url" => + $this->fuckhtml + ->getTextContent( + $a["attributes"]["href"] + ) + ]; + } + } + + /* + Get next page + */ + $this->fuckhtml->load($html); + + $pagination = + $this->fuckhtml + ->getElementsByClassName("pagination"); + + if(count($pagination) !== false){ + + $this->fuckhtml->load($pagination[0]); + $as = + $this->fuckhtml + ->getElementsByTagName("a"); + + foreach($as as $a){ + + if($a["innerHTML"] == "Next"){ + + $out["npt"] = $this->backend->store( + $this->fuckhtml + ->getTextContent( + $a["attributes"]["href"] + ), + "web", + $proxy + ); + } + } + } + + return $out; + } + + public function news($get){ + + $search = $get["s"]; + + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "news" => [] + ]; + + try{ + $html = + $this->get( + $this->backend->get_ip(), + "https://www.mojeek.com/search", + [ + "q" => $search, + "fmt" => "news" + ] + ); + }catch(Exception $error){ + + throw new Exception("Failed to get HTML"); + } + /* + $handle = fopen("scraper/mojeek.html", "r"); + $html = fread($handle, filesize("scraper/mojeek.html")); + fclose($handle); + */ + + $this->fuckhtml->load($html); + + $this->detect_block(); + + $articles = + $this->fuckhtml->getElementsByTagName("article"); + + foreach($articles as $article){ + + $this->fuckhtml->load($article); + + $data = [ + "title" => null, + "author" => null, + "description" => null, + "date" => null, + "thumb" => + [ + "url" => null, + "ratio" => null + ], + "url" => null + ]; + + $a = $this->fuckhtml->getElementsByTagName("a")[0]; + + $data["title"] = + $this->fuckhtml + ->getTextContent( + $a["attributes"]["title"] + ); + + $data["url"] = + $this->fuckhtml + ->getTextContent( + $a["attributes"]["href"] + ); + + $p = $this->fuckhtml->getElementsByTagName("p"); + + $data["description"] = + $this->titledots( + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByClassName( + "s", + $p + )[0] + ) + ); + + if($data["description"] == ""){ + + $data["description"] = null; + } + + // get date from big node + $date = + $this->fuckhtml + ->getElementsByClassName( + "date", + $p + ); + + if(count($date) !== 0){ + + $data["date"] = + strtotime( + $this->fuckhtml + ->getTextContent( + $date[0] + ) + ); + } + + // grep date + author + $s = + $this->fuckhtml + ->getElementsByClassName( + "i", + $p + )[0]; + + $this->fuckhtml->load($s); + + $a = + $this->fuckhtml + ->getElementsByTagName("a"); + + if(count($a) !== 0){ + + // parse big node information + $data["author"] = + htmlspecialchars_decode( + $this->fuckhtml + ->getTextContent( + $a[0]["innerHTML"] + ) + ); + }else{ + + // parse smaller nodes + $replace = + $this->fuckhtml + ->getElementsByTagName("time")[0]; + + $data["date"] = + strtotime( + $this->fuckhtml + ->getTextContent( + $replace + ) + ); + + $s["innerHTML"] = + str_replace( + $replace["outerHTML"], + "", + $s["innerHTML"] + ); + + $data["author"] = + preg_replace( + '/ • $/', + "", + $s["innerHTML"] + ); + } + + $out["news"][] = $data; + } + + return $out; + } + + private function detect_block(){ + + $title = + $this->fuckhtml + ->getElementsByTagName( + "title" + ); + + if( + count($title) !== 0 && + $this->fuckhtml + ->getTextContent( + $title[0]["innerHTML"] + ) == "403 - Forbidden" + ){ + + throw new Exception("Mojeek blocked this instance or request proxy."); + } + } + + private function titledots($title){ + + return trim($title, ". \t\n\r\0\x0B"); + } +} + diff --git a/scraper/mwmbl.php b/scraper/mwmbl.php new file mode 100644 index 0000000..631b90c --- /dev/null +++ b/scraper/mwmbl.php @@ -0,0 +1,236 @@ +<?php + +class mwmbl{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("mwmbl"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + return []; + } + + private function get($proxy, $url, $get = []){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + // use http2 + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Referer: https://beta.mwmbl.org/", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: same-origin", + "Priority: u=0, i", + "Sec-Fetch-User: ?1"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function web($get){ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + try{ + $html = $this->get( + $this->backend->get_ip(), // no next page! + "https://beta.mwmbl.org/", + [ + "q" => $search + ] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch HTML. If you're getting a timeout, make sure you have curl-impersonate setup."); + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + $this->fuckhtml->load($html); + + $results = + $this->fuckhtml + ->getElementsByClassName( + "result", + "li" + ); + + foreach($results as $result){ + + $this->fuckhtml->load($result); + + $p = + $this->fuckhtml + ->getElementsByTagName("p"); + + $sublinks = []; + + $mores = + $this->fuckhtml + ->getElementsByClassName( + "result-link-more", + "div" + ); + + foreach($mores as $more){ + + $this->fuckhtml->load($more); + + $as = + $this->fuckhtml + ->getElementsByClassName( + "more", + "a" + ); + + if(count($as) === 0){ + + // ?? invalid + continue; + } + + $sublinks[] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByClassName( + "more-title", + "span" + )[0] + ) + ), + "description" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByClassName( + "more-extract", + "span" + )[0] + ) + ), + "url" => + $this->fuckhtml + ->getTextContent( + $as[0] + ["attributes"] + ["href"] + ) + ]; + } + + // reset + $this->fuckhtml->load($result); + + $out["web"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByClassName( + "title", + $p + )[0] + ) + ), + "description" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByClassName( + "extract", + $p + )[0] + ) + ), + "url" => + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByTagName("a") + [0] + ["attributes"] + ["href"] + ), + "date" => null, + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => $sublinks, + "table" => [] + ]; + } + + return $out; + } + + private function titledots($title){ + + return rtrim($title, "…"); + } +} diff --git a/scraper/pinterest.php b/scraper/pinterest.php new file mode 100644 index 0000000..4188bce --- /dev/null +++ b/scraper/pinterest.php @@ -0,0 +1,439 @@ +<?php + +class pinterest{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("pinterest"); + } + + public function getfilters($page){ + + return []; + } + + private function get($proxy, $url, $get = [], &$cookies, $header_data_post = null){ + + $curlproc = curl_init(); + + if($header_data_post === null){ + + // handling GET + + // extract cookies + $cookies_tmp = []; + curl_setopt($curlproc, CURLOPT_HEADERFUNCTION, function($curlproc, $header) use (&$cookies_tmp){ + + $length = strlen($header); + + $header = explode(":", $header, 2); + + if(trim(strtolower($header[0])) == "set-cookie"){ + + $cookie_tmp = explode("=", trim($header[1]), 2); + + $cookies_tmp[trim($cookie_tmp[0])] = + explode(";", $cookie_tmp[1], 2)[0]; + } + + return $length; + }); + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: application/json, text/javascript, */*, q=0.01", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Referer: https://ca.pinterest.com/", + "X-Requested-With: XMLHttpRequest", + "X-APP-VERSION: 78f8764", + "X-Pinterest-AppState: active", + "X-Pinterest-Source-Url: /", + "X-Pinterest-PWS-Handler: www/index.js", + "screen-dpr: 1", + "is-preload-enabled: 1", + "DNT: 1", + "Sec-GPC: 1", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-origin", + "Connection: keep-alive", + "Alt-Used: ca.pinterest.com", + "Priority: u=0", + "TE: trailers"] + ); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + }else{ + + // handling POST (pagination) + $get = http_build_query($get); + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: application/json, text/javascript, */*, q=0.01", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Content-Type: application/x-www-form-urlencoded", + "Content-Length: " . strlen($get), + "Referer: https://ca.pinterest.com/", + "X-Requested-With: XMLHttpRequest", + "X-APP-VERSION: 78f8764", + "X-CSRFToken: " . $cookies["csrf"], + "X-Pinterest-AppState: active", + "X-Pinterest-Source-Url: /search/pins/?rs=ac&len=2&q=" . urlencode($header_data_post) . "&eq=" . urlencode($header_data_post), + "X-Pinterest-PWS-Handler: www/search/[scope].js", + "screen-dpr: 1", + "is-preload-enabled: 1", + "Origin: https://ca.pinterest.com", + "DNT: 1", + "Sec-GPC: 1", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-origin", + "Connection: keep-alive", + "Alt-Used: ca.pinterest.com", + "Cookie: " . $cookies["cookie"], + "TE: trailers"] + ); + + curl_setopt($curlproc, CURLOPT_POST, true); + curl_setopt($curlproc, CURLOPT_POSTFIELDS, $get); + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + // http2 bypass + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + if($header_data_post === null){ + + if(!isset($cookies_tmp["csrftoken"])){ + + throw new Exception("Failed to grep CSRF token"); + } + + $cookies = ""; + + foreach($cookies_tmp as $cookie_name => $cookie_value){ + + $cookies .= $cookie_name . "=" . $cookie_value . "; "; + } + + $cookies = [ + "csrf" => $cookies_tmp["csrftoken"], + "cookie" => rtrim($cookies, " ;") + ]; + } + + curl_close($curlproc); + return $data; + } + + public function image($get){ + + if($get["npt"]){ + + [$data, $proxy] = + $this->backend->get( + $get["npt"], "images" + ); + + $data = json_decode($data, true); + + $search = $data["q"]; + $cookies = $data["cookies"]; + + try{ + $json = + $this->get( + $proxy, + "https://ca.pinterest.com/resource/BaseSearchResource/get/", + [ + "source_url" => "/search/pins/?q=" . urlencode($search) . "&rs=typed", + "data" => json_encode( + [ + "options" => [ + "applied_unified_filters" => null, + "appliedProductFilters" => "---", + "article" => null, + "auto_correction_disabled" => false, + "corpus" => null, + "customized_rerank_type" => null, + "domains" => null, + "dynamicPageSizeExpGroup" => null, + "filters" => null, + "journey_depth" => null, + "page_size" => null, + "price_max" => null, + "price_min" => null, + "query_pin_sigs" => null, + "query" => $data["q"], + "redux_normalize_feed" => true, + "request_params" => null, + "rs" => "typed", + "scope" => "pins", + "selected_one_bar_modules" => null, + "source_id" => null, + "source_module_id" => null, + "source_url" => "/search/pins/?q=" . urlencode($search) . "&rs=typed", + "top_pin_id" => null, + "top_pin_ids" => null, + "bookmarks" => [ + $data["bookmark"] + ] + ], + "context" => [] + ], + JSON_UNESCAPED_SLASHES + ) + ], + $cookies, + $search + ); + + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + // https://ca.pinterest.com/resource/BaseSearchResource/get/?source_url=%2Fsearch%2Fpins%2F%3Feq%3Dhigurashi%26etslf%3D5966%26len%3D2%26q%3Dhigurashi%2520when%2520they%2520cry%26rs%3Dac&data=%7B%22options%22%3A%7B%22applied_unified_filters%22%3Anull%2C%22appliedProductFilters%22%3A%22---%22%2C%22article%22%3Anull%2C%22auto_correction_disabled%22%3Afalse%2C%22corpus%22%3Anull%2C%22customized_rerank_type%22%3Anull%2C%22domains%22%3Anull%2C%22dynamicPageSizeExpGroup%22%3Anull%2C%22filters%22%3Anull%2C%22journey_depth%22%3Anull%2C%22page_size%22%3Anull%2C%22price_max%22%3Anull%2C%22price_min%22%3Anull%2C%22query_pin_sigs%22%3Anull%2C%22query%22%3A%22higurashi%20when%20they%20cry%22%2C%22redux_normalize_feed%22%3Atrue%2C%22request_params%22%3Anull%2C%22rs%22%3A%22ac%22%2C%22scope%22%3A%22pins%22%2C%22selected_one_bar_modules%22%3Anull%2C%22source_id%22%3Anull%2C%22source_module_id%22%3Anull%2C%22source_url%22%3A%22%2Fsearch%2Fpins%2F%3Feq%3Dhigurashi%26etslf%3D5966%26len%3D2%26q%3Dhigurashi%2520when%2520they%2520cry%26rs%3Dac%22%2C%22top_pin_id%22%3Anull%2C%22top_pin_ids%22%3Anull%7D%2C%22context%22%3A%7B%7D%7D&_=1736116313987 + // source_url=%2Fsearch%2Fpins%2F%3Feq%3Dhigurashi%26etslf%3D5966%26len%3D2%26q%3Dhigurashi%2520when%2520they%2520cry%26rs%3Dac + // &data=%7B%22options%22%3A%7B%22applied_unified_filters%22%3Anull%2C%22appliedProductFilters%22%3A%22---%22%2C%22article%22%3Anull%2C%22auto_correction_disabled%22%3Afalse%2C%22corpus%22%3Anull%2C%22customized_rerank_type%22%3Anull%2C%22domains%22%3Anull%2C%22dynamicPageSizeExpGroup%22%3Anull%2C%22filters%22%3Anull%2C%22journey_depth%22%3Anull%2C%22page_size%22%3Anull%2C%22price_max%22%3Anull%2C%22price_min%22%3Anull%2C%22query_pin_sigs%22%3Anull%2C%22query%22%3A%22higurashi%20when%20they%20cry%22%2C%22redux_normalize_feed%22%3Atrue%2C%22request_params%22%3Anull%2C%22rs%22%3A%22ac%22%2C%22scope%22%3A%22pins%22%2C%22selected_one_bar_modules%22%3Anull%2C%22source_id%22%3Anull%2C%22source_module_id%22%3Anull%2C%22source_url%22%3A%22%2Fsearch%2Fpins%2F%3Feq%3Dhigurashi%26etslf%3D5966%26len%3D2%26q%3Dhigurashi%2520when%2520they%2520cry%26rs%3Dac%22%2C%22top_pin_id%22%3Anull%2C%22top_pin_ids%22%3Anull%7D%2C%22context%22%3A%7B%7D%7D + // &_=1736116313987 + + $source_url = "/search/pins/?q=" . urlencode($search) . "&rs=" . urlencode($search); + + $filter = [ + "source_url" => $source_url, + "rs" => "typed", + "data" => + json_encode( + [ + "options" => [ + "applied_unified_filters" => null, + "appliedProductFilters" => "---", + "article" => null, + "corpus" => null, + "customized_rerank_type" => null, + "domains" => null, + "dynamicPageSizeExpGroup" => null, + "filters" => null, + "journey_depth" => null, + "page_size" => null, + "price_max" => null, + "price_min" => null, + "query_pin_sigs" => null, + "query" => $search, + "redux_normalize_feed" => true, + "request_params" => null, + "rs" => "ac", + "scope" => "pins", // pins, boards, videos, + "selected_one_bar_modules" => null, + "source_id" => null, + "source_module_id" => null, + "source_url" => $source_url, + "top_pin_id" => null, + "top_pin_ids" => null + ], + "context" => [] + ] + ), + "_" => substr(str_replace(".", "", (string)microtime(true)), 0, -1) + ]; + + $proxy = $this->backend->get_ip(); + $cookies = []; + + try{ + $json = + $this->get( + $proxy, + "https://ca.pinterest.com/resource/BaseSearchResource/get/", + $filter, + $cookies, + null + ); + + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + } + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + if( + !isset( + $json["resource_response"] + ["status"] + ) + ){ + + throw new Exception("Unknown API failure"); + } + + if($json["resource_response"]["status"] != "success"){ + + $status = "Got non-OK response: " . $json["resource_response"]["status"]; + + if( + isset( + $json["resource_response"]["message"] + ) + ){ + + $status .= " - " . $json["resource_response"]["message"]; + } + + throw new Exception($status); + } + + if( + isset( + $json["resource_response"]["sensitivity"] + ["notices"][0]["description"]["text"] + ) + ){ + + throw new Exception( + "Pinterest returned a notice: " . + $json["resource_response"]["sensitivity"]["notices"][0]["description"]["text"] + ); + } + + // get NPT + if(isset($json["resource_response"]["bookmark"])){ + + $out["npt"] = + $this->backend->store( + json_encode([ + "q" => $search, + "bookmark" => $json["resource_response"]["bookmark"], + "cookies" => $cookies + ]), + "images", + $proxy + ); + } + + foreach( + $json + ["resource_response"] + ["data"] + ["results"] + as $item + ){ + + switch($item["type"]){ + + case "pin": + case "board": + + /* + Handle image object + */ + $images = array_values($item["images"]); + $image = &$images[count($images) - 1]; // original + $thumb = &$images[1]; // 236x + + $title = []; + + if( + isset($item["grid_title"]) && + trim($item["grid_title"]) != "" + ){ + + $title[] = $item["grid_title"]; + } + + if( + isset($item["description"]) && + trim($item["description"]) != "" + ){ + + $title[] = $item["description"]; + } + + $title = implode(": ", $title); + + if( + $title == "" && + isset($item["board"]["name"]) && + trim($item["board"]["name"]) != "" + ){ + + $title = $item["board"]["name"]; + } + + if($title == ""){ + + $title = null; + } + + $out["image"][] = [ + "title" => $title, + "source" => [ + [ + "url" => $image["url"], + "width" => (int)$image["width"], + "height" => (int)$image["height"] + ], + [ + "url" => $thumb["url"], + "width" => (int)$thumb["width"], + "height" => (int)$thumb["height"] + ] + ], + "url" => + $item["link"] === null ? + "https://ca.pinterest.com/pin/" . $item["id"] : + $item["link"] + ]; + break; + } + } + + return $out; + } +} diff --git a/scraper/qwant.php b/scraper/qwant.php new file mode 100644 index 0000000..ecbd4ec --- /dev/null +++ b/scraper/qwant.php @@ -0,0 +1,993 @@ +<?php + +class qwant{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("qwant"); + } + + public function getfilters($page){ + + $base = [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "maybe" => "Maybe", + "no" => "No" + ] + ], + "country" => [ + "display" => "Country", + "option" => [ + "en_US" => "United States", + "fr_FR" => "France", + "en_GB" => "Great Britain", + "de_DE" => "Germany", + "it_IT" => "Italy", + "es_AR" => "Argentina", + "en_AU" => "Australia", + "es_ES" => "Spain (es)", + "ca_ES" => "Spain (ca)", + "cs_CZ" => "Czech Republic", + "ro_RO" => "Romania", + "el_GR" => "Greece", + "zh_CN" => "China", + "zh_HK" => "Hong Kong", + "en_NZ" => "New Zealand", + "fr_FR" => "France", + "th_TH" => "Thailand", + "ko_KR" => "South Korea", + "sv_SE" => "Sweden", + "nb_NO" => "Norway", + "da_DK" => "Denmark", + "hu_HU" => "Hungary", + "et_EE" => "Estonia", + "es_MX" => "Mexico", + "es_CL" => "Chile", + "en_CA" => "Canada (en)", + "fr_CA" => "Canada (fr)", + "en_MY" => "Malaysia", + "bg_BG" => "Bulgaria", + "fi_FI" => "Finland", + "pl_PL" => "Poland", + "nl_NL" => "Netherlands", + "pt_PT" => "Portugal", + "de_CH" => "Switzerland (de)", + "fr_CH" => "Switzerland (fr)", + "it_CH" => "Switzerland (it)", + "de_AT" => "Austria", + "fr_BE" => "Belgium (fr)", + "nl_BE" => "Belgium (nl)", + "en_IE" => "Ireland", + "he_IL" => "Israel" + ] + ] + ]; + + switch($page){ + + case "web": + $base = array_merge( + $base, + [ + "time" => [ + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "day" => "Past 24 hours", + "week" => "Past week", + "month" => "Past month" + ] + ], + "extendedsearch" => [ + // no display, wont show in interface + "option" => [ + "yes" => "Yes", + "no" => "No" + ] + ] + ] + ); + break; + + case "images": + $base = array_merge( + $base, + [ + "time" => [ + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "day" => "Past 24 hours", + "week" => "Past week", + "month" => "Past month" + ] + ], + "size" => [ + "display" => "Size", + "option" => [ + "any" => "Any size", + "large" => "Large", + "medium" => "Medium", + "small" => "Small" + ] + ], + "color" => [ + "display" => "Color", + "option" => [ + "any" => "Any color", + "coloronly" => "Color only", + "monochrome" => "Monochrome", + "black" => "Black", + "brown" => "Brown", + "gray" => "Gray", + "white" => "White", + "yellow" => "Yellow", + "orange" => "Orange", + "red" => "Red", + "pink" => "Pink", + "purple" => "Purple", + "blue" => "Blue", + "teal" => "Teal", + "green" => "Green" + ] + ], + "imagetype" => [ + "display" => "Type", + "option" => [ + "any" => "Any type", + "animatedgif" => "Animated GIF", + "photo" => "Photograph", + "transparent" => "Transparent" + ] + ], + "license" => [ + "display" => "License", + "option" => [ + "any" => "Any license", + "share" => "Non-commercial reproduction and sharing", + "sharecommercially" => "Reproduction and sharing", + "modify" => "Non-commercial reproduction, sharing and modification", + "modifycommercially" => "Reproduction, sharing and modification", + "public" => "Public domain" + ] + ] + ] + ); + break; + + case "videos": + $base = array_merge( + $base, + [ + "order" => [ + "display" => "Order by", + "option" => [ + "relevance" => "Relevance", + "views" => "Views", + "date" => "Most recent", + ] + ], + "source" => [ + "display" => "Source", + "option" => [ + "any" => "Any source", + "youtube" => "YouTube", + "dailymotion" => "Dailymotion", + ] + ] + ] + ); + break; + + case "news": + $base = array_merge( + $base, + [ + "time" => [ + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "hour" => "Less than 1 hour ago", + "day" => "Past 24 hours", + "week" => "Past week", + "month" => "Past month" + ] + ], + "order" => [ + "display" => "Order by", + "option" => [ + "relevance" => "Relevance", + "date" => "Most recent" + ] + ] + ] + ); + break; + } + + return $base; + } + + private function get($proxy, $url, $get = []){ + + $headers = [ + "User-Agent: " . config::USER_AGENT, + "Accept: application/json, text/plain, */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Connection: keep-alive", + "Origin: https://www.qwant.com", + "Referer: https://www.qwant.com/", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-site", + "TE: trailers" + ]; + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers); + + // Bypass HTTP/2 check + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + + return $data; + } + + public function web($get){ + + if($get["npt"]){ + + // get next page data + [$params, $proxy] = $this->backend->get($get["npt"], "web"); + + $params = json_decode($params, true); + + }else{ + + // get _GET data instead + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + if(strlen($search) > 2048){ + + throw new Exception("Search term is too long!"); + } + + $proxy = $this->backend->get_ip(); + + $params = [ + "q" => $search, + "freshness" => $get["time"], + "count" => 10, + "locale" => $get["country"], + "offset" => 0, + "device" => "desktop", + "tgp" => 3, + "safesearch" => 0, + "displayed" => "true" + ]; + + switch($get["nsfw"]){ + + case "yes": $params["safesearch"] = 0; break; + case "maybe": $params["safesearch"] = 1; break; + case "no": $params["safesearch"] = 2; break; + } + } + /* + $handle = fopen("scraper/qwant_web.json", "r"); + $json = fread($handle, filesize("scraper/qwant_web.json")); + fclose($handle);*/ + + try{ + $json = + $this->get( + $proxy, + "https://fdn.qwant.com/v3/search/web", + $params + ); + + }catch(Exception $error){ + + throw new Exception("Could not fetch JSON"); + } + + $json = json_decode($json, true); + + if($json === NULL){ + + throw new Exception("Failed to decode JSON"); + } + + if(isset($json["data"]["message"][0])){ + + throw new Exception("Server returned an error:\n" . $json["data"]["message"][0]); + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + if( + $json["status"] != "success" && + $json["data"]["error_code"] === 5 + ){ + + // no results + return $out; + } + + $this->detect_errors($json); + + if(!isset($json["data"]["result"]["items"]["mainline"])){ + + throw new Exception("Server did not return a result object"); + } + + // data is OK, parse + + // get instant answer + if( + $get["extendedsearch"] == "yes" && + isset($json["data"]["result"]["items"]["sidebar"][0]["endpoint"]) + ){ + + try{ + $answer = + $this->get( + $proxy, + "https://api.qwant.com/v3" . + $json["data"]["result"]["items"]["sidebar"][0]["endpoint"], + [] + ); + + $answer = json_decode($answer, true); + + if( + $answer === null || + $answer["status"] != "success" || + $answer["data"]["result"] === null + ){ + + throw new Exception(); + } + + // parse answer + $out["answer"][] = [ + "title" => $answer["data"]["result"]["title"], + "description" => [ + [ + "type" => "text", + "value" => $this->trimdots($answer["data"]["result"]["description"]) + ] + ], + "url" => $answer["data"]["result"]["url"], + "thumb" => + $answer["data"]["result"]["thumbnail"]["landscape"] == null ? + null : + $this->unshitimage($answer["data"]["result"]["thumbnail"]["landscape"]), + "table" => [], + "sublink" => [] + ]; + + }catch(Exception $error){ + + // do nothing in case of failure + } + + } + + // get word correction + if(isset($json["data"]["query"]["queryContext"]["alteredQuery"])){ + + $out["spelling"] = [ + "type" => "including", + "using" => $json["data"]["query"]["queryContext"]["alteredQuery"], + "correction" => $json["data"]["query"]["queryContext"]["alterationOverrideQuery"] + ]; + } + + // check for next page + if($json["data"]["result"]["lastPage"] === false){ + + $params["offset"] = $params["offset"] + 10; + + $out["npt"] = + $this->backend->store( + json_encode($params), + "web", + $proxy + ); + } + + // parse results + foreach($json["data"]["result"]["items"]["mainline"] as $item){ + + switch($item["type"]){ // ignores ads + + case "web": + + $first_iteration = true; + foreach($item["items"] as $result){ + + if(isset($result["thumbnailUrl"])){ + + $thumb = [ + "url" => $this->unshitimage($result["thumbnailUrl"]), + "ratio" => "16:9" + ]; + }else{ + + $thumb = [ + "url" => null, + "ratio" => null + ]; + } + + $sublinks = []; + if(isset($result["links"])){ + + foreach($result["links"] as $link){ + + $sublinks[] = [ + "title" => $this->trimdots($link["title"]), + "date" => null, + "description" => isset($link["desc"]) ? $this->trimdots($link["desc"]) : null, + "url" => $link["url"] + ]; + } + } + + // detect gibberish results + if( + $first_iteration && + !isset($result["urlPingSuffix"]) + ){ + + throw new Exception("Qwant returned gibberish results"); + } + + $out["web"][] = [ + "title" => $this->trimdots($result["title"]), + "description" => $this->trimdots($result["desc"]), + "url" => $result["url"], + "date" => null, + "type" => "web", + "thumb" => $thumb, + "sublink" => $sublinks, + "table" => [] + ]; + + $first_iteration = false; + } + break; + + case "images": + foreach($item["items"] as $image){ + + $out["image"][] = [ + "title" => $image["title"], + "source" => [ + [ + "url" => $image["media"], + "width" => (int)$image["width"], + "height" => (int)$image["height"] + ], + [ + "url" => $this->unshitimage($image["thumbnail"]), + "width" => $image["thumb_width"], + "height" => $image["thumb_height"] + ] + ], + "url" => $image["url"] + ]; + } + break; + + case "videos": + foreach($item["items"] as $video){ + + $out["video"][] = [ + "title" => $video["title"], + "description" => null, + "date" => (int)$video["date"], + "duration" => $video["duration"] === null ? null : $video["duration"] / 1000, + "views" => null, + "thumb" => + $video["thumbnail"] === null ? + [ + "url" => null, + "ratio" => null, + ] : + [ + "url" => $this->unshitimage($video["thumbnail"]), + "ratio" => "16:9", + ], + "url" => $video["url"] + ]; + } + break; + + case "related_searches": + foreach($item["items"] as $related){ + + $out["related"][] = $related["text"]; + } + break; + } + } + + return $out; + } + + + public function image($get){ + + if($get["npt"]){ + + [$params, $proxy] = + $this->backend->get( + $get["npt"], + "images" + ); + + $params = json_decode($params, true); + }else{ + + $search = $get["s"]; + + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + + $params = [ + "t" => "images", + "q" => $search, + "count" => 125, + "locale" => $get["country"], + "offset" => 0, // increment by 125 + "device" => "desktop", + "tgp" => 3 + ]; + + if($get["time"] != "any"){ + + $params["freshness"] = $get["time"]; + } + + foreach(["size", "color", "imagetype", "license"] as $p){ + + if($get[$p] != "any"){ + + $params[$p] = $get[$p]; + } + } + + switch($get["nsfw"]){ + + case "yes": $params["safesearch"] = 0; break; + case "maybe": $params["safesearch"] = 1; break; + case "no": $params["safesearch"] = 2; break; + } + } + + try{ + $json = $this->get( + $proxy, + "https://api.qwant.com/v3/search/images", + $params, + ); + }catch(Exception $err){ + + throw new Exception("Failed to get JSON"); + } + + /* + $handle = fopen("scraper/yandex.json", "r"); + $json = fread($handle, filesize("scraper/yandex.json")); + fclose($handle);*/ + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + $this->detect_errors($json); + + if(isset($json["data"]["result"]["items"]["mainline"])){ + + throw new Exception("Qwant returned gibberish results"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + if($json["data"]["result"]["lastPage"] === false){ + + $params["offset"] = $params["offset"] + 125; + + $out["npt"] = $this->backend->store( + json_encode($params), + "images", + $proxy + ); + } + + foreach($json["data"]["result"]["items"] as $image){ + + $out["image"][] = [ + "title" => $this->trimdots($image["title"]), + "source" => [ + [ + "url" => $image["media"], + "width" => $image["width"], + "height" => $image["height"] + ], + [ + "url" => $this->unshitimage($image["thumbnail"]), + "width" => $image["thumb_width"], + "height" => $image["thumb_height"] + ] + ], + "url" => $image["url"] + ]; + } + + return $out; + } + + public function video($get){ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $params = [ + "t" => "videos", + "q" => $search, + "count" => 50, + "locale" => $get["country"], + "offset" => 0, // dont implement pagination + "device" => "desktop", + "tgp" => 3 + ]; + + switch($get["nsfw"]){ + + case "yes": $params["safesearch"] = 0; break; + case "maybe": $params["safesearch"] = 1; break; + case "no": $params["safesearch"] = 2; break; + } + + try{ + $json = + $this->get( + $this->backend->get_ip(), + "https://api.qwant.com/v3/search/videos", + $params + ); + }catch(Exception $error){ + + throw new Exception("Could not fetch JSON"); + } + + /* + $handle = fopen("scraper/yandex-video.json", "r"); + $json = fread($handle, filesize("scraper/yandex-video.json")); + fclose($handle); + */ + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Could not parse JSON"); + } + + $this->detect_errors($json); + + if(isset($json["data"]["result"]["items"]["mainline"])){ + + throw new Exception("Qwant returned gibberish results"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + foreach($json["data"]["result"]["items"] as $video){ + + if(empty($video["thumbnail"])){ + + $thumb = [ + "url" => null, + "ratio" => null + ]; + }else{ + + $thumb = [ + "url" => $this->unshitimage($video["thumbnail"]), + "ratio" => "16:9" + ]; + } + + $duration = (int)$video["duration"]; + + $out["video"][] = [ + "title" => $video["title"], + "description" => $this->limitstrlen($video["desc"]), + "author" => [ + "name" => $video["channel"], + "url" => null, + "avatar" => null + ], + "date" => (int)$video["date"], + "duration" => $duration === 0 ? null : $duration, + "views" => null, + "thumb" => $thumb, + "url" => preg_replace("/\?syndication=.+/", "", $video["url"]) + ]; + } + + return $out; + } + + public function news($get){ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $params = [ + "t" => "news", + "q" => $search, + "count" => 50, + "locale" => $get["country"], + "offset" => 0, // dont implement pagination + "device" => "desktop", + "tgp" => 3 + ]; + + switch($get["nsfw"]){ + + case "yes": $params["safesearch"] = 0; break; + case "maybe": $params["safesearch"] = 1; break; + case "no": $params["safesearch"] = 2; break; + } + + try{ + $json = + $this->get( + $this->backend->get_ip(), + "https://api.qwant.com/v3/search/news", + $params + ); + }catch(Exception $error){ + + throw new Exception("Could not fetch JSON"); + } + + /* + $handle = fopen("scraper/yandex-video.json", "r"); + $json = fread($handle, filesize("scraper/yandex-video.json")); + fclose($handle); + */ + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Could not parse JSON"); + } + + $this->detect_errors($json); + + if(isset($json["data"]["result"]["items"]["mainline"])){ + + throw new Exception("Qwant returned gibberish results"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "news" => [] + ]; + + foreach($json["data"]["result"]["items"] as $news){ + + if(empty($news["media"][0]["pict_big"]["url"])){ + + $thumb = [ + "url" => null, + "ratio" => null + ]; + }else{ + + $thumb = [ + "url" => $this->unshitimage($news["media"][0]["pict_big"]["url"]), + "ratio" => "16:9" + ]; + } + + $out["news"][] = [ + "title" => $news["title"], + "author" => $news["press_name"], + "description" => $this->trimdots($news["desc"]), + "date" => (int)$news["date"], + "thumb" => $thumb, + "url" => $news["url"] + ]; + } + + return $out; + } + + private function detect_errors($json){ + + if( + isset($json["status"]) && + $json["status"] == "error" + ){ + + if(isset($json["data"]["error_data"]["captchaUrl"])){ + + throw new Exception("Qwant returned a captcha"); + }elseif(isset($json["data"]["error_data"]["error_code"])){ + + throw new Exception( + "Qwant returned an API error: " . + $json["data"]["error_data"]["error_code"] + ); + } + + throw new Exception("Qwant returned an API error"); + } + } + + private function limitstrlen($text){ + + return explode("\n", wordwrap($text, 300, "\n"))[0]; + } + + private function trimdots($text){ + + return trim($text, ". "); + } + + private function unshitimage($url){ + + // https://s1.qwant.com/thumbr/0x0/8/d/f6de4deb2c2b12f55d8bdcaae576f9f62fd58a05ec0feeac117b354d1bf5c2/th.jpg?u=https%3A%2F%2Fwww.bing.com%2Fth%3Fid%3DOIP.vvDWsagzxjoKKP_rOqhwrQAAAA%26w%3D160%26h%3D160%26c%3D7%26pid%3D5.1&q=0&b=1&p=0&a=0 + // https://s2.qwant.com/thumbr/474x289/7/f/412d13b3fe3a03eb2b89633c8e88b609b7d0b93cdd9a5e52db3c663e41e65e/th.jpg?u=https%3A%2F%2Ftse.mm.bing.net%2Fth%3Fid%3DOIP.9Tm_Eo6m7V7ltN19mxduDgHaEh%26pid%3DApi&q=0&b=1&p=0&a=0 + + $image = parse_url($url); + + if( + !isset($image["host"]) || + !isset($image["query"]) + ){ + + // cant do anything + return $url; + } + + $id = null; + + if( + preg_match( + '/s[0-9]+\.qwant\.com$/', + $image["host"] + ) + ){ + + parse_str($image["query"], $str); + + // we're being served a proxy URL + if(isset($str["u"])){ + + $bing_url = $str["u"]; + }else{ + + // give up + return $url; + } + } + + // parse bing URL + $id = null; + $image = parse_url($bing_url); + + if(isset($image["query"])){ + + parse_str($image["query"], $str); + + if(isset($str["id"])){ + + $id = $str["id"]; + } + } + + if($id === null){ + + $id = explode("/th/id/", $image["path"], 2); + + if(count($id) !== 2){ + + // malformed + return $url; + } + + $id = $id[1]; + } + + if(is_array($id)){ + + // fuck off, let proxy.php deal with it + return $url; + } + + return "https://" . $image["host"] . "/th?id=" . rawurlencode($id); + } +} diff --git a/scraper/sc.php b/scraper/sc.php new file mode 100644 index 0000000..7083c42 --- /dev/null +++ b/scraper/sc.php @@ -0,0 +1,512 @@ +<?php + +class sc{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("sc"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + return [ + "type" => [ + "display" => "Type", + "option" => [ + "any" => "Any type", + "track" => "Tracks", + "author" => "People", + "album" => "Albums", + "playlist" => "Playlists", + "goplus" => "Go+ Tracks" + ] + ] + ]; + } + + private function get($proxy, $url, $get = [], $web_req = false){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + // use http2 + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + if($web_req === false){ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Referer: https://soundcloud.com/", + "Origin: https://soundcloud.com", + "DNT: 1", + "Connection: keep-alive", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-site", + "Priority: u=1"] + ); + }else{ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: cross-site", + "Priority: u=1", + "TE: trailers"] + ); + } + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function music($get, $last_attempt = false){ + + if($get["npt"]){ + + [$params, $proxy] = $this->backend->get($get["npt"], "music"); + $params = json_decode($params, true); + + $url = $params["url"]; + unset($params["url"]); + + }else{ + + // normal search: + // https://api-v2.soundcloud.com/search?q=freddie%20dredd&variant_ids=&facet=model&user_id=351062-302234-707916-795081&client_id=iMxZgT5mfGstBj8GWJbYMvpzelS8ne0E&limit=20&offset=0&linked_partitioning=1&app_version=1693487844&app_locale=en + + // soundcloud go+ search: + // https://api-v2.soundcloud.com/search/tracks?q=freddie%20dredd&variant_ids=&filter.content_tier=SUB_HIGH_TIER&facet=genre&user_id=630591-269800-703400-765403&client_id=iMxZgT5mfGstBj8GWJbYMvpzelS8ne0E&limit=20&offset=0&linked_partitioning=1&app_version=1693487844&app_locale=en + + // tracks search: + // https://api-v2.soundcloud.com/search/tracks?q=freddie%20dredd&variant_ids=&facet=genre&user_id=630591-269800-703400-765403&client_id=iMxZgT5mfGstBj8GWJbYMvpzelS8ne0E&limit=20&offset=0&linked_partitioning=1&app_version=1693487844&app_locale=en + + // users search: + // https://api-v2.soundcloud.com/search/users?q=freddie%20dredd&variant_ids=&facet=place&user_id=630591-269800-703400-765403&client_id=iMxZgT5mfGstBj8GWJbYMvpzelS8ne0E&limit=20&offset=0&linked_partitioning=1&app_version=1693487844&app_locale=en + + // albums search: + // https://api-v2.soundcloud.com/search/albums?q=freddie%20dredd&variant_ids=&facet=genre&user_id=630591-269800-703400-765403&client_id=iMxZgT5mfGstBj8GWJbYMvpzelS8ne0E&limit=20&offset=0&linked_partitioning=1&app_version=1693487844&app_locale=en + + // playlists search: + // https://api-v2.soundcloud.com/search/playlists_without_albums?q=freddie%20dredd&variant_ids=&facet=genre&user_id=630591-269800-703400-765403&client_id=iMxZgT5mfGstBj8GWJbYMvpzelS8ne0E&limit=20&offset=0&linked_partitioning=1&app_version=1693487844&app_locale=en + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $type = $get["type"]; + $proxy = $this->backend->get_ip(); + $token = $this->get_token($proxy); + + switch($type){ + + case "any": + $url = "https://api-v2.soundcloud.com/search"; + $params = [ + "q" => $search, + "variant_ids" => "", + "facet" => "model", + "client_id" => $token, + "limit" => 20, + "offset" => 0, + "linked_partitioning" => 1, + "app_version" => 1713542117, + "app_locale" => "en" + ]; + break; + + case "track": + $url = "https://api-v2.soundcloud.com/search/tracks"; + $params = [ + "q" => $search, + "variant_ids" => "", + "facet_genre" => "", + "client_id" => $token, + "limit" => 20, + "offset" => 0, + "linked_partitioning" => 1, + "app_version" => 1713542117, + "app_locale" => "en" + ]; + break; + + case "author": + $url = "https://api-v2.soundcloud.com/search/users"; + $params = [ + "q" => $search, + "variant_ids" => "", + "facet" => "place", + "client_id" => $token, + "limit" => 20, + "offset" => 0, + "linked_partitioning" => 1, + "app_version" => 1713542117, + "app_locale" => "en" + ]; + break; + + case "album": + $url = "https://api-v2.soundcloud.com/search/albums"; + $params = [ + "q" => $search, + "variant_ids" => "", + "facet" => "genre", + "client_id" => $token, + "limit" => 20, + "offset" => 0, + "linked_partitioning" => 1, + "app_version" => 1713542117, + "app_locale" => "en" + ]; + break; + + case "playlist": + $url = "https://api-v2.soundcloud.com/search/playlists_without_albums"; + $params = [ + "q" => $search, + "variant_ids" => "", + "facet" => "genre", + "client_id" => $token, + "limit" => 20, + "offset" => 0, + "linked_partitioning" => 1, + "app_version" => 1713542117, + "app_locale" => "en" + ]; + break; + + case "goplus": + $url = "https://api-v2.soundcloud.com/search/tracks"; + $params = [ + "q" => $search, + "variant_ids" => "", + "filter.content_tier" => "SUB_HIGH_TIER", + "facet" => "genre", + "client_id" => $token, + "limit" => 20, + "offset" => 0, + "linked_partitioning" => 1, + "app_version" => 1713542117, + "app_locale" => "en" + ]; + break; + } + } + + try{ + + $json = $this->get($proxy, $url, $params); + + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + /* + $handle = fopen("scraper/soundcloud.json", "r"); + $json = fread($handle, filesize("scraper/soundcloud.json")); + fclose($handle); + */ + + $json = json_decode($json, true); + + if($json === null){ + + if($last_attempt === true){ + + throw new Exception("Fetched an invalid token (please report!!)"); + } + + // token might've expired, get a new one and re-try search + $this->get_token($proxy); + return $this->music($get, true); + } + + $out = [ + "status" => "ok", + "npt" => null, + "song" => [], + "playlist" => [], + "album" => [], + "podcast" => [], + "author" => [], + "user" => [] + ]; + + /* + Get next page + */ + if(isset($json["next_href"])){ + + $params["query_urn"] = $json["query_urn"]; + $params["offset"] = $params["offset"] + 20; + $params["url"] = $url; // we will remove this later + + $out["npt"] = + $this->backend->store( + json_encode($params), + "music", + $proxy + ); + } + + /* + Scrape items + */ + foreach($json["collection"] as $item){ + + switch($item["kind"]){ + + case "user": + // parse author + $out["author"][] = [ + "title" => $item["username"], + "followers" => $item["followers_count"], + "description" => trim($item["track_count"] . " songs. " . $this->limitstrlen($item["description"])), + "thumb" => [ + "url" => $item["avatar_url"], + "ratio" => "1:1" + ], + "url" => $item["permalink_url"] + ]; + break; + + case "playlist": + // parse playlist + $description = []; + $count = 0; + + foreach($item["tracks"] as $song){ + + $count++; + + if(!isset($song["title"])){ + + continue; + } + + $description[] = $song["title"]; + } + + if(count($description) !== 0){ + + $description = trim($count . " songs. " . implode(", ", $description)); + }else{ + + $description = ""; + } + + if( + isset($item["artwork_url"]) && + !empty($item["artwork_url"]) + ){ + + $thumb = [ + "ratio" => "1:1", + "url" => $item["artwork_url"] + ]; + + }elseif( + isset($item["tracks"][0]["artwork_url"]) && + !empty($item["tracks"][0]["artwork_url"]) + ){ + + $thumb = [ + "ratio" => "1:1", + "url" => $item["tracks"][0]["artwork_url"] + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["playlist"][] = [ + "title" => $item["title"], + "description" => $this->limitstrlen($description), + "author" => [ + "name" => $item["user"]["username"], + "url" => $item["user"]["permalink_url"], + "avatar" => $item["user"]["avatar_url"] + ], + "thumb" => $thumb, + "date" => strtotime($item["created_at"]), + "duration" => $item["duration"] / 1000, + "url" => $item["permalink_url"] + ]; + break; + + case "track": + if(stripos($item["monetization_model"], "TIER") === false){ + + $stream = [ + "endpoint" => "sc", + "url" => + $item["media"]["transcodings"][0]["url"] . + "?client_id=" . $token . + "&track_authorization=" . + $item["track_authorization"] + ]; + }else{ + + $stream = [ + "endpoint" => null, + "url" => null + ]; + } + + // parse track + $out["song"][] = [ + "title" => $item["title"], + "description" => $item["description"] == "" ? null : $this->limitstrlen($item["description"]), + "url" => $item["permalink_url"], + "views" => $item["playback_count"], + "author" => [ + "name" => $item["user"]["username"], + "url" => $item["user"]["permalink_url"], + "avatar" => $item["user"]["avatar_url"] + ], + "thumb" => [ + "ratio" => "1:1", + "url" => $item["artwork_url"] + ], + "date" => strtotime($item["created_at"]), + "duration" => (int)$item["full_duration"] / 1000, + "stream" => $stream + ]; + break; + } + } + + return $out; + } + + public function get_token($proxy){ + + $token = apcu_fetch("sc_token"); + + if($token !== false){ + + return $token; + } + + // search through all javascript components on the main page + try{ + $html = + $this->get( + $proxy, + "https://soundcloud.com", + [], + true + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch front page"); + } + + $this->fuckhtml->load($html); + + $scripts = + $this->fuckhtml + ->getElementsByTagName( + "script" + ); + + foreach($scripts as $script){ + + if( + !isset($script["attributes"]["src"]) || + strpos($script["attributes"]["src"], "sndcdn.com") === false + ){ + + continue; + } + + try{ + $js = + $this->get( + $proxy, + $script["attributes"]["src"], + [] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search token"); + } + + preg_match( + '/client_id=([^"]+)/', + $js, + $token + ); + + if(isset($token[1])){ + + apcu_store("sc_token", $token[1]); + return $token[1]; + break; + } + } + + throw new Exception("Did not find a Soundcloud token in the Javascript blobs"); + } + + private function limitstrlen($text){ + + return + explode( + "\n", + wordwrap( + str_replace( + ["\n\r", "\r\n", "\n", "\r"], + " ", + $text + ), + 300, + "\n" + ), + 2 + )[0]; + } +} diff --git a/scraper/sepiasearch.php b/scraper/sepiasearch.php new file mode 100644 index 0000000..c59e12f --- /dev/null +++ b/scraper/sepiasearch.php @@ -0,0 +1,541 @@ +<?php + +class sepiasearch{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("sepiasearch"); + } + + public function getfilters($page){ + + return [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", // &sensitiveContent=both + "no" => "No" // &sensitiveContent=false + ] + ], + "language" => [ + "display" => "Language", // &language= + "option" => [ + "any" => "Any language", + "en" => "English", + "fr" => "Français", + "ar" => "العربية", + "ca" => "Català", + "cs" => "Čeština", + "de" => "Deutsch", + "el" => "ελληνικά", + "eo" => "Esperanto", + "es" => "Español", + "eu" => "Euskara", + "fa" => "فارسی", + "fi" => "Suomi", + "gd" => "Gàidhlig", + "gl" => "Galego", + "hr" => "Hrvatski", + "hu" => "Magyar", + "is" => "Íslenska", + "it" => "Italiano", + "ja" => "日本語", + "kab" => "Taqbaylit", + "nl" => "Nederlands", + "no" => "Norsk", + "oc" => "Occitan", + "pl" => "Polski", + "pt" => "Português (Brasil)", + "pt-PT" => "Português (Portugal)", + "ru" => "Pусский", + "sk" => "Slovenčina", + "sq" => "Shqip", + "sv" => "Svenska", + "th" => "ไทย", + "tok" => "Toki Pona", + "tr" => "Türkçe", + "uk" => "украї́нська мо́ва", + "vi" => "Tiếng Việt", + "zh-Hans" => "简体中文(中国)", + "zh-Hant" => "繁體中文(台灣)" + ] + ], + "type" => [ + "display" => "Result type", // i handle this + "option" => [ + "videos" => "Videos", + "playlists" => "Playlists", + "channels" => "Channels" + ] + ], + "sort" => [ + "display" => "Sort by", + "option" => [ + "best" => "Best match", // no filter + "-publishedAt" => "Newest", // sort=-publishedAt + "publishedAt" => "Oldest" // sort=publishedAt + ] + ], + "newer" => [ // &startDate=2025-07-26T04:00:00.000Z + "display" => "Newer than", + "option" => "_DATE" + ], + "duration" => [ + "display" => "Duration", + "option" => [ + "any" => "Any duration", + "short" => "Short (0-4mins)", // &durationRange=short + "medium" => "Medium (4-10 mins)", + "long" => "Long (10+ mins)", + ] + ], + "category" => [ + "display" => "Category", // &categoryOneOf[]= + "option" => [ + "any" => "Any category", + "1" => "Music", + "2" => "Films", + "3" => "Vehicles", + "4" => "Art", + "5" => "Sports", + "6" => "Travels", + "7" => "Gaming", + "8" => "People", + "9" => "Comedy", + "10" => "Entertainment", + "11" => "News & Politics", + "12" => "How To", + "13" => "Education", + "14" => "Activism", + "15" => "Science & Technology", + "16" => "Animals", + "17" => "Kids", + "18" => "Food" + ] + ], + "display" => [ + "display" => "Display", + "option" => [ + "any" => "Everything", + "true" => "Live videos", // &isLive=true + "false" => "VODs" // &isLive=false + ] + ], + "license" => [ + "display" => "License", // &license= + "option" => [ + "any" => "Any license", + "1" => "Attribution", + "2" => "Attribution - Share Alike", + "3" => "Attribution - No Derivatives", + "4" => "Attribution - Non Commercial", + "5" => "Attribution - Non Commercial - Share Alike", + "6" => "Attribution - Non Commercial - No Derivatives", + "7" => "Public Domain Dedication" + ] + ] + ]; + } + + private function get($proxy, $url, $get = []){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + curl_setopt( + $curlproc, + CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: application/json, text/plain, */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Referer: https://sepiasearch.org/search", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-origin", + "Priority: u=0", + "TE: trailers"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function video($get){ + + if($get["npt"]){ + + [$npt, $proxy] = + $this->backend + ->get( + $get["npt"], + "videos" + ); + + $npt = json_decode($npt, true); + $type = $npt["type"]; + $npt = $npt["npt"]; + }else{ + + $proxy = $this->backend->get_ip(); + + $npt = [ + "search" => $get["s"], + "start" => 0, + "count" => 20 + ]; + + if($get["type"] == "videos"){ + + // + // Parse video filters + // + switch($get["nsfw"]){ + + case "yes": $npt["nsfw"] = "both"; break; + case "no": $npt["nsfw"] = "false"; break; + } + + $npt["boostLanguages[]"] = "en"; + if($get["language"] != "any"){ + + $npt["languageOneOf[]"] = $get["language"]; + } + + if($get["sort"] != "best"){ + + $npt["sort"] = $get["sort"]; + } + + if($get["newer"] !== false){ + + $date = new DateTime("@{$get["newer"]}"); + $date->setTimezone(new DateTimeZone("UTC")); + $formatted = $date->format("Y-m-d\TH:i:s.000\Z"); + + $npt["startDate"] = $formatted; + } + + switch($get["duration"]){ + + case "short": + $npt["durationMax"] = 240; + break; + + case "medium": + $npt["durationMin"] = 240; + $npt["durationMax"] = 600; + break; + + case "long": + $npt["durationMin"] = 600; + break; + } + + if($get["category"] != "any"){ + + $npt["categoryOneOf[]"] = $get["category"]; + } + + if($get["display"] != "any"){ + + $npt["isLive"] = $get["display"]; + } + + if($get["license"] != "any"){ + + // typo in license, lol + $npt["licenceOneOf[]"] = $get["license"]; + } + } + + $type = $get["type"]; + } + + switch($type){ + + case "videos": + $url = "https://sepiasearch.org/api/v1/search/videos"; + break; + + case "channels": + $url = "https://sepiasearch.org/api/v1/search/video-channels"; + break; + + case "playlists": + $url = "https://sepiasearch.org/api/v1/search/video-playlists"; + break; + } + + //$json = file_get_contents("scraper/sepia.json"); + try{ + + $json = + $this->get( + $proxy, + $url, + $npt + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to parse JSON"); + } + + if(isset($json["errors"])){ + + $msg = []; + foreach($json["errors"] as $error){ + + if(isset($error["msg"])){ + + $msg[] = $error["msg"]; + } + } + + throw new Exception("Sepia Search returned error(s): " . implode(", ", $msg)); + } + + if(!isset($json["data"])){ + + throw new Exception("Sepia Search did not return a data object"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + + switch($get["type"]){ + + case "videos": + foreach($json["data"] as $video){ + + if(count($video["account"]["avatars"]) !== 0){ + + $avatar = + $video["account"]["avatars"][count($video["account"]["avatars"]) - 1]["url"]; + }else{ + + $avatar = null; + } + + if($video["thumbnailUrl"] === null){ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + }else{ + + $thumb = [ + "ratio" => "16:9", + "url" => $video["thumbnailUrl"] + ]; + } + + if($video["isLive"]){ + + $append = "livestream"; + }else{ + + $append = "video"; + } + + $out[$append][] = [ + "title" => $video["name"], + "description" => + $this->limitstrlen( + $this->titledots( + $video["description"] + ) + ), + "author" => [ + "name" => $video["account"]["displayName"] . " ({$video["account"]["name"]})", + "url" => $video["account"]["url"], + "avatar" => $avatar + ], + "date" => strtotime($video["publishedAt"]), + "duration" => $video["isLive"] ? "_LIVE" : $video["duration"], + "views" => $video["views"], + "thumb" => $thumb, + "url" => $video["url"] + ]; + } + break; + + case "playlists": + foreach($json["data"] as $playlist){ + + if(count($playlist["ownerAccount"]["avatars"]) !== 0){ + + $avatar = + $playlist["ownerAccount"]["avatars"][count($playlist["ownerAccount"]["avatars"]) - 1]["url"]; + }else{ + + $avatar = null; + } + + if($playlist["thumbnailUrl"] === null){ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + }else{ + + $thumb = [ + "ratio" => "16:9", + "url" => $playlist["thumbnailUrl"] + ]; + } + + $out["playlist"][] = [ + "title" => $playlist["displayName"], + "description" => + $this->limitstrlen( + $this->titledots( + $playlist["description"] + ) + ), + "author" => [ + "name" => $playlist["ownerAccount"]["displayName"] . " ({$playlist["ownerAccount"]["name"]})", + "url" => $playlist["ownerAccount"]["url"], + "avatar" => $avatar + ], + "date" => strtotime($playlist["createdAt"]), + "duration" => $playlist["videosLength"], + "views" => null, + "thumb" => $thumb, + "url" => $playlist["url"] + ]; + } + break; + + case "channels": + foreach($json["data"] as $channel){ + + if(count($channel["avatars"]) !== 0){ + + $thumb = [ + "ratio" => "1:1", + "url" => $channel["avatars"][count($channel["avatars"]) - 1]["url"] + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["author"][] = [ + "title" => $channel["displayName"] . " ({$channel["name"]})", + "followers" => $channel["followersCount"], + "description" => + $channel["videosCount"] . " videos. " . + $this->limitstrlen( + $this->titledots( + $channel["description"] + ) + ), + "thumb" => $thumb, + "url" => $channel["url"] + ]; + } + break; + } + + // get next page + if($json["total"] - 20 > $npt["start"]){ + + $npt["start"] += 20; + + $npt = [ + "type" => $get["type"], + "npt" => $npt + ]; + + $out["npt"] = + $this->backend + ->store( + json_encode($npt), + "videos", + $proxy + ); + } + + return $out; + } + + private function titledots($title){ + + $substr = substr($title, -3); + + if( + $substr == "..." || + $substr == "…" + ){ + + return trim(substr($title, 0, -3), " \n\r\t\v\x00\0\x0B\xc2\xa0"); + } + + return trim($title, " \n\r\t\v\x00\0\x0B\xc2\xa0"); + } + + private function limitstrlen($text){ + + return + explode( + "\n", + wordwrap( + str_replace( + ["\n\r", "\r\n", "\n", "\r"], + " ", + $text + ), + 300, + "\n" + ), + 2 + )[0]; + } +} diff --git a/scraper/solofield.php b/scraper/solofield.php new file mode 100644 index 0000000..4fe10e4 --- /dev/null +++ b/scraper/solofield.php @@ -0,0 +1,668 @@ +<?php + +class solofield{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("solofield"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + return [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "no" => "No", + ] + ] + ]; + } + + private function get($proxy, $url, $get = []){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Referer: https://solofield.net", + "DNT: 1", + "Connection: keep-alive", + "Cookie: cross-site-cookie=name; lno=35842050", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: same-origin", + "Sec-Fetch-User: ?1"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function web($get){ + + if($get["npt"]){ + + [$query, $proxy] = $this->backend->get($get["npt"], "web"); + + try{ + + $html = + $this->get( + $proxy, + "https://solofield.net/search?" . $query, + [] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + }else{ + + $proxy = $this->backend->get_ip(); + + try{ + + $html = + $this->get( + $proxy, + "https://solofield.net/search", + [ + "q" => $get["s"], + "ie" => "UTF-8", + "oe" => "UTF-8", + "hl" => "ja", // changing this doesnt do anything + "lr" => "lang_ja", // same here + //"ls" => "", // ?? + "f" => ($get["nsfw"] == "yes" ? "off" : "on") + ] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + // check for errors and load the result div + if($this->error_and_load($html)){ + + return $out; + } + + $items = + $this->fuckhtml + ->getElementsByClassName( + "g0", + "li" + ); + + foreach($items as $item){ + + $this->fuckhtml->load($item); + + $title_tag = + $this->fuckhtml + ->getElementsByClassName( + "r", + "h3" + ); + + if(count($title_tag) === 0){ + + continue; + } + + $this->fuckhtml->load($title_tag[0]); + + $link = + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByTagName( + "a" + )[0] + ["attributes"] + ["href"] + ); + + $this->fuckhtml->load($item); + $thumb = + $this->fuckhtml + ->getElementsByClassName( + "webshot", + "img" + ); + + if(count($thumb) !== 0){ + + $uri = + $this->fuckhtml + ->getTextContent( + $thumb[0] + ["attributes"] + ["src"] + ); + + if(stripos($uri, "now_printing") === false){ + + $thumb = [ + "ratio" => "1:1", + "url" => + "https://solofield.net" . + $this->fuckhtml + ->getTextContent( + $thumb[0] + ["attributes"] + ["src"] + ) + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["web"][] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $title_tag[0] + ), + "description" => + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByClassName( + "s", + "div" + )[0] + ), + "url" => $link, + "date" => null, + "type" => "web", + "thumb" => $thumb, + "sublink" => [], + "table" => [] + ]; + } + + // get next page + $this->get_npt($html, $proxy, $out, "web"); + + return $out; + } + + + public function image($get){ + + // no pagination + $html = + $this->get( + $this->backend->get_ip(), + "https://solofield.net/isearch", + [ + "q" => $get["s"], + "ie" => "UTF-8", + "oe" => "UTF-8", + "hl" => "ja", // changing this doesnt do anything + //"lr" => "lang_ja", // same here + "ls" => "", // ?? + "f" => ($get["nsfw"] == "yes" ? "off" : "on") + ] + ); + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + // check for errors and load the result div + if($this->error_and_load($html)){ + + return $out; + } + + $images = + $this->fuckhtml + ->getElementsByTagName( + "li" + ); + + foreach($images as $image){ + + $this->fuckhtml->load($image); + + $img = + $this->fuckhtml + ->getElementsByTagName( + "img" + ); + + if(count($img) === 0){ + + // ?? invalid + continue; + } + + $img = $img[0]; + + $size = + explode( + "x", + $this->fuckhtml + ->getTextContent( + $image + ), + 2 + ); + + $size = [ + (int)trim($size[0]), // width + (int)trim($size[1]) // height + ]; + + $out["image"][] = [ + "title" => null, + "source" => [ + [ + "url" => + "https://solofield.net/" . + $this->fuckhtml + ->getTextContent( + $img["attributes"]["src"] + ), + "width" => $size[0], + "height" => $size[1] + ] + ], + "url" => + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByTagName( + "a" + )[0] + ["attributes"] + ["href"] + ) + ]; + } + + return $out; + } + + + public function video($get){ + + if($get["npt"]){ + + [$query, $proxy] = $this->backend->get($get["npt"], "videos"); + + try{ + + $html = + $this->get( + $proxy, + "https://solofield.net/vsearch?" . $query, + [] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + }else{ + + $proxy = $this->backend->get_ip(); + + try{ + + $html = + $this->get( + $proxy, + "https://solofield.net/vsearch", + [ + "q" => $get["s"], + "ie" => "UTF-8", + "oe" => "UTF-8", + "hl" => "ja", // changing this doesnt do anything + //"lr" => "lang_ja", // same here + "ls" => "", // ?? + "f" => ($get["nsfw"] == "yes" ? "off" : "on") + ] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + } + + $out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + // check for errors and load the result div + if($this->error_and_load($html)){ + + return $out; + } + + $items = + $this->fuckhtml + ->getElementsByTagName( + "li" + ); + + foreach($items as $item){ + + $this->fuckhtml->load($item); + + $as = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + if(count($as) === 0){ + + continue; + } + + $thumb = + $this->fuckhtml + ->getElementsByTagName( + "img" + ); + + if(count($thumb) !== 0){ + + $thumb = [ + "ratio" => "16:9", + "url" => + "https://solofield.net/" . + $thumb[0] + ["attributes"] + ["src"] + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $date = + $this->fuckhtml + ->getElementsByAttributeValue( + "style", + "font-size: 10px;", + "span" + ); + + if(count($date) !== 0){ + + $date = + $this->unfuckdate( + $this->fuckhtml + ->getTextContent( + $date[0] + ) + ); + }else{ + + $date = null; + } + + $center_td = + $this->fuckhtml + ->getElementsByAttributeValue( + "align", + "center", + "td" + ); + + if(count($center_td) === 2){ + + $duration = + $this->fuckhtml + ->getTextContent( + $this->hms2int( + $center_td[0] + ) + ); + }else{ + + $duration = null; + } + + $out["video"][] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $as[1] + ), + "description" => null, + "author" => [ + "name" => null, + "url" => null, + "avatar" => null + ], + "date" => $date, + "duration" => $duration, + "views" => null, + "thumb" => $thumb, + "url" => + $this->fuckhtml + ->getTextContent( + $as[0] + ["attributes"] + ["href"] + ) + ]; + } + + // get next page + $this->get_npt($html, $proxy, $out, "videos"); + + return $out; + } + + + private function get_npt($html, $proxy, &$out, $type){ + + // get next page + $this->fuckhtml->load($html); + + $pjs = + $this->fuckhtml + ->getElementById( + "pjs" + ); + + if($pjs){ + + $alnk = + $this->fuckhtml + ->getElementsByClassName( + "alnk", + "span" + ); + + foreach($alnk as $lnk){ + + if( + stripos( + $this->fuckhtml + ->getTextContent( + $lnk + ), + "Next" + ) !== false + ){ + + $this->fuckhtml->load($lnk); + + $out["npt"] = + $this->backend->store( + parse_url( + $this->fuckhtml + ->getElementsByTagName( + "a" + )[0] + ["attributes"] + ["href"], + PHP_URL_QUERY + ), + $type, + $proxy + ); + } + } + } + } + + private function error_and_load($html){ + + if(strlen($html) === 0){ + + throw new Exception("Solofield blocked the request IP"); + } + + $this->fuckhtml->load($html); + + $list = + $this->fuckhtml + ->getElementById( + "list", + "div" + ); + + if($list === false){ + + $nosearch = + $this->fuckhtml + ->getElementById( + "nosearch", + "div" + ); + + if($nosearch){ + + return true; + } + + throw new Exception("Failed to grep search list"); + } + + $this->fuckhtml->load($list); + return false; + } + + private function unfuckdate($date){ + + return + strtotime( + rtrim( + preg_replace( + '/[^0-9]+/', + "-", + explode( + ":", + $date, + 2 + )[1] + ), + "-" + ) + ); + } + + private function hms2int($time){ + + $parts = explode(":", $time, 3); + $time = 0; + + if(count($parts) === 3){ + + // hours + $time = $time + ((int)$parts[0] * 3600); + array_shift($parts); + } + + if(count($parts) === 2){ + + // minutes + $time = $time + ((int)$parts[0] * 60); + array_shift($parts); + } + + // seconds + $time = $time + (int)$parts[0]; + + return $time; + } +} diff --git a/scraper/spotify.php b/scraper/spotify.php new file mode 100644 index 0000000..79f61a6 --- /dev/null +++ b/scraper/spotify.php @@ -0,0 +1,726 @@ +<?php + +class spotify{ + + private const req_web = 0; + private const req_api = 1; + private const req_clientid = 2; + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("spotify"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + return [ + "category" => [ + "display" => "Category", + "option" => [ + "any" => "All (no pagination)", + "audiobooks" => "Audiobooks", + "tracks" => "Songs", + "artists" => "Artists", + "playlists" => "Playlists", + "albums" => "Albums", + "podcastAndEpisodes" => "Podcasts & Shows (no pagination)", + "episodes" => "Episodes", + "users" => "Profiles" + ] + ] + ]; + } + + private function get($proxy, $url, $get = [], $reqtype = self::req_web, $bearer = null, $token = null){ + + $curlproc = curl_init(); + + switch($reqtype){ + + case self::req_api: + $headers = [ + "User-Agent: " . config::USER_AGENT, + "Accept: application/json", + "Accept-Language: en", + "app-platform: WebPlayer", + "authorization: Bearer {$bearer}", + "client-token: {$token}", + "content-type: application/json;charset=UTF-8", + "Origin: https://open.spotify.com", + "Referer: https://open.spotify.com/", + "DNT: 1", + "Connection: keep-alive", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-site", + "spotify-app-version: 1.2.27.93.g7aee53d4", + "TE: trailers" + ]; + break; + + case self::req_web: + $headers = [ + "User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: cross-site" + ]; + break; + + case self::req_clientid: + $get = json_encode($get); + + curl_setopt($curlproc, CURLOPT_POST, true); + curl_setopt($curlproc, CURLOPT_POSTFIELDS, $get); + + $headers = [ + "User-Agent:" . config::USER_AGENT, + "Accept: application/json", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br", + "Referer: https://open.spotify.com/", + "content-type: application/json", + "Content-Length: " . strlen($get), + "Origin: https://open.spotify.com", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-site", + "TE: trailers" + ]; + break; + } + + if($reqtype !== self::req_clientid){ + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function music($get){ + + $search = $get["s"]; + $ip = $this->backend->get_ip(); + $category = $get["category"]; + + /* + audiobooks first and second page decoded + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchAudiobooks&variables={"searchTerm":"freddie+dredd","offset":0,"limit":30,"numberOfTopResults":20,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"8758e540afdba5afa3c5246817f6bd31d86a15b3f5666c363dd017030f35d785"}} + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchAudiobooks&variables={"searchTerm":"freddie+dredd","offset":30,"limit":30,"numberOfTopResults":20,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"8758e540afdba5afa3c5246817f6bd31d86a15b3f5666c363dd017030f35d785"}} + */ + + /* + songs + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchTracks&variables={"searchTerm":"asmr","offset":0,"limit":100,"numberOfTopResults":20,"includeAudiobooks":false}&extensions={"persistedQuery":{"version":1,"sha256Hash":"16c02d6304f5f721fc2eb39dacf2361a4543815112506a9c05c9e0bc9733a679"}} + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchTracks&variables={"searchTerm":"asmr","offset":100,"limit":100,"numberOfTopResults":20,"includeAudiobooks":false}&extensions={"persistedQuery":{"version":1,"sha256Hash":"16c02d6304f5f721fc2eb39dacf2361a4543815112506a9c05c9e0bc9733a679"}} + */ + + /* + artists + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchArtists&variables={"searchTerm":"asmr","offset":0,"limit":30,"numberOfTopResults":20,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"b8840daafdda9a9ceadb7c5774731f63f9eca100445d2d94665f2dc58b45e2b9"}} + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchArtists&variables={"searchTerm":"asmr","offset":30,"limit":23,"numberOfTopResults":20,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"b8840daafdda9a9ceadb7c5774731f63f9eca100445d2d94665f2dc58b45e2b9"}} + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchArtists&variables={"searchTerm":"asmr","offset":53,"limit":30,"numberOfTopResults":20,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"b8840daafdda9a9ceadb7c5774731f63f9eca100445d2d94665f2dc58b45e2b9"}} + */ + + /* + playlists + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchPlaylists&variables={"searchTerm":"asmr","offset":0,"limit":30,"numberOfTopResults":20,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"19b4143a0500ccec189ca0f4a0316bc2c615ecb51ce993ba4d7d08afd1d87aa4"}} + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchPlaylists&variables={"searchTerm":"asmr","offset":30,"limit":3,"numberOfTopResults":20,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"19b4143a0500ccec189ca0f4a0316bc2c615ecb51ce993ba4d7d08afd1d87aa4"}} + */ + + /* + albums + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchAlbums&variables={"searchTerm":"asmr","offset":33,"limit":30,"numberOfTopResults":20,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"e93b13cda461482da2940467eb2beed9368e9bb2fff37df3fb6633fc61271a27"}} + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchAlbums&variables={"searchTerm":"asmr","offset":33,"limit":30,"numberOfTopResults":20,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"e93b13cda461482da2940467eb2beed9368e9bb2fff37df3fb6633fc61271a27"}} + */ + + /* + podcasts & shows (contains authors, no pagination) + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchFullEpisodes&variables={"searchTerm":"asmr","offset":0,"limit":30}&extensions={"persistedQuery":{"version":1,"sha256Hash":"9f996251c9781fabce63f1a9980b5287ea33bc5e8c8953d0c4689b09936067a1"}} + */ + + /* + episodes + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchDesktop&variables={"searchTerm":"asmr","offset":0,"limit":10,"numberOfTopResults":5,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"da03293d92a2cfc5e24597dcdc652c0ad135e1c64a78fddbf1478a7e096bea44"}} + ??? https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchFullEpisodes&variables={"searchTerm":"asmr","offset":60,"limit":30}&extensions={"persistedQuery":{"version":1,"sha256Hash":"9f996251c9781fabce63f1a9980b5287ea33bc5e8c8953d0c4689b09936067a1"}} + */ + + /* + profiles + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchUsers&variables={"searchTerm":"asmr","offset":0,"limit":30,"numberOfTopResults":20,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"02026f48ab5001894e598904079b620ebc64f2d53b55ca20c3858abd3a46c5fb"}} + https://api-partner.spotify.com/pathfinder/v1/query?operationName=searchUsers&variables={"searchTerm":"asmr","offset":30,"limit":30,"numberOfTopResults":20,"includeAudiobooks":true}&extensions={"persistedQuery":{"version":1,"sha256Hash":"02026f48ab5001894e598904079b620ebc64f2d53b55ca20c3858abd3a46c5fb"}} + */ + + // get HTML + try{ + + $html = + $this->get( + $ip, + "https://open.spotify.com/search/" . + rawurlencode($search) . + ($category != "any" ? "/" . $category : ""), + [] + ); + }catch(Exception $error){ + + throw new Exception("Failed to get initial search page"); + } + + // grep bearer and client ID + $this->fuckhtml->load($html); + + $script = + $this->fuckhtml + ->getElementById( + "session", + "script" + ); + + if($script === null){ + + throw new Exception("Failed to grep bearer token"); + } + + $script = + json_decode( + $script["innerHTML"], + true + ); + + $bearer = $script["accessToken"]; + $client_id = $script["clientId"]; + + // hit client ID endpoint + try{ + + $token = + json_decode( + $this->get( + $ip, + "https://clienttoken.spotify.com/v1/clienttoken", + [ // !! that shit must be sent as json data + "client_data" => [ + "client_id" => $client_id, + "client_version" => "1.2.27.93.g7aee53d4", + "js_sdk_data" => [ + "device_brand" => "unknown", + "device_id" => "4c7ca20117ca12288ea8fc7118a9118c", + "device_model" => "unknown", + "device_name" => "computer", + "os" => "windows", + "os_version" => "NT 10.0" + ] + ] + ], + self::req_clientid + ), + true + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch token"); + } + + if($token === null){ + + throw new Exception("Failed to decode token"); + } + + $token = $token["granted_token"]["token"]; + + try{ + + switch($get["option"]){ + + case "any": + $variables = [ + "searchTerm" => $search, + "offset" => 0, + "limit" => 10, + "numberOfTopResults" => 5, + "includeAudiobooks" => true + ]; + break; + + case "audiobooks": + + break; + } + + $payload = + $this->get( + $ip, + "https://api-partner.spotify.com/pathfinder/v1/query", + [ + "operationName" => "searchDesktop", + "variables" => + json_encode( + [ + "searchTerm" => $search, + "offset" => 0, + "limit" => 10, + "numberOfTopResults" => 5, + "includeAudiobooks" => true + ] + ), + "extensions" => + json_encode( + [ + "persistedQuery" => [ + "version" => 1, + "sha256Hash" => "21969b655b795601fb2d2204a4243188e75fdc6d3520e7b9cd3f4db2aff9591e" // ? + ] + ] + ) + ], + self::req_api, + $bearer, + $token + ); + + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON results"); + } + + if($payload == "Token expired"){ + + throw new Exception("Grepped spotify token has expired"); + } + + $payload = json_decode($payload, true); + + if($payload === null){ + + throw new Exception("Failed to decode JSON results"); + } + + //$payload = json_decode(file_get_contents("scraper/spotify.json"), true); + + $out = [ + "status" => "ok", + "npt" => null, + "song" => [], + "playlist" => [], + "album" => [], + "podcast" => [], + "author" => [], + "user" => [] + ]; + + // get songs + foreach($payload["data"]["searchV2"]["tracksV2"]["items"] as $result){ + + if(isset($result["item"])){ + + $result = $result["item"]; + } + + if(isset($result["data"])){ + + $result = $result["data"]; + } + + [$artist, $artist_link] = $this->get_artists($result["artists"]); + + $out["song"][] = [ + "title" => $result["name"], + "description" => null, + "url" => "https://open.spotify.com/track/" . $result["id"], + "views" => null, + "author" => [ + "name" => $artist, + "url" => $artist_link, + "avatar" => null + ], + "thumb" => $this->get_thumb($result["albumOfTrack"]["coverArt"]), + "date" => null, + "duration" => $result["duration"]["totalMilliseconds"] / 1000, + "stream" => [ + "endpoint" => "spotify", + "url" => "track." . $result["id"] + ] + ]; + } + + // get playlists + foreach($payload["data"]["searchV2"]["playlists"]["items"] as $playlist){ + + if(isset($playlist["data"])){ + + $playlist = $playlist["data"]; + } + + $avatar = $this->get_thumb($playlist["ownerV2"]["data"]["avatar"]); + + $out["playlist"][] = [ + "title" => $playlist["name"], + "description" => null, + "author" => [ + "name" => $playlist["ownerV2"]["data"]["name"], + "url" => + "https://open.spotify.com/user/" . + explode( + ":", + $playlist["ownerV2"]["data"]["uri"], + 3 + )[2], + "avatar" => $avatar["url"] + ], + "thumb" => $this->get_thumb($playlist["images"]["items"][0]), + "date" => null, + "duration" => null, + "url" => + "https://open.spotify.com/playlist/" . + explode( + ":", + $playlist["uri"], + 3 + )[2] + ]; + } + + // get albums + foreach($payload["data"]["searchV2"]["albums"]["items"] as $album){ + + if(isset($album["data"])){ + + $album = $album["data"]; + } + + [$artist, $artist_link] = $this->get_artists($album["artists"]); + + $out["album"][] = [ + "title" => $album["name"], + "description" => null, + "author" => [ + "name" => $artist, + "url" => $artist_link, + "avatar" => null + ], + "thumb" => $this->get_thumb($album["coverArt"]), + "date" => mktime(0, 0, 0, 0, 32, $album["date"]["year"]), + "duration" => null, + "url" => + "https://open.spotify.com/album/" . + explode( + ":", + $album["uri"], + 3 + )[2] + ]; + } + + // get podcasts + foreach($payload["data"]["searchV2"]["podcasts"]["items"] as $podcast){ + + if(isset($podcast["data"])){ + + $podcast = $podcast["data"]; + } + + $description = []; + foreach($podcast["topics"]["items"] as $subject){ + + $description[] = $subject["title"]; + } + + $description = implode(", ", $description); + + if($description == ""){ + + $description = null; + } + + $out["podcast"][] = [ + "title" => $podcast["name"], + "description" => $description, + "author" => [ + "name" => $podcast["publisher"]["name"], + "url" => null, + "avatar" => null + ], + "thumb" => $this->get_thumb($podcast["coverArt"]), + "date" => null, + "duration" => null, + "url" => + "https://open.spotify.com/show/" . + explode( + ":", + $podcast["uri"], + 3 + )[2], + "stream" => [ + "endpoint" => null, + "url" => null + ] + ]; + } + + // get audio books (put in podcasts) + foreach($payload["data"]["searchV2"]["audiobooks"]["items"] as $podcast){ + + if(isset($podcast["data"])){ + + $podcast = $podcast["data"]; + } + + $description = []; + foreach($podcast["topics"]["items"] as $subject){ + + $description[] = $subject["title"]; + } + + $description = implode(", ", $description); + + if($description == ""){ + + $description = null; + } + + $authors = []; + foreach($podcast["authors"] as $author){ + + $authors[] = $author["name"]; + } + + $authors = implode(", ", $authors); + + if($authors == ""){ + + $authors = null; + } + + $uri = + explode( + ":", + $podcast["uri"], + 3 + )[2]; + + $out["podcast"][] = [ + "title" => $podcast["name"], + "description" => $description, + "author" => [ + "name" => $authors, + "url" => null, + "avatar" => null + ], + "thumb" => $this->get_thumb($podcast["coverArt"]), + "date" => strtotime($podcast["publishDate"]["isoString"]), + "duration" => null, + "url" => "https://open.spotify.com/show/" . $uri, + "stream" => [ + "endpoint" => "spotify", + "url" => "episode." . $uri + ] + ]; + } + + // get episodes (and place them in podcasts) + foreach($payload["data"]["searchV2"]["episodes"]["items"] as $podcast){ + + if(isset($podcast["data"])){ + + $podcast = $podcast["data"]; + } + + $out["podcast"][] = [ + "title" => $podcast["name"], + "description" => $this->limitstrlen($podcast["description"]), + "author" => [ + "name" => + isset( + $podcast["podcastV2"]["data"]["publisher"]["name"] + ) ? + $podcast["podcastV2"]["data"]["publisher"]["name"] + : null, + "url" => null, + "avatar" => null + ], + "thumb" => $this->get_thumb($podcast["coverArt"]), + "date" => strtotime($podcast["releaseDate"]["isoString"]), + "duration" => $podcast["duration"]["totalMilliseconds"] / 1000, + "url" => + "https://open.spotify.com/show/" . + explode( + ":", + $podcast["uri"], + 3 + )[2], + "stream" => [ + "endpoint" => null, + "url" => null + ] + ]; + } + + // get authors + foreach($payload["data"]["searchV2"]["artists"]["items"] as $user){ + + if(isset($user["data"])){ + + $user = $user["data"]; + } + + $avatar = $this->get_thumb($user["visuals"]["avatarImage"]); + + $out["author"][] = [ + "title" => + ( + $user["profile"]["verified"] === true ? + "✓ " : "" + ) . + $user["profile"]["name"], + "followers" => null, + "description" => null, + "thumb" => $avatar, + "url" => + "https://open.spotify.com/artist/" . + explode( + ":", + $user["uri"], + 3 + )[2] + ]; + } + + // get users + foreach($payload["data"]["searchV2"]["users"]["items"] as $user){ + + if(isset($user["data"])){ + + $user = $user["data"]; + } + + $avatar = $this->get_thumb($user["avatar"]); + + $out["user"][] = [ + "title" => $user["displayName"] . " (@{$user["id"]})", + "followers" => null, + "description" => null, + "thumb" => $avatar, + "url" => "https://open.spotify.com/user/" . $user["id"] + ]; + } + + return $out; + } + + private function get_artists($artists){ + + $artist_out = []; + + foreach($artists["items"] as $artist){ + + $artist_out[] = $artist["profile"]["name"]; + } + + $artist_out = + implode(", ", $artist_out); + + if($artist_out == ""){ + + return [null, null]; + } + + $artist_link = + $artist === null ? + null : + "https://open.spotify.com/artist/" . + explode( + ":", + $artists["items"][0]["uri"] + )[2]; + + return [$artist_out, $artist_link]; + } + + private function get_thumb($cover){ + + $thumb_out = null; + + if($cover !== null){ + foreach($cover["sources"] as $thumb){ + + if( + $thumb_out === null || + (int)$thumb["width"] > $thumb_out["width"] + ){ + + $thumb_out = $thumb; + } + } + } + + if($thumb_out === null){ + + return [ + "url" => null, + "ratio" => null + ]; + }else{ + + return [ + "url" => $thumb_out["url"], + "ratio" => "1:1" + ]; + } + } + + private function limitstrlen($text){ + + return + explode( + "\n", + wordwrap( + str_replace( + ["\n\r", "\r\n", "\n", "\r"], + " ", + $text + ), + 300, + "\n" + ), + 2 + )[0]; + } +} diff --git a/scraper/startpage.php b/scraper/startpage.php new file mode 100644 index 0000000..e48a429 --- /dev/null +++ b/scraper/startpage.php @@ -0,0 +1,1584 @@ +<?php + +class startpage{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("startpage"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + switch($page){ + case "web": + return [ + "country" => [ + "display" => "Country", + "option" => [ + "any" => "All Regions", + "es_AR" => "Argentina", + "en_AU" => "Australia", + "de_AT" => "Austria", + "ru_BY" => "Belarus", + "fr_BE" => "Belgium (FR)", + "nl_BE" => "Belgium (NL)", + "bg_BG" => "Bulgaria", + "en_CA" => "Canada (EN)", + "fr_CA" => "Canada (FR)", + "es_CL" => "Chile", + "es_CO" => "Colombia", + "cs_CZ" => "Czech Republic", + "da_DK" => "Denmark", + "ar_EG" => "Egypt", + "et_EE" => "Estonia", + "fi_FI" => "Finland", + "fr_FR" => "France", + "de_DE" => "Germany", + "el_GR" => "Greece", + "hu_HU" => "Hungary", + "hi_IN" => "India (HI)", + "en_IN" => "India (EN)", + "id_ID" => "Indonesia (ID)", + "en_ID" => "Indonesia (EN)", + "en_IE" => "Ireland", + "it_IT" => "Italy", + "ja_JP" => "Japan", + "ko_KR" => "Korea", + "ms_MY" => "Malaysia (MS)", + "en_MY" => "Malaysia (EN)", + "es_MX" => "Mexico", + "nl_NL" => "Netherlands", + "en_NZ" => "New Zealand", + "no_NO" => "Norway", + "es_PE" => "Peru", + "fil_PH" => "Philippines (FIL)", + "en_PH" => "Philippines (EN)", + "pl_PL" => "Poland", + "pt_PT" => "Portugal", + "ro_RO" => "Romania", + "ru_RU" => "Russia", + "ms_SG" => "Singapore (MS)", + "en_SG" => "Singapore (EN)", + "es_ES" => "Spain (ES)", + "ca_ES" => "Spain (CA)", + "sv_SE" => "Sweden", + "de_CH" => "Switzerland (DE)", + "fr_CH" => "Switzerland (FR)", + "it_CH" => "Switzerland (IT)", + "tr_TR" => "Turkey", + "uk_UA" => "Ukraine", + "en_US" => "US (EN)", + "es_US" => "US (ES)", + "es_UY" => "Uruguay", + "es_VE" => "Venezuela", + "vi_VN" => "Vietnam (VI)", + "en_VN" => "Vietnam (EN)", + "en_ZA" => "South Africa" + ] + ], + "nsfw" => [ // qadf + "display" => "NSFW", + "option" => [ + "yes" => "Yes", // qadf=none + "no" => "No" // qadf=heavy + ] + ], + "time" => [ // with_date + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "d" => "Past 24 hours", + "w" => "Past week", + "m" => "Past month", + "y" => "Past year", + ] + ], + "extendedsearch" => [ + // undefined display, so it wont show in frontend + "option" => [ + "yes" => "Yes", + "no" => "No" + ] + ] + ]; + break; + + case "images": + return [ + "nsfw" => [ // qadf + "display" => "NSFW", + "option" => [ + "yes" => "Yes", // qadf=none + "no" => "No" // qadf=heavy + ] + ], + "size" => [ // flimgsize + "display" => "Size", + "option" => [ + "any" => "Any size", + "Small" => "Small", + "Medium" => "Medium", + "Large" => "Large", + "Wallpaper" => "Wallpaper", + // from here, image-size-select, var prefix = isz:lt,islt: + "qsvgs" => "Larger than 400x300", + "vga" => "Larger than 640x480", + "svga" => "Larger than 800x600", + "xga" => "Larger than 1024x768", + "qsvgs" => "Larger than 400x300", + "2mp" => "Larger than 2 MP (1600x1200)", + "4mp" => "Larger than 4 MP (2272x1704)", + "6mp" => "Larger than 6 MP (2816x2112)", + "8mp" => "Larger than 8 MP (3264x2448)", + "10mp" => "Larger than 10 MP (3648x2736)", + "12mp" => "Larger than 12 MP (4096x3072)", + "15mp" => "Larger than 15 MP (4480x3360)", + "20mp" => "Larger than 20 MP (5120x3840)", + "40mp" => "Larger than 40 MP (7216x5412)", + "70mp" => "Larger than 70 MP (9600x7200)" + ] + ], + "color" => [ // flimgcolor + "display" => "Color", + "option" => [ + "any" => "Any color", + // from here, var prefix = ic: + "color" => "Color only", + "bnw" => "Black & white", // set to "gray" + // from here, var prefix = ic:specific,isc: + "red" => "Red", + "orange" => "Orange", + "yellow" => "Yellow", + "green" => "Green", + "teal" => "Teal", + "blue" => "Blue", + "purple" => "Purple", + "pink" => "Pink", + "white" => "White", + "gray" => "Gray", + "black" => "Black", + "brown" => "Brown" + ] + ], + "type" => [ // flimgtype + "display" => "Type", + "option" => [ + "any" => "Any type", + "AnimatedGif" => "Animated GIF", + "Clipart" => "Clip Art", + "Line" => "Line Drawing", + "Photo" => "Photograph", + "Transparent" => "Transparent Background" + ] + ], + "license" => [ // flimglicense + "display" => "License", + "option" => [ + "any" => "Any license", + "p" => "Public domain", + "s" => "Free to share", + "sc" => "Free to share commercially", + "m" => "Free to modify", + "mc" => "Free to modify commercially" + ] + ] + ]; + break; + + case "videos": + return [ + "nsfw" => [ // qadf + "display" => "NSFW", + "option" => [ + "yes" => "Yes", // qadf=none + "no" => "No" // qadf=heavy + ] + ], + "sort" => [ + "display" => "Sort by", + "option" => [ + "relevance" => "Most relevant", + "popular" => "Most popular", + "recent" => "Most recent" + ] + ], + "duration" => [ // with_duration + "display" => "Duration", + "option" => [ + "any" => "Any duration", + "short" => "Short", + "medium" => "Medium", + "long" => "Long" + ] + ] + ]; + break; + + case "news": + return [ + "nsfw" => [ // qadf + "display" => "NSFW", + "option" => [ + "yes" => "Yes", // qadf=none + "no" => "No" // qadf=heavy + ] + ], + "time" => [ // with_date + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "d" => "Past 24 hours", + "w" => "Past week", + "m" => "Past month" + ] + ] + ]; + break; + + //preferences=date_timeEEEworldN1Ndisable_family_filterEEE1N1Ndisable_open_in_new_windowEEE0N1Nenable_post_methodEEE1N1Nenable_proxy_safety_suggestEEE0N1Nenable_stay_controlEEE0N1Ninstant_answersEEE1N1Nlang_homepageEEEs%2Fdevice%2FenN1NlanguageEEEazerbaijaniN1Nlanguage_uiEEEenglishN1Nnum_of_resultsEEE20N1Nsearch_results_regionEEEallN1NsuggestionsEEE1N1Nwt_unitEEEcelsius; Domain=startpage.com; Expires=Mon, 28 Oct 2024 20:21:58 GMT; Secure; Path=/ + //preferences=date_timeEEEworldN1Ndisable_family_filterEEE1N1Ndisable_open_in_new_windowEEE0N1Nenable_post_methodEEE1N1Nenable_proxy_safety_suggestEEE0N1Nenable_stay_controlEEE0N1Ninstant_answersEEE1N1Nlang_homepageEEEs%2Fdevice%2FenN1NlanguageEEEenglishN1Nlanguage_uiEEEenglishN1Nnum_of_resultsEEE20N1Nsearch_results_regionEEEallN1NsuggestionsEEE1N1Nwt_unitEEEcelsius; Domain=startpage.com; Expires=Mon, 28 Oct 2024 20:22:52 GMT; Secure; Path=/ + } + } + + private function get($proxy, $url, $get = [], $post = false, $is_xhr = false){ + + $curlproc = curl_init(); + + if($post === true){ + + curl_setopt($curlproc, CURLOPT_POST, true); + curl_setopt($curlproc, CURLOPT_POSTFIELDS, $get); + + }elseif($get !== []){ + + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + // http2 bypass + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + if($is_xhr === true){ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: application/json", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Referer: https://www.startpage.com/", + "Content-Type: application/json", + "Content-Length: " . strlen($get), + "Origin: https://www.startpage.com/", + "DNT: 1", + "Connection: keep-alive", + "Cookie: preferences=date_timeEEEworldN1Ndisable_family_filterEEE1N1Ndisable_open_in_new_windowEEE0N1Nenable_post_methodEEE1N1Nenable_proxy_safety_suggestEEE0N1Nenable_stay_controlEEE0N1Ninstant_answersEEE1N1Nlang_homepageEEEs%2Fdevice%2FenN1NlanguageEEEenglishN1Nlanguage_uiEEEenglishN1Nnum_of_resultsEEE20N1Nsearch_results_regionEEEallN1NsuggestionsEEE1N1Nwt_unitEEEcelsius", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-origin", + "TE: trailers"] + ); + + }elseif($post === true){ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Referer: https://www.startpage.com/", + "Content-Type: application/x-www-form-urlencoded", + "Content-Length: " . strlen($get), + "DNT: 1", + "Connection: keep-alive", + "Cookie: preferences=date_timeEEEworldN1Ndisable_family_filterEEE1N1Ndisable_open_in_new_windowEEE0N1Nenable_post_methodEEE1N1Nenable_proxy_safety_suggestEEE0N1Nenable_stay_controlEEE0N1Ninstant_answersEEE1N1Nlang_homepageEEEs%2Fdevice%2FenN1NlanguageEEEenglishN1Nlanguage_uiEEEenglishN1Nnum_of_resultsEEE20N1Nsearch_results_regionEEEallN1NsuggestionsEEE1N1Nwt_unitEEEcelsius", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1", + "Priority: u=0, i", + "TE: trailers"] + ); + }else{ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Connection: keep-alive", + "Cookie: preferences=date_timeEEEworldN1Ndisable_family_filterEEE1N1Ndisable_open_in_new_windowEEE0N1Nenable_post_methodEEE1N1Nenable_proxy_safety_suggestEEE0N1Nenable_stay_controlEEE0N1Ninstant_answersEEE1N1Nlang_homepageEEEs%2Fdevice%2FenN1NlanguageEEEenglishN1Nlanguage_uiEEEenglishN1Nnum_of_resultsEEE20N1Nsearch_results_regionEEEallN1NsuggestionsEEE1N1Nwt_unitEEEcelsius", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1", + "Priority: u=0, i", + "TE: trailers"] + ); + } + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function web($get){ + + if($get["npt"]){ + + [$post, $proxy] = $this->backend->get($get["npt"], "web"); + + try{ + $html = $this->get( + $proxy, + "https://www.startpage.com/sp/search", + $post, + true + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + $get_instant_answer = false; + + }else{ + + $proxy = $this->backend->get_ip(); + + $params = [ + "query" => $get["s"], + "cat" => "web", + "pl" => "opensearch" + ]; + + if($get["nsfw"] == "no"){ + + $params["qadf"] = "heavy"; + $get_instant_answer = false; + }else{ + + $get_instant_answer = true; + } + + if($get["country"] !== "any"){ + + $params["qsr"] = $get["country"]; + } + + if($get["time"] !== "any"){ + + $params["with_date"] = $get["time"]; + } + + try{ + $html = $this->get( + $proxy, + "https://www.startpage.com/sp/search", + $params + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + //$html = file_get_contents("scraper/startpage.html"); + } + + $this->detect_captcha($html); + + if( + preg_match( + '/React\.createElement\(UIStartpage\.AppSerpWeb, ?(.+)\),?$/m', + $html, + $matches + ) === 0 + ){ + + throw new Exception("Failed to grep JSON object"); + } + + $json = json_decode($matches[1], true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + //print_r($json); + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + // get npt + $out["npt"] = $this->parse_npt($json, "web", $proxy); + + foreach($json["render"]["presenter"]["regions"]["mainline"] as $category){ + + if(!isset($category["display_type"])){ + + continue; + } + + switch($category["display_type"]){ + + case "web-google": + foreach($category["results"] as $result){ + + $sublinks = []; + + foreach($result["siteLinks"] as $sublink){ + + $sublinks[] = [ + "title" => $sublink["title"], + "description" => null, + "url" => $sublink["clickUrl"] + ]; + } + + $description = + explode( + "...", + $this->titledots( + html_entity_decode( + $this->fuckhtml + ->getTextContent( + $result["description"] + ) + ) + ), + 2 + ); + + $date = strtotime(trim($description[0])); + + if( + $date === false || + count($description) !== 2 || + strlen($description[0]) > 14 + ){ + + // no date found + $description = + implode( + " ... ", + $description + ); + + $date = null; + }else{ + + // date found + $description = ltrim($description[1]); + } + + $out["web"][] = [ + "title" => + $this->titledots( + html_entity_decode( + $this->fuckhtml + ->getTextContent( + $result["title"] + ) + ) + ), + "description" => $description, + "url" => $result["clickUrl"], + "date" => $date, + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => $sublinks, + "table" => [] + ]; + } + break; + + case "images-qi-top": + foreach($category["results"] as $result){ + + $out["image"][] = [ + "title" => + $this->titledots( + html_entity_decode( + $this->fuckhtml + ->getTextContent( + $result["title"] + ) + ) + ), + "source" => [ + [ + "url" => $result["rawImageUrl"], + "width" => (int)$result["width"], + "height" => (int)$result["height"] + ], + [ + "url" => $this->unshitimage($result["mdThumbnailUrl"]), + "width" => (int)$result["mdThumbnailWidth"], + "height" => (int)$result["mdThumbnailHeight"] + ] + ], + "url" => + $result["altClickUrl"] + ]; + } + break; + + case "spellsuggest-google": + $out["spelling"] = + [ + "type" => "including", + "using" => $json["render"]["query"], + "correction" => $category["results"][0]["query"] + ]; + break; + + case "dictionary-qi": + foreach($category["results"] as $result){ + + $answer = [ + "title" => $result["word"], + "description" => [], + "url" => null, + "thumb" => null, + "table" => [], + "sublink" => [] + ]; + + foreach($result["lexical_categories"] as $lexic_type => $definitions){ + + $answer["description"][] = [ + "type" => "title", + "value" => $lexic_type + ]; + + $i = 0; + + foreach($definitions as $definition){ + + $text_definition = trim($definition["definition"]); + $text_example = trim($definition["example"]); + $text_synonyms = implode(", ", $definition["synonyms"]); + + if($text_definition != ""){ + + $i++; + + $c = count($answer["description"]) - 1; + if( + $c !== 0 && + $answer["description"][$c]["type"] == "text" + ){ + + $answer["description"][$c]["value"] .= + "\n\n" . $i . ". " . $text_definition; + + }else{ + + $answer["description"][] = [ + "type" => "text", + "value" => $i . ". " . $text_definition + ]; + } + } + + if($text_example != ""){ + + $answer["description"][] = [ + "type" => "quote", + "value" => $text_example + ]; + } + + if($text_synonyms != ""){ + + $answer["description"][] = [ + "type" => "text", + "value" => "Synonyms: " . $text_synonyms + ]; + } + } + } + + $out["answer"][] = $answer; + } + break; + } + } + + // parse instant answers + if( + $get["extendedsearch"] == "yes" && + $get_instant_answer === true + ){ + + // https://www.startpage.com/sp/qi?qimsn=ex&sxap=%2Fv1%2Fquery&sc=BqZ3inqrAgF701&sr=1 + try{ + $post = [ + "se" => "n0vze2y9dqwy", + "q" => $json["render"]["query"], + "results" => [], // populate + "enableKnowledgePanel" => true, + "enableMediaThumbBar" => false, + "enableSearchSuggestions" => false, + "enableTripadvisorProperties" => [], + "enableTripadvisorPlaces" => [], + "enableTripadvisorPlacesForLocations" => [], + "enableWebProducts" => false, + "tripadvisorPartnerId" => null, + "tripadvisorMapColorMode" => "light", + "tripadvisorDisablesKnowledgePanel" => false, + "instantAnswers" => [ + "smartAnswers", + "youtube", + "tripadvisor" + ], + "iaType" => null, + "forceEnhancedKnowledgePanel" => false, + "shoppingOnly" => false, + "allowAdultProducts" => true, + "lang" => "en", + "browserLang" => "en-US", + "browserTimezone" => "America/New_York", + "market" => null, + "userLocation" => null, + "userDate" => date("Y-m-d"), + "userAgentType" => "unknown" + ]; + + foreach($out["web"] as $result){ + + $post["results"][] = [ + "url" => $result["url"], + "title" => $result["title"] + ]; + } + + $post = json_encode($post, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_INVALID_UTF8_IGNORE); + + $additional_data = + $this->get( + $proxy, + "https://www.startpage.com/sp/qi?qimsn=ex&sxap=%2Fv1%2Fquery&sc=" . $json["render"]["callback_sc"] . "&sr=1", + $post, + true, + true + ); + + $additional_data = json_decode($additional_data, true); + + if($additional_data === null){ + + throw new Exception("Failed to decode JSON"); // just break out, dont fail completely + } + + if(!isset($additional_data["knowledgePanel"])){ + + throw new Exception("Response has missing data (knowledgePanel)"); + } + + $additional_data = $additional_data["knowledgePanel"]; + + $answer = [ + "title" => $additional_data["meta"]["title"], + "description" => [ + [ + "type" => "quote", + "value" => $additional_data["meta"]["description"] + ] + ], + "url" => $additional_data["meta"]["origWikiUrl"], + "thumb" => $additional_data["meta"]["image"], + "table" => [], + "sublink" => [] + ]; + + // parse html for instant answer + $this->fuckhtml->load($additional_data["html"]); + + $div = + $this->fuckhtml + ->getElementsByTagName( + "div" + ); + + // get description + $description = + $this->fuckhtml + ->getElementsByClassName( + "sx-kp-short-extract sx-kp-short-extract-complete", + $div + ); + + if(count($description) !== 0){ + + $answer["description"][] = [ + "type" => "text", + "value" => + html_entity_decode( + $this->fuckhtml + ->getTextContent( + $description[0] + ) + ) + ]; + } + + // get socials + $socials = + $this->fuckhtml + ->getElementsByClassName( + "sx-wiki-social-link", + "a" + ); + + foreach($socials as $social){ + + $title = + $this->fuckhtml + ->getTextContent( + $social["attributes"]["title"] + ); + + $url = + $this->fuckhtml + ->getTextContent( + $social["attributes"]["href"] + ); + + switch($title){ + + case "Official Website": + $title = "Website"; + break; + } + + $answer["sublink"][$title] = $url; + } + + // get videos + $videos = + $this->fuckhtml + ->getElementsByClassName( + "sx-kp-video-grid-item", + $div + ); + + foreach($videos as $video){ + + $this->fuckhtml->load($video); + + $as = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + if(count($as) === 0){ + + // ?? invalid + continue; + } + + $image = + $this->fuckhtml + ->getElementsByAttributeName( + "data-sx-src", + "img" + ); + + if(count($image) !== 0){ + + $thumb = [ + "ratio" => "16:9", + "url" => + $this->fuckhtml + ->getTextContent( + $image[0]["attributes"]["data-sx-src"] + ) + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["video"][] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $as[0]["attributes"]["title"] + ), + "description" => null, + "date" => null, + "duration" => null, + "views" => null, + "thumb" => $thumb, + "url" => + $this->fuckhtml + ->getTextContent( + $as[0]["attributes"]["href"] + ) + ]; + } + + // reset + $this->fuckhtml->load($additional_data["html"]); + + // get table elements + $table = + $this->fuckhtml + ->getElementsByClassName( + "sx-infobox", + "table" + ); + + if(count($table) !== 0){ + + $trs = + $this->fuckhtml + ->getElementsByTagName( + "tr" + ); + + foreach($trs as $tr){ + + $this->fuckhtml->load($tr); + + // ok so startpage devs cant fucking code a table + // td = content + // th (AAAHH) = title + $tds = + $this->fuckhtml + ->getElementsByTagName( + "td" + ); + + $ths = + $this->fuckhtml + ->getElementsByTagName( + "th" + ); + + if( + count($ths) === 1 && + count($tds) === 1 + ){ + + $title = + $this->fuckhtml + ->getTextContent( + $ths[0] + ); + + $description = []; + + $this->fuckhtml->load($tds[0]); + + $lis = + $this->fuckhtml + ->getElementsByTagName( + "li" + ); + + if(count($lis) !== 0){ + + foreach($lis as $li){ + + $description[] = + $this->fuckhtml + ->getTextContent( + $li + ); + } + + $description = implode(", ", $description); + }else{ + + $description = + $this->fuckhtml + ->getTextContent( + $tds[0] + ); + } + + $answer["table"][$title] = $description; + } + } + } + + $out["answer"][] = $answer; + + }catch(Exception $error){ + + // do nothing + //echo "error!"; + } + } + + return $out; + } + + public function image($get){ + + if($get["npt"]){ + + [$post, $proxy] = $this->backend->get($get["npt"], "images"); + + try{ + $html = $this->get( + $proxy, + "https://www.startpage.com/sp/search", + $post, + true + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + try{ + + $proxy = $this->backend->get_ip(); + + $params = [ + "query" => $get["s"], + "cat" => "images", + "pl" => "opensearch" + ]; + + if($get["nsfw"] == "no"){ + + $params["qadf"] = "heavy"; + } + + if($get["size"] != "any"){ + + if( + $get["size"] == "Small" || + $get["size"] == "Medium" || + $get["size"] == "Large" || + $get["size"] == "Wallpaper" + ){ + + $params["flimgsize"] = $get["size"]; + }else{ + + $params["image-size-select"] = "isz:lt,islt:" . $get["size"]; + } + } + + if($get["color"] != "any"){ + + if($get["color"] == "color"){ + + $params["flimgcolor"] = "ic:color"; + }elseif($get["color"] == "bnw"){ + + $params["flimgcolor"] = "ic:gray"; + }else{ + + $params["flimgcolor"] = "ic:specific,isc:" . $get["color"]; + } + } + + if($get["type"] != "any"){ + + $params["flimgtype"] = $get["type"]; + } + + if($get["license"] != "any"){ + + $params["flimglicense"] = $get["license"]; + } + + try{ + $html = $this->get( + $proxy, + "https://www.startpage.com/sp/search", + $params + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + //$html = file_get_contents("scraper/startpage.html"); + + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + } + + $this->detect_captcha($html); + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + if( + preg_match( + '/React\.createElement\(UIStartpage\.AppSerpImages, ?(.+)\),?$/m', + $html, + $matches + ) === 0 + ){ + + throw new Exception("Failed to grep JSON object"); + } + + $json = json_decode($matches[1], true); + + if($json === null){ + + throw new Exception("Failed to decode JSON object"); + } + + // get npt + $out["npt"] = $this->parse_npt($json, "images", $proxy); + + // get images + foreach($json["render"]["presenter"]["regions"]["mainline"] as $category){ + + if($category["display_type"] != "images-bing"){ + + // ignore ads and !! suggestions !! @todo + continue; + } + + foreach($category["results"] as $image){ + + $out["image"][] = [ + "title" => $this->titledots($image["title"]), + "source" => [ + [ + "url" => $this->unshitimage($image["clickUrl"]), + "width" => (int)$image["width"], + "height" => (int)$image["height"] + ], + [ + "url" => $this->unshitimage($image["thumbnailUrl"]), + "width" => (int)$image["thumbnailWidth"], + "height" => (int)$image["thumbnailHeight"] + ] + ], + "url" => $image["altClickUrl"] + ]; + } + } + + return $out; + } + + public function video($get){ + + if($get["npt"]){ + + [$post, $proxy] = $this->backend->get($get["npt"], "videos"); + + try{ + $html = $this->get( + $proxy, + "https://www.startpage.com/sp/search", + $post, + true + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + try{ + + $proxy = $this->backend->get_ip(); + + $params = [ + "query" => $get["s"], + "cat" => "video", + "pl" => "opensearch" + ]; + + if($get["nsfw"] == "no"){ + + $params["qadf"] = "heavy"; + } + + if($get["sort"] != "relevance"){ + + $params["sort_by"] = $get["sort"]; + } + + if($get["duration"] != "any"){ + + $params["with_duration"] = $get["duration"]; + } + + try{ + $html = $this->get( + $proxy, + "https://www.startpage.com/sp/search", + $params + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + //$html = file_get_contents("scraper/startpage.html"); + + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + } + + $this->detect_captcha($html); + + if( + preg_match( + '/React\.createElement\(UIStartpage\.AppSerpVideos, ?(.+)\),?$/m', + $html, + $matches + ) === 0 + ){ + + throw new Exception("Failed to get JSON object"); + } + + $json = json_decode($matches[1], true); + + if($json === null){ + + throw new Exception("Failed to decode JSON object"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + // get npt + $out["npt"] = $this->parse_npt($json, "video", $proxy); + + // get results + foreach($json["render"]["presenter"]["regions"]["mainline"] as $category){ + + if( + preg_match( + '/^video-/i', + $category["display_type"] + ) + ){ + + foreach($category["results"] as $video){ + + if( + isset($video["thumbnailUrl"]) && + $video["thumbnailUrl"] !== null + ){ + + $thumb = [ + "ratio" => "16:9", + "url" => $this->unshitimage($video["thumbnailUrl"]) + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["video"][] = [ + "title" => str_replace(["", ""], "", $video["title"]), + "description" => $this->limitstrlen($video["description"]), + "author" => [ + "name" => $video["channelTitle"], + "url" => null, + "avatar" => null + ], + "date" => strtotime($video["publishDate"]), + "duration" => $this->hms2int($category["display_type"] == "video-youtube" ? $video["duration"] : $video["duration"] / 1000), + "views" => (int)$video["viewCount"], + "thumb" => $thumb, + "url" => $video["clickUrl"] + ]; + } + } + } + + return $out; + } + + public function news($get){ + + if($get["npt"]){ + + [$post, $proxy] = $this->backend->get($get["npt"], "news"); + + try{ + $html = $this->get( + $proxy, + "https://www.startpage.com/sp/search", + $post, + true + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + try{ + + $proxy = $this->backend->get_ip(); + + $params = [ + "query" => $get["s"], + "cat" => "news", + "pl" => "opensearch" + ]; + + if($get["nsfw"] == "no"){ + + $params["qadf"] = "heavy"; + } + + if($get["time"] != "any"){ + + $params["with_date"] = $get["time"]; + } + + try{ + $html = $this->get( + $proxy, + "https://www.startpage.com/sp/search", + $params + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + //$html = file_get_contents("scraper/startpage.html"); + + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + } + + $this->detect_captcha($html); + + if( + preg_match( + '/React\.createElement\(UIStartpage\.AppSerpNews, ?(.+)\),?$/m', + $html, + $matches + ) === 0 + ){ + + throw new Exception("Failed to get JSON object"); + } + + $json = json_decode($matches[1], true); + + if($json === null){ + + throw new Exception("Failed to decode JSON object"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "news" => [] + ]; + + // get npt + $out["npt"] = $this->parse_npt($json, "news", $proxy); + + foreach($json["render"]["presenter"]["regions"]["mainline"] as $category){ + + if($category["display_type"] != "news-bing"){ + + // unsupported category + continue; + } + + foreach($category["results"] as $news){ + + if( + isset($news["thumbnailUrl"]) && + $news["thumbnailUrl"] !== null + ){ + + $thumb = [ + "ratio" => "16:9", + "url" => $this->unshitimage($news["thumbnailUrl"]) + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["news"][] = [ + "title" => $this->titledots($this->remove_penguins($news["title"])), + "author" => $news["source"], + "description" => $this->titledots($this->remove_penguins($news["description"])), + "date" => (int)substr((string)$news["date"], 0, -3), + "thumb" => $thumb, + "url" => $news["clickUrl"] + ]; + } + } + + return $out; + } + + private function parse_npt($json, $pagetype, $proxy){ + + foreach($json["render"]["presenter"]["pagination"]["pages"] as $page){ + + if($page["name"] == "Next"){ + + parse_str( + explode( + "?", + $page["url"], + 2 + )[1], + $str + ); + + return + $this->backend->store( + http_build_query( + [ + "lui" => "english", + "language" => "english", + "query" => $str["q"], + "cat" => $pagetype, + "sc" => $str["sc"], + "t" => "device", + "segment" => "startpage.udog", + "page" => $str["page"] + ] + ), + $pagetype, + $proxy + ); + + break; + } + } + + return null; + } + + private function unshitimage($url){ + + $query = parse_url($url, PHP_URL_QUERY); + parse_str($query, $query); + + if(isset($query["piurl"])){ + + if(strpos($query["piurl"], "gstatic.com/")){ + + return + explode( + "&", + $query["piurl"], + 2 + )[0]; + } + + if( + strpos($query["piurl"], "bing.net/") || + strpos($query["piurl"], "bing.com/") + ){ + + return + explode( + "&", + $query["piurl"], + 2 + )[0]; + } + + return $query["piurl"]; + } + + return $url; + } + + private function limitstrlen($text){ + + return + explode( + "\n", + wordwrap( + str_replace( + ["\n\r", "\r\n", "\n", "\r"], + " ", + $text + ), + 300, + "\n" + ), + 2 + )[0]; + } + + private function titledots($title){ + + return trim($title, " .\t\n\r\0\x0B…"); + } + + private function hms2int($time){ + + $parts = explode(":", $time, 3); + $time = 0; + + if(count($parts) === 3){ + + // hours + $time = $time + ((int)$parts[0] * 3600); + array_shift($parts); + } + + if(count($parts) === 2){ + + // minutes + $time = $time + ((int)$parts[0] * 60); + array_shift($parts); + } + + // seconds + $time = $time + (int)$parts[0]; + + return $time; + } + + private function remove_penguins($text){ + + return str_replace( + ["", ""], + "", + $text + ); + } + + private function detect_captcha($html){ + + $this->fuckhtml->load($html); + + $title = + $this->fuckhtml + ->getElementsByTagName( + "title" + ); + + if( + count($title) !== 0 && + $title[0]["innerHTML"] == "Redirecting..." + ){ + + // check if it's a captcha + $as = + $this->fuckhtml + ->getElementsByTagName( + "a" + ); + + foreach($as as $a){ + + if( + strpos( + $this->fuckhtml + ->getTextContent( + $a["innerHTML"] + ), + "https://www.startpage.com/sp/captcha" + ) !== false + ){ + + throw new Exception("Startpage returned a captcha"); + } + } + + throw new Exception("Startpage redirected the scraper to an unhandled page"); + } + } +} diff --git a/scraper/vimeo.php b/scraper/vimeo.php new file mode 100644 index 0000000..50bb21b --- /dev/null +++ b/scraper/vimeo.php @@ -0,0 +1,754 @@ +<?php + +class vimeo{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("vimeo"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + return [ + "time" => [ + "display" => "Date uploaded", // &filter_uploaded= + "option" => [ + "any" => "Any time", + "today" => "Last 24 hours", + "this-week" => "Last 7 days", + "this-month" => "Last 30 days", + "this-year" => "Last 365 days", + ] + ], + "display" => [ + "display" => "Display", + "option" => [ + "video" => "Videos", + "ondemand" => "On-Demand ($$)", + "people" => "People", + "channel" => "Channels", + "group" => "Groups" + ] + ], + "sort" => [ + "display" => "Sort by", + "option" => [ + "relevance" => "Relevance", // no param + "recent" => "Newest", // &sort=latest&direction=desc + "popular" => "Most popular", // &sort=popularity&direction=desc + "a_z" => "Title, A to Z", // &sort=alphabetical&direction=asc + "z_a" => "Title, Z to A", // &sort=alphabetical&direction=desc + "longest" => "Longest", // &sort=duration&direction=desc + "shortest" => "Shortest", // &sort=duration&direction=asc + ] + ], + "duration" => [ + "display" => "Duration", // &filter_duration= + "option" => [ + "any" => "Any duration", + "short" => "Short (less than 4 minutes)", + "medium" => "Medium (4-10 minutes)", + "long" => "Long (over 10 minutes)" + ] + ], + "resolution" => [ + "display" => "Resolution", + "option" => [ + "any" => "Any resolution", + "4k" => "4K" // &filter_resolution=4k + ] + ], + "category" => [ + "display" => "Category", // &filter_category= + "option" => [ + "any" => "Any category", + "animation" => "Animation", + "comedy" => "Comedy", + "music" => "Music", + "experimental" => "Experimental", + "documentary" => "Documentary", + "identsandanimatedlogos" => "Idents and Animated Logos", + "industry" => "Industry", + "instructionals" => "Instructionals", + "narrative" => "Narrative", + "personal" => "Personal" + ] + ], + "live" => [ + "display" => "Live events", + "option" => [ + "any" => "Any", + "yes" => "Live now" // &filter_live=now + ] + ], + "hdr" => [ + "display" => "HDR", // &filter_hdr= + "option" => [ + "any" => "Any", + "hdr" => "Any HDR", + "dolby_vision" => "Dolby Vision", + "hdr10" => "HDR10", + "hdr10+" => "HDR10+" + ] + ], + "vimeo_360" => [ + "display" => "Vimeo 360°", // &filter_vimeo_360 + "option" => [ + "any" => "Any", + "spatial" => "Spatial", + "360" => "360°" + ] + ], + "price" => [ // &filter_price= + "display" => "Price", + "option" => [ + "any" => "Any price", + "free" => "Free", + "paid" => "Paid" + ] + ], + "collection" => [ + "display" => "Vimeo collections", + "option" => [ + "any" => "Any collection", + "staff_pick" => "Staff picks" // &filter_staffpicked=true + ] + ], + "license" => [ // &filter_license= + "display" => "License", + "option" => [ + "any" => "Any license", + "by-nc-nd" => "CC BY-NC-ND", + "by" => "CC BY", + "by-nc" => "CC BY-NC", + "by-nc-sa" => "CC BY-NC-SA", + "by-nd" => "CC BY-ND", + "by-sa" => "CC BY-SA", + "cc0" => "CC0" + ] + ] + ]; + } + + private function get($proxy, $url, $get = [], $jwt = false){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + if($jwt === false){ + + curl_setopt( + $curlproc, + CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + "Referer: https://vimeo.com/search", + "X-Requested-With: XMLHttpRequest", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-origin", + "Priority: u=4"] + ); + + }else{ + + curl_setopt( + $curlproc, + CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: application/vnd.vimeo.*+json;version=3.3", + "Accept-Language: en", + "Accept-Encoding: gzip, deflate, br, zstd", + "Referer: https://vimeo.com/", + "Content-Type: application/json", + "Authorization: jwt $jwt", + "Vimeo-Page: /search/[[...slug]]", + "Origin: https://vimeo.com", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-site", + "Priority: u=4"] + ); + } + + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function video($get){ + + // parse shit + if($get["npt"]){ + + [$npt, $proxy] = + $this->backend + ->get( + $get["npt"], + "videos" + ); + + $npt = json_decode($npt, true); + $pagetype = $npt["pagetype"]; + $npt = $npt["npt"]; + + $jwt = $this->get_jwt($proxy); + + try{ + + $json = + $this->get( + $proxy, + "https://api.vimeo.com" . $npt, + [], + $jwt + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + }else{ + + $proxy = null; + $jwt = $this->get_jwt($proxy); // this gives us a proxy by reference + + // parse filters + $npt = [ + "query" => $get["s"], + "page" => 1, + "per_page" => 24, + "facets" => "type" + ]; + + switch($get["display"]){ + + case "video": + $npt["filter_type"] = "clip"; + $npt["fields"] = "clip.name,stats.plays,clip.pictures,clip.user.name,clip.user.link,clip.user.pictures.sizes,clip.uri,clip.stats.plays,clip.duration,clip.created_time,clip.link,clip.description"; + break; + + case "ondemand": + $npt["filter_type"] = "ondemand"; + $npt["sizes"] = "296x744"; + $npt["fields"] = "ondemand.link,ondemand.name,ondemand.pictures.sizes,ondemand.metadata.interactions.buy,ondemand.metadata.interactions.rent,ondemand.uri"; + break; + + case "people": + $npt["filter_type"] = "people"; + $npt["fetch_user_profile"] = "1"; + $npt["fields"] = "people.name,people.location_details.formatted_address,people.metadata.public_videos.total,people.pictures.sizes,people.link,people.metadata.connections.followers.total,people.skills.name,people.skills.uri,people.background_video,people.uri"; + break; + + case "channel": + $npt["filter_type"] = "channel"; + $npt["fields"] = "channel.name,channel.metadata.connections.users.total,channel.metadata.connections.videos.total,channel.pictures.sizes,channel.link,channel.uri"; + break; + + case "group": + $npt["filter_type"] = "group"; + $npt["fields"] = "group.name,group.metadata.connections.users.total,group.metadata.connections.videos.total,group.pictures.sizes,group.link,group.uri"; + break; + } + + // only apply filters if we're searching for videos + if($get["display"] == "video"){ + + switch($get["sort"]){ + + case "relevance": break; // do nothing + + case "recent": + $npt["sort"] = "latest"; + $npt["direction"] = "desc"; + break; + + case "popular": + $npt["sort"] = "popularity"; + $npt["direction"] = "desc"; + break; + + case "a_z": + $npt["sort"] = "alphabetical"; + $npt["direction"] = "asc"; + break; + + case "z_a": + $npt["sort"] = "alphabetical"; + $npt["direction"] = "desc"; + break; + + case "longest": + $npt["sort"] = "duration"; + $npt["direction"] = "desc"; + break; + + case "shortest": + $npt["sort"] = "duration"; + $npt["direction"] = "asc"; + break; + } + + if($get["time"] != "any"){ + + $npt["filter_uploaded"] = $get["time"]; + } + + if($get["duration"] != "any"){ + + $npt["filter_duration"] = $get["duration"]; + } + + if($get["resolution"] != "any"){ + + $npt["filter_resolution"] = $get["resolution"]; + } + + if($get["category"] != "any"){ + + $npt["filter_category"] = $get["category"]; + } + + if($get["live"] != "any"){ + + $npt["filter_live"] = "now"; + } + + if($get["hdr"] != "any"){ + + $npt["filter_hdr"] = $get["hdr"]; + } + + if($get["vimeo_360"] != "any"){ + + $npt["filter_vimeo_360"] = $get["vimeo_360"]; + } + + if($get["price"] != "any"){ + + $npt["filter_price"] = $get["price"]; + } + + if($get["collection"] == "staff_pick"){ + + $npt["filter_staffpicked"] = "true"; + } + + if($get["license"] != "any"){ + + $npt["filter_license"] = $get["license"]; + } + } + + $pagetype = $npt["filter_type"]; + + try{ + + $json = + $this->get( + $proxy, + "https://api.vimeo.com/search", + $npt, + $jwt + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + } + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to parse JSON"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + if(isset($json["error"])){ + + $error = $json["error"]; + if(isset($json["developer_message"])){ + + $error .= " ({$json["developer_message"]})"; + } + + throw new Exception("Vimeo returned an error: " . $error); + } + + if(!isset($json["data"])){ + + throw new Exception("Vimeo did not return a data object"); + } + + switch($pagetype){ + + case "clip": + foreach($json["data"] as $video){ + + $video = $video["clip"]; + + if(isset($video["user"]["pictures"]["sizes"])){ + + $avatar = $video["user"]["pictures"]["sizes"][count($video["user"]["pictures"]["sizes"]) - 1]["link"]; + }else{ + + $avatar = null; + } + + $out["video"][] = [ + "title" => $video["name"], + "description" => + $this->limitstrlen( + $video["description"] + ), + "author" => [ + "name" => $video["user"]["name"], + "url" => $video["user"]["link"], + "avatar" => $avatar + ], + "date" => strtotime($video["created_time"]), + "duration" => (int)$video["duration"], + "views" => (int)$video["stats"]["plays"], + "thumb" => [ + "ratio" => "16:9", + "url" => $video["pictures"]["base_link"] + ], + "url" => $video["link"] + ]; + } + break; + + case "ondemand": + foreach($json["data"] as $video){ + + $video = $video["ondemand"]; + + $description = []; + if(isset($video["metadata"]["interactions"]["rent"]["display_price"])){ + + $description[] = "Rent for " . $video["metadata"]["interactions"]["rent"]["display_price"]; + } + + if(isset($video["metadata"]["interactions"]["buy"]["display_price"])){ + + $description[] = "Buy for " . $video["metadata"]["interactions"]["buy"]["display_price"]; + } + + $description = implode(", ", $description); + + $out["video"][] = [ + "title" => $video["name"], + "description" => $description, + "author" => [ + "name" => null, + "url" => null, + "avatar" => null + ], + "date" => null, + "duration" => null, + "views" => null, + "thumb" => [ + "ratio" => "9:16", + "url" => $video["pictures"]["sizes"][0]["link"] + ], + "url" => $video["link"] + ]; + } + break; + + case "people": + foreach($json["data"] as $user){ + + $user = $user["people"]; + + if( + isset($user["pictures"]["sizes"]) && + count($user["pictures"]["sizes"]) !== 0 + ){ + + $thumb = [ + "ratio" => "1:1", + "url" => $user["pictures"]["sizes"][count($user["pictures"]["sizes"]) - 1]["link"] + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["author"][] = [ + "title" => $user["name"], + "followers" => (int)$user["metadata"]["connections"]["followers"]["total"], + "description" => $user["metadata"]["public_videos"]["total"] . " videos.", + "thumb" => $thumb, + "url" => $user["link"] + ]; + } + break; + + case "channel": + case "group": + foreach($json["data"] as $channel){ + + $channel = $channel[$npt["filter_type"]]; + + if( + isset($channel["pictures"]["sizes"]) && + count($channel["pictures"]["sizes"]) !== 0 + ){ + + $thumb = [ + "ratio" => "16:9", + "url" => $channel["pictures"]["sizes"][count($channel["pictures"]["sizes"]) - 1]["link"] + ]; + }else{ + + $thumb = [ + "ratio" => null, + "url" => null + ]; + } + + $out["author"][] = [ + "title" => $channel["name"], + "followers" => (int)$channel["metadata"]["connections"]["users"]["total"], + "description" => $channel["metadata"]["connections"]["videos"]["total"] . " videos.", + "thumb" => $thumb, + "url" => $channel["link"] + ]; + } + break; + } + + // + // get next page + // + if( + isset($json["paging"]["next"]) && + is_string($json["paging"]["next"]) + ){ + + $out["npt"] = + $this->backend + ->store( + json_encode([ + "npt" => $json["paging"]["next"], + "pagetype" => $pagetype + ]), + "videos", + $proxy + ); + } + + return $out; + } + + private function get_jwt(&$proxy){ + + // + // get jwt token + // it's probably safe to cache this across proxies, cause the jwt doesnt contain an userID + // only an appID, whatever shit that is + // we can only cache it for 5 minutes though, otherwise vimeo cries about it + // + if($proxy === null){ + + $proxy = $this->backend->get_ip(); + } + + $jwt = apcu_fetch("vimeo_jwt"); + + if($jwt === false){ + /* + $html = + $this->get( + $proxy, + "https://vimeo.com/search", + [], + false + ); + + $this->fuckhtml->load($html); + + $captcha = + $this->fuckhtml + ->getElementsByTagName( + "title" + ); + + if( + count($captcha) !== 0 && + $this->fuckhtml + ->getTextContent( + $captcha[0] + ) == "Vimeo / CAPTCHA Challenge" + ){ + + throw new Exception("Vimeo returned a Captcha"); + } + + $html = + explode( + '<script id="viewer-bootstrap" type="application/json">', + $html, + 2 + ); + + if(count($html) !== 2){ + + throw new Exception("Failed to find JWT json"); + } + + $jwt = + json_decode( + $this->fuckhtml + ->extract_json( + $html[1] + ), + true + ); + + if($jwt === null){ + + throw new Exception("Failed to decode JWT json"); + } + + if(!isset($jwt["jwt"])){ + + throw new Exception("Failed to grep JWT"); + } + + $jwt = $jwt["jwt"]; + */ + + try{ + $json = + $this->get( + $proxy, + "https://vimeo.com/_next/jwt", + [], + false + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JWT token"); + } + + $this->fuckhtml->load($json); + + $captcha = + $this->fuckhtml + ->getElementsByTagName( + "title" + ); + + if( + count($captcha) !== 0 && + $this->fuckhtml + ->getTextContent( + $captcha[0] + ) == "Vimeo / CAPTCHA Challenge" + ){ + + throw new Exception("Vimeo returned a Captcha"); + } + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("The JWT object could not be decoded"); + } + + if(!isset($json["token"])){ + + throw new Exception("Vimeo did not return a JWT"); + } + + $jwt = $json["token"]; + + apcu_store("vimeo_jwt", $jwt, 300); + } + + return $jwt; + } + + private function titledots($title){ + + $substr = substr($title, -3); + + if( + $substr == "..." || + $substr == "…" + ){ + + return trim(substr($title, 0, -3), " \n\r\t\v\x00\0\x0B\xc2\xa0"); + } + + return trim($title, " \n\r\t\v\x00\0\x0B\xc2\xa0"); + } + + private function limitstrlen($text){ + + return + explode( + "\n", + wordwrap( + str_replace( + ["\n\r", "\r\n", "\n", "\r"], + " ", + $text + ), + 300, + "\n" + ), + 2 + )[0]; + } +} diff --git a/scraper/vsco.php b/scraper/vsco.php new file mode 100644 index 0000000..8a7f057 --- /dev/null +++ b/scraper/vsco.php @@ -0,0 +1,257 @@ +<?php + +class vsco{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("vsco"); + } + + public function getfilters($page){ + + return []; + } + + private function get($proxy, $url, $get = [], $bearer = null){ + + $curlproc = curl_init(); + + if($get !== []){ + $get_tmp = http_build_query($get); + $url .= "?" . $get_tmp; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + + if($bearer === null){ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: same-origin", + "Sec-Fetch-User: ?1", + "Priority: u=0, i", + "TE: trailers"] + ); + }else{ + + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: */*", + "Accept-Language: en-US", + "Accept-Encoding: gzip", + "Referer: https://vsco.co/search/images/" . urlencode($get["query"]), + "authorization: Bearer " . $bearer, + "content-type: application/json", + "x-client-build: 1", + "x-client-platform: web", + "DNT: 1", + "Sec-GPC: 1", + "Connection: keep-alive", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-origin", + "Priority: u=0", + "TE: trailers"] + ); + } + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + // http2 bypass + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function image($get){ + + if($get["npt"]){ + + [$data, $proxy] = + $this->backend->get( + $get["npt"], "images" + ); + + $data = json_decode($data, true); + + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + + // get bearer token + try{ + + $html = + $this->get( + $proxy, + "https://vsco.co/feed" + ); + + }catch(Exception $error){ + + throw new Exception("Failed to fetch feed page"); + } + + preg_match( + '/"tkn":"([A-z0-9]+)"/', + $html, + $bearer + ); + + if(!isset($bearer[1])){ + + throw new Exception("Failed to grep bearer token"); + } + + $data = [ + "pagination" => [ + "query" => $search, + "page" => 0, + "size" => 100 + ], + "bearer" => $bearer[1] + ]; + } + + try{ + + $json = + $this->get( + $proxy, + "https://vsco.co/api/2.0/search/images", + $data["pagination"], + $data["bearer"] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + if(!isset($json["results"])){ + + throw new Exception("Failed to access results object"); + } + + foreach($json["results"] as $image){ + + $image_domain = parse_url("https://" . $image["responsive_url"], PHP_URL_HOST); + $thumbnail = explode($image_domain, $image["responsive_url"], 2)[1]; + + if(substr($thumbnail, 0, 3) != "/1/"){ + + $thumbnail = + preg_replace( + '/^\/[^\/]+/', + "", + $thumbnail + ); + } + + $thumbnail = "https://img.vsco.co/cdn-cgi/image/width=480,height=360" . $thumbnail; + $size = + $this->image_ratio( + (int)$image["dimensions"]["width"], + (int)$image["dimensions"]["height"] + ); + + $out["image"][] = [ + "title" => $image["description"], + "source" => [ + [ + "url" => "https://" . $image["responsive_url"], + "width" => (int)$image["dimensions"]["width"], + "height" => (int)$image["dimensions"]["height"] + ], + [ + "url" => $thumbnail, + "width" => $size[0], + "height" => $size[1] + ] + ], + "url" => "https://" . $image["grid"]["domain"] . "/media/" . $image["imageId"] + ]; + } + + // get NPT + $max_page = ceil($json["total"] / 100); + $data["pagination"]["page"]++; + + if($max_page > $data["pagination"]["page"]){ + + $out["npt"] = + $this->backend->store( + json_encode($data), + "images", + $proxy + ); + } + + return $out; + } + + private function image_ratio($width, $height){ + + $ratio = [ + 480 / $width, + 360 / $height + ]; + + if($ratio[0] < $ratio[1]){ + + $ratio = $ratio[0]; + }else{ + + $ratio = $ratio[1]; + } + + return [ + floor($width * $ratio), + floor($height * $ratio) + ]; + } +} diff --git a/scraper/wiby.php b/scraper/wiby.php new file mode 100644 index 0000000..59f723c --- /dev/null +++ b/scraper/wiby.php @@ -0,0 +1,246 @@ +<?php + +class wiby{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("wiby"); + } + + public function getfilters($page){ + + if($page != "web"){ + + return []; + } + + return [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "no" => "No" + ] + ], + "date" => [ + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "day" => "Past day", + "week" => "Past week", + "month" => "Past month", + "year" => "Past year", + ] + ] + ]; + } + + private function get($proxy, $url, $get = [], $nsfw){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Cookie: ws={$nsfw}", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function web($get){ + + if($get["npt"]){ + + [$q, $proxy] = $this->backend->get($get["npt"], "web"); + $q = json_decode($q, true); + + $nsfw = $q["nsfw"]; + unset($q["nsfw"]); + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + $date = $get["date"]; + $nsfw = $get["nsfw"] == "yes" ? "0" : "1"; + + $search = + str_replace( + [ + "!g", + "!gi", + "!gv", + "!gm", + "!b", + "!bi", + "!bv", + "!bm", + "!td", + "!tw", + "!tm", + "!ty", + "&g", + "&gi", + "&gv", + "&gm", + "&b", + "&bi", + "&bv", + "&bm", + "&td", + "&tw", + "&tm", + "&ty", + ], + "", + $search + ); + + switch($date){ + + case "day": $search = "!td " . $search; break; + case "week": $search = "!tw " . $search; break; + case "month": $search = "!tm " . $search; break; + case "year": $search = "!ty " . $search; break; + } + + $q = [ + "q" => $search + ]; + } + + try{ + $html = $this->get( + $proxy, + "https://wiby.me/", + $q, + $nsfw + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch search page"); + } + + preg_match( + '/<p class="pin"><blockquote>(?:<\/p>)?<br><a class="more" href="\/\?q=[^"]+&p=([0-9]+)">Find more\.\.\.<\/a><\/blockquote>/', + $html, + $nextpage + ); + + if(count($nextpage) === 0){ + + $nextpage = null; + }else{ + + $nextpage = + $this->backend->store( + json_encode([ + "q" => $q["q"], + "p" => (int)$nextpage[1], + "nsfw" => $nsfw + ]), + "web", + $proxy + ); + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => $nextpage, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + preg_match_all( + '/<blockquote>[\s]*<a .* href="(.*)">(.*)<\/a>.*<p>(.*)<\/p>[\s]*<\/blockquote>/Ui', + $html, + $links + ); + + for($i=0; $i<count($links[0]); $i++){ + + $out["web"][] = [ + "title" => $this->unescapehtml(trim($links[2][$i])), + "description" => $this->unescapehtml(trim(strip_tags($links[3][$i]), ".\n\r ")), + "url" => trim($links[1][$i]), + "date" => null, + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => [], + "table" => [] + ]; + } + + return $out; + } + + private function unescapehtml($str){ + + return html_entity_decode( + str_replace( + [ + "<br>", + "<br/>", + "</br>", + "<BR>", + "<BR/>", + "</BR>", + ], + "\n", + $str + ), + ENT_QUOTES | ENT_XML1, 'UTF-8' + ); + } +} diff --git a/scraper/yandex.php b/scraper/yandex.php new file mode 100644 index 0000000..f73c3fd --- /dev/null +++ b/scraper/yandex.php @@ -0,0 +1,1248 @@ +<?php + +class yandex{ + + /* + curl functions + */ + public function __construct(){ + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + + include "lib/backend.php"; + // backend included in the scraper functions + } + + private function get($proxy, $url, $get = [], $nsfw, $get_cookie = 1){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + // extract "i" cookie + if($get_cookie === 0){ + + $cookies_tmp = []; + curl_setopt($curlproc, CURLOPT_HEADERFUNCTION, function($curlproc, $header) use (&$cookies_tmp){ + + $length = strlen($header); + + $header = explode(":", $header, 2); + + if(trim(strtolower($header[0])) == "set-cookie"){ + + $cookie_tmp = explode("=", trim($header[1]), 2); + + $cookies_tmp[trim($cookie_tmp[0])] = + explode(";", $cookie_tmp[1], 2)[0]; + } + + return $length; + }); + } + + switch($nsfw){ + case "yes": $nsfw = "0"; break; + case "maybe": $nsfw = "1"; break; + case "no": $nsfw = "2"; break; + } + + switch($get_cookie){ + + case 0: + $cookie = ""; + break; + + case 1: + $cookie = "Cookie: yp=" . (time() - 4000033) . ".szm.1:1920x1080:876x1000#" . time() . ".sp.family:" . $nsfw; + break; + + default: + $cookie = "Cookie: i=" . $get_cookie; + } + + $headers = + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Encoding: gzip", + "Accept-Language: en-US,en;q=0.5", + "DNT: 1", + $cookie, + "Referer: https://yandex.com/images/search", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: cross-site", + "Upgrade-Insecure-Requests: 1"]; + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if($get_cookie === 0){ + + if(isset($cookies_tmp["i"])){ + + return $cookies_tmp["i"]; + }else{ + + throw new Exception("Failed to get Yandex clearance cookie"); + } + } + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function getfilters($pagetype){ + + switch($pagetype){ + + case "web": + return [ + "lang" => [ + "display" => "Language", + "option" => [ + "any" => "Any language", + "en" => "English", + "ru" => "Russian", + "be" => "Belorussian", + "fr" => "French", + "de" => "German", + "id" => "Indonesian", + "kk" => "Kazakh", + "tt" => "Tatar", + "tr" => "Turkish", + "uk" => "Ukrainian" + ] + ], + "newer" => [ + "display" => "Newer than", + "option" => "_DATE" + ], + "older" => [ + "display" => "Older than", + "option" => "_DATE" + ] + ]; + break; + + case "images": + return + [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "maybe" => "Maybe", + "no" => "No" + ] + ], + "time" => [ + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "week" => "Last week" + ] + ], + "size" => [ + "display" => "Size", + "option" => [ + "any" => "Any size", + "small" => "Small", + "medium" => "Medium", + "large" => "Large", + "wallpaper" => "Wallpaper" + ] + ], + "color" => [ + "display" => "Colors", + "option" => [ + "any" => "All colors", + "color" => "Color images only", + "gray" => "Black and white", + "red" => "Red", + "orange" => "Orange", + "yellow" => "Yellow", + "cyan" => "Cyan", + "green" => "Green", + "blue" => "Blue", + "violet" => "Purple", + "white" => "White", + "black" => "Black" + ] + ], + "type" => [ + "display" => "Type", + "option" => [ + "any" => "All types", + "photo" => "Photos", + "clipart" => "White background", + "lineart" => "Drawings and sketches", + "face" => "People", + "demotivator" => "Demotivators" + ] + ], + "layout" => [ + "display" => "Layout", + "option" => [ + "any" => "All layouts", + "horizontal" => "Horizontal", + "vertical" => "Vertical", + "square" => "Square" + ] + ], + "format" => [ + "display" => "Format", + "option" => [ + "any" => "Any format", + "jpeg" => "JPEG", + "png" => "PNG", + "gif" => "GIF" + ] + ] + ]; + break; + + case "videos": + return [ + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "maybe" => "Maybe", + "no" => "No" + ] + ], + "time" => [ + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "9" => "Recently" + ] + ], + "duration" => [ + "display" => "Duration", + "option" => [ + "any" => "Any duration", + "short" => "Short" + ] + ] + ]; + break; + } + } + + public function web($get){ + + $this->backend = new backend("yandex_w"); + + // has captcha + // https://yandex.com/search/touch/?text=lol&app_platform=android&appsearch_header=1&ui=webmobileapp.yandex&app_version=23070603&app_id=ru.yandex.searchplugin&search_source=yandexcom_touch_native&clid=2218567 + + // https://yandex.com/search/site/?text=minecraft&web=1&frame=1&v=2.0&searchid=3131712 + // &within=777&from_day=26&from_month=8&from_year=2023&to_day=26&to_month=8&to_year=2023 + + // get clearance cookie + if(($cookie = apcu_fetch("yandexweb_cookie")) === false){ + + $proxy = $this->backend->get_ip(); + + $cookie = + $this->get( + $proxy, + "https://yandex.ru/support2/smart-captcha/ru/", + [], + false, + 0 + ); + + apcu_store("yandexweb_cookie", $cookie); + } + + if($get["npt"]){ + + [$npt, $proxy] = $this->backend->get($get["npt"], "web"); + + $html = + $this->get( + $proxy, + "https://yandex.com" . $npt, + [], + "yes", + $cookie + ); + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = !isset($proxy) ? $this->backend->get_ip() : $proxy; + $lang = $get["lang"]; + $older = $get["older"]; + $newer = $get["newer"]; + + $params = [ + "text" => $search, + "web" => "1", + "frame" => "1", + "searchid" => "3131712" + ]; + + if($lang != "any"){ + + $params["lang"] = $lang; + } + + if( + $newer === false && + $older !== false + ){ + + $newer = 0; + } + + if($newer !== false){ + + $params["from_day"] = date("j", $newer); + $params["from_month"] = date("n", $newer); + $params["from_year"] = date("Y", $newer); + + if($older === false){ + + $older = time(); + } + + $params["to_day"] = date("j", $older); + $params["to_month"] = date("n", $older); + $params["to_year"] = date("Y", $older); + } + + try{ + $html = + $this->get( + $proxy, + "https://yandex.com/search/site/", + $params, + "yes", + $cookie + ); + }catch(Exception $error){ + + throw new Exception("Could not get search page"); + } + + /* + $handle = fopen("scraper/yandex.html", "r"); + $html = fread($handle, filesize("scraper/yandex.html")); + fclose($handle);*/ + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + $this->fuckhtml->load($html); + + // Scrape page blocked error + $title = + $this->fuckhtml + ->getElementsByTagName("title"); + + if( + count($title) !== 0 && + $title[0]["innerHTML"] == "403" + ){ + + throw new Exception("Yandex blocked this proxy or 4get instance."); + } + + // get nextpage + $npt = + $this->fuckhtml + ->getElementsByClassName( + "b-pager__next", + "a" + ); + + if(count($npt) !== 0){ + + $out["npt"] = + $this->backend->store( + $this->fuckhtml + ->getTextContent( + $npt + [0] + ["attributes"] + ["href"] + ), + "web", + $proxy + ); + } + + // get items + $items = + $this->fuckhtml + ->getElementsByClassName( + "b-serp-item", + "li" + ); + + foreach($items as $item){ + + $this->fuckhtml->load($item); + + $link = + $this->fuckhtml + ->getElementsByClassName( + "b-serp-item__title-link", + "a" + )[0]; + + $out["web"][] = [ + "title" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $link + ) + ), + "description" => + $this->titledots( + $this->fuckhtml + ->getTextContent( + $this->fuckhtml + ->getElementsByClassName( + "b-serp-item__text", + "div" + )[0] + ) + ), + "url" => + $this->fuckhtml + ->getTextContent( + $link + ["attributes"] + ["href"] + ), + "date" => null, + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => [], + "table" => [] + ]; + } + + return $out; + } + + public function image($get){ + + $this->backend = new backend("yandex_i"); + + if($get["npt"]){ + + [$request, $proxy] = + $this->backend->get( + $get["npt"], + "images" + ); + + $request = json_decode($request, true); + + $nsfw = $request["nsfw"]; + unset($request["nsfw"]); + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + $nsfw = $get["nsfw"]; + $time = $get["time"]; + $size = $get["size"]; + $color = $get["color"]; + $type = $get["type"]; + $layout = $get["layout"]; + $format = $get["format"]; + /* + $handle = fopen("scraper/yandex.json", "r"); + $json = fread($handle, filesize("scraper/yandex.json")); + fclose($handle);*/ + + // SIZE + // large + // 227.0=1;203.0=1;76fe94.0=1;41d251.0=1;75.0=1;371.0=1;291.0=1;307.0=1;f797ee.0=1;1cf7c2.0=1;deca32.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&isize=large&suggest_reqid=486139416166165501540886508227485&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // medium + // 227.0=1;203.0=1;76fe94.0=1;41d251.0=1;75.0=1;371.0=1;291.0=1;307.0=1;f797ee.0=1;1cf7c2.0=1;deca32.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&isize=medium&suggest_reqid=486139416166165501540886508227485&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // small + // 227.0=1;203.0=1;76fe94.0=1;41d251.0=1;75.0=1;371.0=1;291.0=1;307.0=1;f797ee.0=1;1cf7c2.0=1;deca32.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&isize=small&suggest_reqid=486139416166165501540886508227485&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // ORIENTATION + // Horizontal + // 227.0=1;203.0=1;76fe94.0=1;41d251.0=1;75.0=1;371.0=1;291.0=1;307.0=1;f797ee.0=1;1cf7c2.0=1;deca32.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&iorient=horizontal&suggest_reqid=486139416166165501540886508227485&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Vertical + // 227.0=1;203.0=1;76fe94.0=1;41d251.0=1;75.0=1;371.0=1;291.0=1;307.0=1;f797ee.0=1;1cf7c2.0=1;deca32.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&iorient=vertical&suggest_reqid=486139416166165501540886508227485&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Square + // 227.0=1;203.0=1;76fe94.0=1;41d251.0=1;75.0=1;371.0=1;291.0=1;307.0=1;f797ee.0=1;1cf7c2.0=1;deca32.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&iorient=square&suggest_reqid=486139416166165501540886508227485&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // TYPE + // Photos + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&text=minecraft&type=photo&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // White background + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&text=minecraft&type=clipart&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Drawings and sketches + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&text=minecraft&type=lineart&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // People + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&text=minecraft&type=face&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Demotivators + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&text=minecraft&type=demotivator&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // COLOR + // Color images only + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&icolor=color&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Black and white + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&icolor=gray&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Red + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&icolor=red&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Orange + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&icolor=orange&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Yellow + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&icolor=yellow&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Cyan + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&icolor=cyan&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Green + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&icolor=green&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Blue + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&icolor=blue&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Purple + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&icolor=violet&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // White + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&icolor=white&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // Black + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&icolor=black&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // FORMAT + // jpeg + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&itype=jpg&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // png + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&itype=png&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // gif + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&itype=gifan&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // RECENT + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&recent=7D&text=minecraft&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + // WALLPAPER + // 307.0=1;371.0=1;291.0=1;203.0=1;deca32.0=1;f797ee.0=1;1cf7c2.0=1;41d251.0=1;267.0=1;bde197.0=1"},"extraContent":{"names":["i-react-ajax-adapter"]}}}&yu=4861394161661655015&isize=wallpaper&text=minecraft&wp=wh16x9_1920x1080&uinfo=sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080 + + + $request = [ + "format" => "json", + "request" => [ + "blocks" => [ + [ + "block" => "extra-content", + "params" => (object)[], + "version" => 2 + ], + [ + "block" => "i-global__params:ajax", + "params" => (object)[], + "version" => 2 + ], + [ + "block" => "search2:ajax", + "params" => (object)[], + "version" => 2 + ], + [ + "block" => "preview__isWallpaper", + "params" => (object)[], + "version" => 2 + ], + [ + "block" => "content_type_search", + "params" => (object)[], + "version" => 2 + ], + [ + "block" => "serp-controller", + "params" => (object)[], + "version" => 2 + ], + [ + "block" => "cookies_ajax", + "params" => (object)[], + "version" => 2 + ], + [ + "block" => "advanced-search-block", + "params" => (object)[], + "version" => 2 + ] + ], + "metadata" => [ + "bundles" => [ + "lb" => "AS?(E<X120" + ], + "assets" => [ + // las base + "las" => "justifier-height=1;justifier-setheight=1;fitimages-height=1;justifier-fitincuts=1;react-with-dom=1;" + + // las default + //"las" => "justifier-height=1;justifier-setheight=1;fitimages-height=1;justifier-fitincuts=1;react-with-dom=1;227.0=1;203.0=1;76fe94.0=1;215f96.0=1;75.0=1" + ], + "extraContent" => [ + "names" => [ + "i-react-ajax-adapter" + ] + ] + ] + ] + ]; + + /* + Apply filters + */ + if($time == "week"){ + $request["recent"] = "7D"; + } + + if($size != "any"){ + + $request["isize"] = $size; + } + + if($type != "any"){ + + $request["type"] = $type; + } + + if($color != "any"){ + + $request["icolor"] = $color; + } + + if($layout != "any"){ + + $request["iorient"] = $layout; + } + + if($format != "any"){ + + $request["itype"] = $format; + } + + $request["text"] = $search; + $request["uinfo"] = "sw-1920-sh-1080-ww-1125-wh-999-pd-1-wp-16x9_1920x1080"; + + $request["request"] = json_encode($request["request"]); + } + + try{ + $json = $this->get( + $proxy, + "https://yandex.com/images/search", + $request, + $nsfw, + "yandex_i" + ); + }catch(Exception $err){ + + throw new Exception("Failed to get JSON"); + } + + /* + $handle = fopen("scraper/yandex.json", "r"); + $json = fread($handle, filesize("scraper/yandex.json")); + fclose($handle);*/ + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + if( + isset($json["type"]) && + $json["type"] == "captcha" + ){ + + throw new Exception("Yandex blocked this 4get instance. Please try again in ~7 minutes."); + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + // get html + $html = ""; + foreach($json["blocks"] as $block){ + + $html .= $block["html"]; + // get next page + if( + isset($block["params"]["nextPageUrl"]) && + !empty($block["params"]["nextPageUrl"]) + ){ + + $request["nsfw"] = $nsfw; + + if(isset($request["p"])){ + + $request["p"]++; + }else{ + + $request["p"] = 1; + } + + $out["npt"] = + $this->backend->store( + json_encode($request), + "images", + $proxy + ); + } + } + + $this->fuckhtml->load($html); + + // get search results + $data = null; + + foreach( + $this->fuckhtml + ->getElementsByClassName( + "Root", + "div" + ) as $div + ){ + + if(isset($div["attributes"]["data-state"])){ + + $tmp = json_decode( + $this->fuckhtml + ->getTextContent( + $div["attributes"]["data-state"] + ), + true + ); + + if(isset($tmp["initialState"]["serpList"])){ + + $data = $tmp; + break; + } + } + } + + if($data === null){ + + throw new Exception("Failed to extract JSON"); + } + + foreach($data["initialState"]["serpList"]["items"]["entities"] as $image){ + + $title = [html_entity_decode($image["snippet"]["title"], ENT_QUOTES | ENT_HTML5)]; + + if(isset($image["snippet"]["text"])){ + + $title[] = html_entity_decode($image["snippet"]["text"], ENT_QUOTES | ENT_HTML5); + } + + $tmp = [ + "title" => + $this->fuckhtml + ->getTextContent( + $this->titledots( + implode(": ", $title) + ) + ), + "source" => [], + "url" => htmlspecialchars_decode($image["snippet"]["url"]) + ]; + + // add preview URL + $tmp["source"][] = [ + "url" => htmlspecialchars_decode($image["viewerData"]["preview"][0]["url"]), + "width" => (int)$image["viewerData"]["preview"][0]["w"], + "height" => (int)$image["viewerData"]["preview"][0]["h"], + ]; + + foreach($image["viewerData"]["dups"] as $dup){ + + $tmp["source"][] = [ + "url" => htmlspecialchars_decode($dup["url"]), + "width" => (int)$dup["w"], + "height" => (int)$dup["h"], + ]; + } + + $tmp["source"][] = [ + "url" => + preg_replace( + '/^\/\//', + "https://", + htmlspecialchars_decode($image["viewerData"]["thumb"]["url"]) + ), + "width" => (int)$image["viewerData"]["thumb"]["w"], + "height" => (int)$image["viewerData"]["thumb"]["h"] + ]; + + $out["image"][] = $tmp; + } + + return $out; + } + + public function video($get){ + + $this->backend = new backend("yandex_v"); + + if($get["npt"]){ + + [$params, $proxy] = + $this->backend->get( + $get["npt"], + "video" + ); + + $params = json_decode($params, true); + + $nsfw = $params["nsfw"]; + unset($params["nsfw"]); + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + $nsfw = $get["nsfw"]; + $time = $get["time"]; + $duration = $get["duration"]; + + // https://yandex.com/video/search + // ?tmpl_version=releases/frontend/video/v1.1168.0#8d942de0f4ebc4eb6b8f3c24ffbd1f8dbc5bbe63 + // &format=json + // &request= + // { + // "blocks":[ + // {"block":"extra-content","params":{},"version":2}, + // {"block":"i-global__params:ajax","params":{},"version":2}, + // {"block":"search2:ajax","params":{},"version":2}, + // {"block":"vital-incut","params":{},"version":2}, + // {"block":"content_type_search","params":{},"version":2}, + // {"block":"serp-controller","params":{},"version":2}, + // {"block":"cookies_ajax","params":{},"version":2} + // ], + // "metadata":{ + // "bundles":{"lb":"^G]!q<X120"}, + // "assets":{"las":"react-with-dom=1;185.0=1;73.0=1;145.0=1;5a502a.0=1;32c342.0=1;b84ac8.0=1"}, + // "extraContent":{"names":["i-react-ajax-adapter"]} + // } + // } + // &yu=4861394161661655015 + // &from=tabbar + // &reqid=1693106278500184-6825210746979814879-balancer-l7leveler-kubr-yp-sas-7-BAL-4237 + // &suggest_reqid=486139416166165501562797413447032 + // &text=minecraft + + $params = [ + "tmpl_version" => "releases/frontend/video/v1.1168.0#8d942de0f4ebc4eb6b8f3c24ffbd1f8dbc5bbe63", + "format" => "json", + "request" => json_encode([ + "blocks" => [ + (object)[ + "block" => "extra-content", + "params" => (object)[], + "version" => 2 + ], + (object)[ + "block" => "i-global__params:ajax", + "params" => (object)[], + "version" => 2 + ], + (object)[ + "block" => "search2:ajax", + "params" => (object)[], + "version" => 2 + ], + (object)[ + "block" => "vital-incut", + "params" => (object)[], + "version" => 2 + ], + (object)[ + "block" => "content_type_search", + "params" => (object)[], + "version" => 2 + ], + (object)[ + "block" => "serp-controller", + "params" => (object)[], + "version" => 2 + ], + (object)[ + "block" => "cookies_ajax", + "params" => (object)[], + "version" => 2 + ] + ], + "metadata" => (object)[ + "bundles" => (object)[ + "lb" => "^G]!q<X120" + ], + "assets" => (object)[ + "las" => "react-with-dom=1;185.0=1;73.0=1;145.0=1;5a502a.0=1;32c342.0=1;b84ac8.0=1" + ], + "extraContent" => (object)[ + "names" => [ + "i-react-ajax-adapter" + ] + ] + ] + ]), + "text" => $search + ]; + + if($duration != "any"){ + + $params["duration"] = $duration; + } + + if($time != "any"){ + + $params["within"] = $time; + } + } + /* + $handle = fopen("scraper/yandex-video.json", "r"); + $json = fread($handle, filesize("scraper/yandex-video.json")); + fclose($handle); + */ + try{ + $json = + $this->get( + $proxy, + "https://yandex.com/video/search", + $params, + $nsfw, + "yandex_v" + ); + }catch(Exception $error){ + + throw new Exception("Could not fetch JSON"); + } + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Could not parse JSON"); + } + + if(!isset($json["blocks"])){ + + throw new Exception("Yandex blocked this 4get instance. Please try again in 7~ minutes."); + } + + $out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + $html = null; + foreach($json["blocks"] as $block){ + + if(isset($block["html"])){ + + $html .= $block["html"]; + } + } + + $this->fuckhtml->load($html); + + $div = + $this->fuckhtml + ->getElementsByTagName("div"); + + /* + Get nextpage + */ + $npt = + $this->fuckhtml + ->getElementsByClassName( + "more more_direction_next i-bem", + $div + ); + + if(count($npt) !== 0){ + + $params["p"] = "1"; + $params["nsfw"] = $nsfw; + $out["npt"] = + $this->backend->store( + json_encode($params), + "video", + $proxy + ); + } + + $items = + $this->fuckhtml + ->getElementsByClassName( + "serp-item", + $div + ); + + foreach($items as $item){ + + $data = + json_decode( + $this->fuckhtml + ->getTextContent( + $item["attributes"]["data-video"] + ), + true + ); + + $this->fuckhtml->load($item); + + $thumb = + $this->fuckhtml + ->getElementsByClassName( + "thumb-image__image", + "img" + ); + + $c = 1; + if(count($thumb) === 0){ + + $thumb = [ + "url" => null, + "ratio" => null + ]; + }else{ + + $thumb = [ + "url" => + str_replace( + "//", + "https://", + $this->fuckhtml + ->getTextContent( + $thumb + [0] + ["attributes"] + ["src"] + ), + $c + ), + "ratio" => "16:9" + ]; + } + + $smallinfos = + $this->fuckhtml + ->getElementsByClassName( + "serp-item__sitelinks-item", + "div" + ); + + $date = null; + $views = null; + $first = true; + + foreach($smallinfos as $info){ + + if($first){ + + $first = false; + continue; + } + + $info = + $this->fuckhtml + ->getTextContent( + $info + ); + + if($temp_date = strtotime($info)){ + + $date = $temp_date; + }else{ + + $views = $this->parseviews($info); + } + } + + $description = + $this->fuckhtml + ->getElementsByClassName( + "serp-item__text serp-item__text_visibleText_always", + "div" + ); + + if(count($description) === 0){ + + $description = null; + }else{ + + $description = + $this->titledots( + $this->fuckhtml + ->getTextContent( + $description[0] + ) + ); + } + + $out["video"][] = [ + "title" => + $this->fuckhtml + ->getTextContent( + $this->titledots( + $data["title"] + ) + ), + "description" => $description, + "author" => [ + "name" => null, + "url" => null, + "avatar" => null + ], + "date" => $date, + "duration" => + (int)$data + ["counters"] + ["toHostingLoaded"] + ["stredParams"] + ["duration"], + "views" => $views, + "thumb" => $thumb, + "url" => + str_replace( + "http://", + "https://", + $this->fuckhtml + ->getTextContent( + $data["counters"] + ["toHostingLoaded"] + ["postfix"] + ["href"] + ), + $c + ) + ]; + } + + return $out; + } + + private function parseviews($text){ + + $text = explode(" ", $text); + + $num = (float)$text[0]; + $mod = $text[1]; + + switch($mod){ + + case "bln.": $num = $num * 1000000000; break; + case "mln.": $num = $num * 1000000; break; + case "thsd.": $num = $num * 1000; break; + } + + return $num; + } + + private function titledots($title){ + + $substr = substr($title, -3); + + if( + $substr == "..." || + $substr == "…" + ){ + + return trim(substr($title, 0, -3)); + } + + return trim($title); + } +} diff --git a/scraper/yep.php b/scraper/yep.php new file mode 100644 index 0000000..bfe347f --- /dev/null +++ b/scraper/yep.php @@ -0,0 +1,741 @@ +<?php + +class yep{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("yep"); + + include "lib/fuckhtml.php"; + $this->fuckhtml = new fuckhtml(); + } + + public function getfilters($page){ + + return [ + "country" => [ + "display" => "Country", + "option" => [ + "all" => "All regions", + "af" => "Afghanistan", + "al" => "Albania", + "dz" => "Algeria", + "as" => "American Samoa", + "ad" => "Andorra", + "ao" => "Angola", + "ai" => "Anguilla", + "ag" => "Antigua and Barbuda", + "ar" => "Argentina", + "am" => "Armenia", + "aw" => "Aruba", + "au" => "Australia", + "at" => "Austria", + "az" => "Azerbaijan", + "bs" => "Bahamas", + "bh" => "Bahrain", + "bd" => "Bangladesh", + "bb" => "Barbados", + "by" => "Belarus", + "be" => "Belgium", + "bz" => "Belize", + "bj" => "Benin", + "bt" => "Bhutan", + "bo" => "Bolivia", + "ba" => "Bosnia and Herzegovina", + "bw" => "Botswana", + "br" => "Brazil", + "bn" => "Brunei Darussalam", + "bg" => "Bulgaria", + "bf" => "Burkina Faso", + "bi" => "Burundi", + "cv" => "Cabo Verde", + "kh" => "Cambodia", + "cm" => "Cameroon", + "ca" => "Canada", + "ky" => "Cayman Islands", + "cf" => "Central African Republic", + "td" => "Chad", + "cl" => "Chile", + "cn" => "China", + "co" => "Colombia", + "cg" => "Congo", + "cd" => "Congo, Democratic Republic", + "ck" => "Cook Islands", + "cr" => "Costa Rica", + "hr" => "Croatia", + "cu" => "Cuba", + "cy" => "Cyprus", + "cz" => "Czechia", + "ci" => "Côte d'Ivoire", + "dk" => "Denmark", + "dj" => "Djibouti", + "dm" => "Dominica", + "do" => "Dominican Republic", + "ec" => "Ecuador", + "eg" => "Egypt", + "sv" => "El Salvador", + "gq" => "Equatorial Guinea", + "ee" => "Estonia", + "et" => "Ethiopia", + "fo" => "Faroe Islands", + "fj" => "Fiji", + "fi" => "Finland", + "fr" => "France", + "gf" => "French Guiana", + "pf" => "French Polynesia", + "ga" => "Gabon", + "gm" => "Gambia", + "ge" => "Georgia", + "de" => "Germany", + "gh" => "Ghana", + "gi" => "Gibraltar", + "gr" => "Greece", + "gl" => "Greenland", + "gd" => "Grenada", + "gp" => "Guadeloupe", + "gu" => "Guam", + "gt" => "Guatemala", + "gg" => "Guernsey", + "gn" => "Guinea", + "gy" => "Guyana", + "ht" => "Haiti", + "hn" => "Honduras", + "hk" => "Hong Kong", + "hu" => "Hungary", + "is" => "Iceland", + "in" => "India", + "id" => "Indonesia", + "iq" => "Iraq", + "ie" => "Ireland", + "im" => "Isle of Man", + "il" => "Israel", + "it" => "Italy", + "jm" => "Jamaica", + "jp" => "Japan", + "je" => "Jersey", + "jo" => "Jordan", + "kz" => "Kazakhstan", + "ke" => "Kenya", + "ki" => "Kiribati", + "kw" => "Kuwait", + "kg" => "Kyrgyzstan", + "la" => "Lao People's Democratic Republic", + "lv" => "Latvia", + "lb" => "Lebanon", + "ls" => "Lesotho", + "ly" => "Libya", + "li" => "Liechtenstein", + "lt" => "Lithuania", + "lu" => "Luxembourg", + "mk" => "Macedonia", + "mg" => "Madagascar", + "mw" => "Malawi", + "my" => "Malaysia", + "mv" => "Maldives", + "ml" => "Mali", + "mt" => "Malta", + "mq" => "Martinique", + "mr" => "Mauritania", + "mu" => "Mauritius", + "yt" => "Mayotte", + "mx" => "Mexico", + "fm" => "Micronesia, Federated States of", + "md" => "Moldova", + "mc" => "Monaco", + "mn" => "Mongolia", + "me" => "Montenegro", + "ms" => "Montserrat", + "ma" => "Morocco", + "mz" => "Mozambique", + "mm" => "Myanmar", + "na" => "Namibia", + "nr" => "Nauru", + "np" => "Nepal", + "nl" => "Netherlands", + "nc" => "New Caledonia", + "nz" => "New Zealand", + "ni" => "Nicaragua", + "ne" => "Niger", + "ng" => "Nigeria", + "nu" => "Niue", + "no" => "Norway", + "om" => "Oman", + "pk" => "Pakistan", + "ps" => "Palestine, State of", + "pa" => "Panama", + "pg" => "Papua New Guinea", + "py" => "Paraguay", + "pe" => "Peru", + "ph" => "Philippines", + "pn" => "Pitcairn", + "pl" => "Poland", + "pt" => "Portugal", + "pr" => "Puerto Rico", + "qa" => "Qatar", + "ro" => "Romania", + "ru" => "Russian Federation", + "rw" => "Rwanda", + "re" => "Réunion", + "sh" => "Saint Helena", + "kn" => "Saint Kitts and Nevis", + "lc" => "Saint Lucia", + "vc" => "Saint Vincent and the Grenadines", + "ws" => "Samoa", + "sm" => "San Marino", + "st" => "Sao Tome and Principe", + "sa" => "Saudi Arabia", + "sn" => "Senegal", + "rs" => "Serbia", + "sc" => "Seychelles", + "sl" => "Sierra Leone", + "sg" => "Singapore", + "sk" => "Slovakia", + "si" => "Slovenia", + "sb" => "Solomon Islands", + "so" => "Somalia", + "kr" => "Sourth Korea", + "za" => "South Africa", + "es" => "Spain", + "lk" => "Sri Lanka", + "sr" => "Suriname", + "se" => "Sweden", + "ch" => "Switzerland", + "tw" => "Taiwan", + "tj" => "Tajikistan", + "tz" => "Tanzania", + "th" => "Thailand", + "tl" => "Timor-Leste", + "tg" => "Togo", + "tk" => "Tokelau", + "to" => "Tonga", + "tt" => "Trinidad and Tobago", + "tn" => "Tunisia", + "tr" => "Turkey", + "tm" => "Turkmenistan", + "ug" => "Uganda", + "ua" => "Ukraine", + "ae" => "United Arab Emirates", + "gb" => "United Kingdom", + "us" => "United States", + "uy" => "Uruguay", + "uz" => "Uzbekistan", + "vu" => "Vanuatu", + "ve" => "Venezuela", + "vn" => "Vietnam", + "vg" => "Virgin Islands, British", + "vi" => "Virgin Islands, U.S.", + "ye" => "Yemen", + "zm" => "Zambia", + "zw" => "Zimbabwe" + ] + ], + "nsfw" => [ + "display" => "NSFW", + "option" => [ + "yes" => "Yes", + "maybe" => "Maybe", + "no" => "No" + ] + ] + ]; + } + + private function get($proxy, $url, $get = []){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + // use http2 + curl_setopt($curlproc, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_2_0); + + // set ciphers + curl_setopt( + $curlproc, + CURLOPT_SSL_CIPHER_LIST, + "aes_128_gcm_sha_256,chacha20_poly1305_sha_256,aes_256_gcm_sha_384,ecdhe_ecdsa_aes_128_gcm_sha_256,ecdhe_rsa_aes_128_gcm_sha_256,ecdhe_ecdsa_chacha20_poly1305_sha_256,ecdhe_rsa_chacha20_poly1305_sha_256,ecdhe_ecdsa_aes_256_gcm_sha_384,ecdhe_rsa_aes_256_gcm_sha_384,ecdhe_ecdsa_aes_256_sha,ecdhe_ecdsa_aes_128_sha,ecdhe_rsa_aes_128_sha,ecdhe_rsa_aes_256_sha,rsa_aes_128_gcm_sha_256,rsa_aes_256_gcm_sha_384,rsa_aes_128_sha,rsa_aes_256_sha" + ); + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, + ["User-Agent: " . config::USER_AGENT, + "Accept: */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip, deflate, br, zstd", + "Referer: https://yep.com/", + "Origin: https://yep.com", + "DNT: 1", + "Connection: keep-alive", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: cors", + "Sec-Fetch-Site: same-site", + "Priority: u=4", + "TE: trailers"] + ); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + + + public function web($get){ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $country = $get["country"]; + $nsfw = $get["nsfw"]; + + switch($nsfw){ + + case "yes": $nsfw = "off"; break; + case "maybe": $nsfw = "moderate"; break; + case "no": $nsfw = "strict"; break; + } + + $out = [ + "status" => "ok", + "spelling" => [ + "type" => "no_correction", + "using" => null, + "correction" => null + ], + "npt" => null, + "answer" => [], + "web" => [], + "image" => [], + "video" => [], + "news" => [], + "related" => [] + ]; + + try{ + + // https://api.yep.com/fs/2/search?client=web&gl=CA&no_correct=false&q=undefined+variable+javascript&safeSearch=off&type=web + $json = + $this->get( + $this->backend->get_ip(), + "https://api.yep.com/fs/2/search", + [ + "client" => "web", + "gl" => $country == "all" ? $country : strtoupper($country), + "limit" => "99999", + "no_correct" => "false", + "q" => $search, + "safeSearch" => $nsfw, + "type" => "web" + ] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + $this->detect_cf($json); + + $json = json_decode($json, true); + //$json = json_decode(file_get_contents("scraper/yep.json"), true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + if(isset($json[1]["correction"])){ + + $out["spelling"] = [ + "type" => "not_many", + "using" => $search, + "correction" => $json[1]["correction"][1] + ]; + } + + if(isset($json[1]["results"])){ + foreach($json[1]["results"] as $item){ + + switch(strtolower($item["type"])){ + + case "organic": + $sublinks = []; + + if(isset($item["sitelinks"]["full"])){ + + foreach($item["sitelinks"]["full"] as $link){ + + $sublinks[] = [ + "title" => $link["title"], + "date" => null, + "description" => + $this->titledots( + strip_tags( + html_entity_decode( + $link["snippet"] + ) + ) + ), + "url" => $link["url"] + ]; + } + } + + $out["web"][] = [ + "title" => $item["title"], + "description" => + $this->titledots( + strip_tags( + html_entity_decode( + $item["snippet"] + ) + ) + ), + "url" => $item["url"], + "date" => strtotime($item["first_seen"]), + "type" => "web", + "thumb" => [ + "url" => null, + "ratio" => null + ], + "sublink" => $sublinks, + "table" => [] + ]; + break; + } + } + } + + if(isset($json[1]["featured_news"])){ + + foreach($json[1]["featured_news"] as $news){ + + $out["news"][] = [ + "title" => $news["title"], + "description" => + $this->titledots( + strip_tags( + html_entity_decode( + $news["snippet"] + ) + ) + ), + "date" => strtotime($news["first_seen"]), + "thumb" => + isset($news["img"]) ? + [ + "url" => $this->unshiturl($news["img"]), + "ratio" => "16:9" + ] : + [ + "url" => null, + "ratio" => null + ], + "url" => $news["url"] + ]; + } + } + + if(isset($json[1]["featured_images"])){ + + foreach($json[1]["featured_images"] as $image){ + + if( + $image["width"] !== 0 && + $image["height"] !== 0 + ){ + + $thumb_width = $image["width"] >= 260 ? 260 : $image["width"]; + $thumb_height = ceil($image["height"] * ($thumb_width / $image["width"])); + + $width = $image["width"]; + $height = $image["height"]; + }else{ + + $thumb_width = null; + $thumb_height = null; + $width = null; + $height = null; + } + + $out["image"][] = [ + "title" => $image["title"], + "source" => [ + [ + "url" => $image["image_id"], + "width" => $width, + "height" => $height + ], + [ + "url" => $image["src"], + "width" => $thumb_width, + "height" => $thumb_height + ] + ], + "url" => $image["host_page"] + ]; + } + } + + return $out; + } + + + + public function image($get){ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $country = $get["country"]; + $nsfw = $get["nsfw"]; + + switch($nsfw){ + + case "yes": $nsfw = "off"; break; + case "maybe": $nsfw = "moderate"; break; + case "no": $nsfw = "strict"; break; + } + + $out = [ + "status" => "ok", + "npt" => null, + "image" => [] + ]; + + try{ + + $json = + $this->get( + $this->backend->get_ip(), // no nextpage! + "https://api.yep.com/fs/2/search", + [ + "client" => "web", + "gl" => $country == "all" ? $country : strtoupper($country), + "no_correct" => "false", + "q" => $search, + "safeSearch" => $nsfw, + "type" => "images" + ] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + $this->detect_cf($json); + + $json = json_decode($json, true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + if(isset($json[1]["results"])){ + foreach($json[1]["results"] as $item){ + + if( + $item["width"] !== 0 && + $item["height"] !== 0 + ){ + + $thumb_width = $item["width"] >= 260 ? 260 : $item["width"]; + $thumb_height = ceil($item["height"] * ($thumb_width / $item["width"])); + + $width = $item["width"]; + $height = $item["height"]; + }else{ + + $thumb_width = null; + $thumb_height = null; + $width = null; + $height = null; + } + + $out["image"][] = [ + "title" => $item["title"], + "source" => [ + [ + "url" => $item["image_id"], + "width" => $width, + "height" => $height + ], + [ + "url" => $item["src"], + "width" => $thumb_width, + "height" => $thumb_height + ] + ], + "url" => $item["host_page"] + ]; + } + } + + return $out; + } + + + public function news($get){ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $country = $get["country"]; + $nsfw = $get["nsfw"]; + + switch($nsfw){ + + case "yes": $nsfw = "off"; break; + case "maybe": $nsfw = "moderate"; break; + case "no": $nsfw = "strict"; break; + } + + $out = [ + "status" => "ok", + "npt" => null, + "news" => [] + ]; + + try{ + + // https://api.yep.com/fs/2/search?client=web&gl=CA&no_correct=false&q=undefined+variable+javascript&safeSearch=off&type=web + $json = + $this->get( + $this->backend->get_ip(), + "https://api.yep.com/fs/2/search", + [ + "client" => "web", + "gl" => $country == "all" ? $country : strtoupper($country), + "limit" => "99999", + "no_correct" => "false", + "q" => $search, + "safeSearch" => $nsfw, + "type" => "news" + ] + ); + }catch(Exception $error){ + + throw new Exception("Failed to fetch JSON"); + } + + $this->detect_cf($json); + + $json = json_decode($json, true); + //$json = json_decode(file_get_contents("scraper/yep.json"), true); + + if($json === null){ + + throw new Exception("Failed to decode JSON"); + } + + if(isset($json[1]["results"])){ + foreach($json[1]["results"] as $item){ + + $out["news"][] = [ + "title" => $item["title"], + "author" => null, + "description" => + $this->titledots( + strip_tags( + html_entity_decode( + $item["snippet"] + ) + ) + ), + "date" => strtotime($item["first_seen"]), + "thumb" => + isset($item["img"]) ? + [ + "url" => $this->unshiturl($item["img"]), + "ratio" => "16:9" + ] : + [ + "url" => null, + "ratio" => null + ], + "url" => $item["url"] + ]; + } + } + + return $out; + } + + + private function detect_cf($payload){ + + // detect cloudflare page + $this->fuckhtml->load($payload); + + if( + count( + $this->fuckhtml + ->getElementsByClassName( + "cf-wrapper", + "div" + ) + ) !== 0 + ){ + + throw new Exception("Blocked by Cloudflare. Please follow curl-impersonate installation instructions"); + } + } + + + private function titledots($title){ + + $substr = substr($title, -4); + + if( + strpos($substr, "...") !== false || + strpos($substr, "…") !== false + ){ + + return trim(substr($title, 0, -4)); + } + + return trim($title); + } + + private function unshiturl($url){ + + $newurl = parse_url($url, PHP_URL_QUERY); + parse_str($newurl, $newurl); + + if(isset($newurl["url"])){ + + return $newurl["url"]; + } + + return $url; + } +} diff --git a/scraper/yt.php b/scraper/yt.php new file mode 100644 index 0000000..a27fd82 --- /dev/null +++ b/scraper/yt.php @@ -0,0 +1,1727 @@ +<?php + +//$yt = new youtube(); +//header("Content-Type: application/json"); +//echo json_encode($yt->video("minecraft", null, "today", "any", "any", "live", "relevance")); + +class yt{ + + public function __construct(){ + + include "lib/backend.php"; + $this->backend = new backend("yt"); + } + + public function getfilters($page){ + + if($page != "videos"){ + + return []; + } + + return [ + "date" => [ + "display" => "Time posted", + "option" => [ + "any" => "Any time", + "hour" => "Last hour", + "today" => "Today", + "week" => "This week", + "month" => "This month", + "year" => "This year" + ] + ], + "type" => [ + "display" => "Type", + "option" => [ + "video" => "Video", + "channel" => "Channel", + "playlist" => "Playlist", + "Movie" => "Movie" + ] + ], + "duration" => [ + "display" => "Duration", + "option" => [ + "any" => "Any duration", + "short" => "Short (>4min)", + "medium" => "Medium (4-20min)", + "long" => "Long (<20min)" + ] + ], + "feature" => [ + "display" => "Feature", + "option" => [ + "any" => "No features", + "live" => "Live", + "4k" => "4K", + "hd" => "HD", + "subtitles" => "Subtitles/CC", + "creativecommons" => "Creative Commons", + "360" => "VR 360°", + "vr180" => "VR 180°", + "3d" => "3D", + "hdr" => "HDR" + ] + ], + "sort" => [ + "display" => "Sort by", + "option" => [ + "relevance" => "Relevance", + "upload_date" => "Upload date", + "view_count" => "View count", + "rating" => "Rating" + ] + ] + ]; + } + + private function ytfilter($date, $type, $duration, $feature, $sort){ + + // ------------ + // INCOMPATIBLE FILTERS + // channel,playlist DURATION, FEATURES, SORT BY + // Movie Features=[live, subtitles, creative commons, 3d] + + // live, 3D + // Type[channel, playlist, movie] + + // UPLOAD DATE, DURATION, 4k, 360, VR180, HDR + // Type[channel, playlist] + + // ----------- + + // MUST BE TOGETHER + // Relevance,upload date Type=Video + + switch($type){ + + case "channel": + case "playlist": + if($duration != "any"){ $duration = "any"; } + if($feature != "any"){ $feature = "any"; } + if($sort != "any"){ $sort = "any"; } + break; + + case "movie": + if( + in_array( + $feature, + [ + "live", + "subtitles", + "creative_commons", + "3d" + ], + ) + ){ + + $feature = "any"; + } + break; + } + + switch($feature){ + + case "live": + case "3d": + if( + in_array( + $type, + [ + "channel", + "playlist", + "movie" + ], + ) + ){ + + $type = "video"; + } + break; + } + + if( + ( + $date != "any" || + $duration != "any" || + $feature == "4k" || + $feature == "360" || + $feature == "vr180" || + $feature == "hdr" + ) && + ( + $type == "channel" || + $type == "playlist" + ) + ){ + + $type = "video"; + } + + if( + $date == "any" && + $type == "video" && + $duration == "any" && + $feature == "any" && + $sort == "relevance" + ){ + + return null; + } + + //print_r([$date, $type, $duration, $feature, $sort]); + + /* + Encode hex data + */ + + // UPLOAD DATE + // hour EgQIARAB 12 04 08 01 10 01 + // today EgQIAhAB 12 04 08 02 10 01 + // week EgQIAxAB 12 04 08 03 10 01 + // month EgQIBBAB 12 04 08 04 10 01 + // year EgQIBRAB 12 04 08 05 10 01 + + // TYPE + // video EgIQAQ%253D%253D 12 02 10 01 + // channel EgIQAg%253D%253D 12 02 10 02 + // playlist EgIQAw%253D%253D 12 02 10 03 + // movie EgIQBA%253D%253D 12 02 10 04 + + // DURATION + // -4min EgIYAQ%253D%253D 12 02 18 01 + // 4-20min EgIYAw%253D%253D 12 02 18 03 + // 20+min EgIYAg%253D%253D 12 02 18 02 + + // FEATURE + // live EgJAAQ%253D%253D 12 02 40 01 + // 4K EgJwAQ%253D%253D 12 02 70 01 + // HD EgIgAQ%253D%253D 12 02 20 01 + // Subtitles/CC EgIoAQ%253D%253D 12 02 28 01 + // Creative Commons EgIwAQ%253D%253D 12 02 30 01 + // 360 EgJ4AQ%253D%253D 12 02 78 01 + // VR180 EgPQAQE%253D 12 03 d0 01 01 + // 3D EgI4AQ%253D%253D 12 02 38 01 + // HDR EgPIAQE%253D 12 03 c8 01 01 + // (location & purchased unused) + + // SORT BY + // Relevance CAASAhAB 08 00 12 02 10 01 (is nothing by default) + // Upload date CAI%253D 08 02 + // View count CAM%253D 08 03 + // Rating CAE%253D 08 01 + + // video + // 12 02 10 01 + + // under 4 minutes + // 12 02 18 01 + + // video + under 4 minutes + // 12 04 10 01 18 01 + + // video + under 4 minutes + HD + // 08 00 12 06 10 01 18 01 20 01 + + // video + under 4 minutes + upload date + // 08 02 12 04 10 01 18 01 + + // video + under 4 minutes + HD + upload date + // 08 02 12 06 10 01 18 01 20 01 + + // this year + video + under 4 minutes + HD + upload date + // 08 02 12 08 08 05 10 01 18 01 20 01 + + // this week + video + over 20 minutes + HD + view count + // 08 03 12 08 08 03 10 01 18 02 20 01 + + //echo urlencode(urlencode(base64_encode(hex2bin($str)))); + //echo bin2hex(base64_decode(urldecode(urldecode("CAI%253D")))); + + // week + video + 20min + rating + // 08 01 12 06 08 03 10 01 18 02 + + // week + video + 20min + live + rating + // 08 01 12 08 08 03 10 01 18 02 40 01 + + // live 12 02 40 01 + + $hex = null; + if( + $date == "any" && + $type == "video" && + $duration == "any" && + $feature == "any" && + $sort == "relevance" + ){ + + return $hex; + } + + $opcode = 0; + + if($date != "any"){ $opcode += 2; } + if($type != "any"){ $opcode += 2; } + if($duration != "any"){ $opcode += 2; } + + switch($feature){ + + case "live": + case "4k": + case "hd": + case "subtitles": + case "creativecommons": + case "360": + case "3d": + $opcode += 2; + break; + + case "hdr": + case "vr180": + $opcode += 3; + break; + } + + switch($sort){ + + case "relevance": $hex .= "0800"; break; + case "upload_date": $hex .= "0802"; break; + case "view_count": $hex .= "0803"; break; + case "rating": $hex .= "0801"; break; + } + + $hex .= "12" . "0".$opcode; + + switch($date){ + + case "hour": $hex .= "0801"; break; + case "today": $hex .= "0802"; break; + case "week": $hex .= "0803"; break; + case "month": $hex .= "0804"; break; + case "year": $hex .= "0805"; break; + } + + switch($type){ + + case "video": $hex .= "1001"; break; + case "channel": $hex .= "1002"; break; + case "playlist": $hex .= "1003"; break; + case "movie": $hex .= "1004"; break; + } + + switch($duration){ + + case "short": $hex .= "1801"; break; + case "medium": $hex .= "1803"; break; + case "long": $hex .= "1802"; break; + } + + switch($feature){ + + case "live": $hex .= "4001"; break; + case "4k": $hex .= "7001"; break; + case "hd": $hex .= "2001"; break; + case "subtitles": $hex .= "2801"; break; + case "creativecommons": $hex .= "3001"; break; + case "360": $hex .= "7801"; break; + case "vr180": $hex .= "d00101"; break; + case "3d": $hex .= "3801"; break; + case "hdr": $hex .= "c80101"; break; + } + + //echo $hex . "\n\n"; + return urlencode(base64_encode(hex2bin($hex))); + } + + // me reading youtube's json + // https://imgur.com/X9hVlFX + + const req_web = 0; + const req_xhr = 1; + + private function get($proxy, $url, $get = [], $reqtype = self::req_web, $continuation = null){ + + $curlproc = curl_init(); + + if($get !== []){ + $get = http_build_query($get); + $url .= "?" . $get; + } + + curl_setopt($curlproc, CURLOPT_URL, $url); + + switch($reqtype){ + case self::req_web: + $headers = + ["User-Agent: " . config::USER_AGENT, + "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Cookie: PREF=tz=America.New_York", + "DNT: 1", + "Connection: keep-alive", + "Upgrade-Insecure-Requests: 1", + "Sec-Fetch-Dest: document", + "Sec-Fetch-Mode: navigate", + "Sec-Fetch-Site: none", + "Sec-Fetch-User: ?1"]; + break; + + case self::req_xhr: + $headers = + ["User-Agent: " . config::USER_AGENT, + "Accept: */*", + "Accept-Language: en-US,en;q=0.5", + "Accept-Encoding: gzip", + "Cookie: PREF=tz=America.New_York", + "Referer: https://youtube.com.com/", + "Content-Type: application/json", + "Content-Length: " . strlen($continuation), + "DNT: 1", + "Connection: keep-alive", + "Sec-Fetch-Dest: empty", + "Sec-Fetch-Mode: same-origin", + "Sec-Fetch-Site: same-origin"]; + + curl_setopt($curlproc, CURLOPT_POST, true); + curl_setopt($curlproc, CURLOPT_POSTFIELDS, $continuation); + break; + } + + curl_setopt($curlproc, CURLOPT_ENCODING, ""); // default encoding + curl_setopt($curlproc, CURLOPT_HTTPHEADER, $headers); + + curl_setopt($curlproc, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYHOST, 2); + curl_setopt($curlproc, CURLOPT_SSL_VERIFYPEER, true); + curl_setopt($curlproc, CURLOPT_CONNECTTIMEOUT, 30); + curl_setopt($curlproc, CURLOPT_TIMEOUT, 30); + + $this->backend->assign_proxy($curlproc, $proxy); + + $data = curl_exec($curlproc); + + if(curl_errno($curlproc)){ + + throw new Exception(curl_error($curlproc)); + } + + curl_close($curlproc); + return $data; + } + + public function video($get){ + + $this->out = [ + "status" => "ok", + "npt" => null, + "video" => [], + "author" => [], + "livestream" => [], + "playlist" => [], + "reel" => [] + ]; + + if($get["npt"]){ + + // parse nextPage + // https://www.youtube.com/youtubei/v1/search?key=AIzaSyAO_FJ2SlqU8Q4STEHLGCilw_Y9_11qcW8&prettyPrint=false + /* + $handle = fopen("nextpage.json", "r"); + $json = fread($handle, filesize("nextpage.json")); + fclose($handle);*/ + + [$npt, $proxy] = + $this->backend->get( + $get["npt"], + "videos" + ); + + $npt = json_decode($npt, true); + + try{ + $json = $this->get( + $proxy, + "https://www.youtube.com/youtubei/v1/search", + [ + "key" => $npt["key"], + "prettyPrint" => "false" + ], + self::req_xhr, + json_encode($npt["post"]) + ); + }catch(Exception $error){ + + throw new Exception("Could not fetch results page"); + } + + $json = json_decode($json); + + foreach( + $json + ->onResponseReceivedCommands[0] + ->appendContinuationItemsAction + ->continuationItems[0] + ->itemSectionRenderer + ->contents + as $video + ){ + + $this->parsevideoobject($video); + } + + if( + !isset( + $json + ->onResponseReceivedCommands[0] + ->appendContinuationItemsAction + ->continuationItems[1] + ->continuationItemRenderer + ->continuationEndpoint + ->continuationCommand + ->token + ) + ){ + + $npt = null; + + }else{ + // prepare nextpage for later.. + $npt["post"]["continuation"] = + $json + ->onResponseReceivedCommands[0] + ->appendContinuationItemsAction + ->continuationItems[1] + ->continuationItemRenderer + ->continuationEndpoint + ->continuationCommand + ->token; + } + + $this->out["npt"] = $npt; + + }else{ + + $search = $get["s"]; + if(strlen($search) === 0){ + + throw new Exception("Search term is empty!"); + } + + $proxy = $this->backend->get_ip(); + $date = $get["date"]; + $type = $get["type"]; + $duration = $get["duration"]; + $feature = $get["feature"]; + $sort = $get["sort"]; + + // parse ytInitialData + + $get = [ + "search_query" => $search + ]; + + if( + ( + $filter = + $this->ytfilter( + $date, + $type, + $duration, + $feature, + $sort + ) + ) !== null + ){ + + $get["sp"] = $filter; + } + + try{ + $json = $this->get( + $proxy, + "https://www.youtube.com/results", + $get + ); + }catch(Exception $error){ + + throw new Exception("Could not fetch results page"); + } + /* + $handle = fopen("test.html", "r"); + $json = fread($handle, filesize("test.html")); + fclose($handle); + */ + if( + !preg_match( + '/ytcfg\.set\(({".*})\); *window\.ytcfg/', + $json, + $ytconfig + ) + ){ + + throw new Exception("Could not get ytcfg"); + } + + $ytconfig = json_decode($ytconfig[1]); + + if( + !preg_match( + '/ytInitialData *= *({.*});<\/script>/', + $json, + $json + ) + ){ + + throw new Exception("Could not get ytInitialData"); + } + + $json = json_decode($json[1]); + + // generate POST data for nextpage + + $ytconfig->INNERTUBE_CONTEXT->client->screenWidthPoints = 1239; + $ytconfig->INNERTUBE_CONTEXT->client->screenHeightPoints = 999; + $ytconfig->INNERTUBE_CONTEXT->client->screenPixelDensity = 1; + $ytconfig->INNERTUBE_CONTEXT->client->screenDensityFloat = 1; + $ytconfig->INNERTUBE_CONTEXT->client->utcOffsetMinutes = -240; + $ytconfig->INNERTUBE_CONTEXT->request->internalExperimentFlags = []; + $ytconfig->INNERTUBE_CONTEXT->request->consistencyTokenJars = []; + + $ytconfig->INNERTUBE_CONTEXT->client->mainAppWebInfo = [ + "graftUrl" => $ytconfig->INNERTUBE_CONTEXT->client->originalUrl, + "webDisplayMode" => "WEB_DISPLAY_MODE_BROWSER", + "isWebNativeShareAvailable" => false + ]; + + $ytconfig->INNERTUBE_CONTEXT->adSignalsInfo = [ + "params" => [ + [ + "key" => "dt", + "value" => (string)$ytconfig->TIME_CREATED_MS + ], + [ + "key" => "flash", + "value" => "0" + ], + [ + "key" => "frm", + "value" => "0" + ], + [ + "key" => "u_tz", + "value" => "-240" + ], + [ + "key" => "u_his", + "value" => "3" + ], + [ + "key" => "u_h", + "value" => "1080" + ], + [ + "key" => "u_w", + "value" => "1920" + ], + [ + "key" => "u_ah", + "value" => "1080" + ], + [ + "key" => "u_cd", + "value" => "24" + ], + [ + "key" => "bc", + "value" => "31" + ], + [ + "key" => "bih", + "value" => "999" + ], + [ + "key" => "biw", + "value" => "1239" + ], + [ + "key" => "brdim", + "value" => "0,0,0,0,1920,0,1920,1061,1239,999" + ], + [ + "key" => "vis", + "value" => "1" + ], + [ + "key" => "wgl", + "value" => "true" + ], + [ + "key" => "ca_type", + "value" => "image" + ] + ] + ]; + + /* + echo json_encode($json); + die();*/ + + // *inhales* + foreach( + $json + ->contents + ->twoColumnSearchResultsRenderer + ->primaryContents + ->sectionListRenderer + ->contents[0] + ->itemSectionRenderer + ->contents + as $video + ){ + + $this->parsevideoobject($video); + } + + // get additional data from secondaryContents + if( + isset( + $json + ->contents + ->twoColumnSearchResultsRenderer + ->secondaryContents + ->secondarySearchContainerRenderer + ->contents[0] + ->universalWatchCardRenderer + ) + ){ + + $video = + $json + ->contents + ->twoColumnSearchResultsRenderer + ->secondaryContents + ->secondarySearchContainerRenderer + ->contents[0] + ->universalWatchCardRenderer; + /* + echo json_encode($video); + die();*/ + + $author = + [ + "name" => + $video + ->header + ->watchCardRichHeaderRenderer + ->title + ->simpleText, + "url" => + "https://www.youtube.com/channel/" . + $video + ->header + ->watchCardRichHeaderRenderer + ->titleNavigationEndpoint + ->browseEndpoint + ->browseId, + "avatar" => null + ]; + + if( + isset( + $video + ->header + ->watchCardRichHeaderRenderer + ->avatar + ->thumbnails[0] + ->url + ) + ){ + + $author["avatar"] = + $video + ->header + ->watchCardRichHeaderRenderer + ->avatar + ->thumbnails[0] + ->url; + } + + // add video in callToAction if present + if( + isset( + $video + ->callToAction + ->watchCardHeroVideoRenderer + ->lengthText + ) + ){ + + array_push( + $this->out["video"], + [ + "title" => + $video + ->callToAction + ->watchCardHeroVideoRenderer + ->title + ->simpleText, + "description" => null, + "author" => $author, + "date" => + $this->textualdate2unix( + trim( + explode( + "•", + $video + ->callToAction + ->watchCardHeroVideoRenderer + ->subtitle + ->simpleText + )[2] + ) + ), + "duration" => + $this->hms2int( + $video + ->callToAction + ->watchCardHeroVideoRenderer + ->lengthText + ->simpleText + ), + "views" => + $this->truncatedcount2int( + trim( + explode( + "•", + $video + ->callToAction + ->watchCardHeroVideoRenderer + ->subtitle + ->simpleText, + 2 + )[1] + ) + ), + "thumb" => [ + "url" => + $video + ->callToAction + ->watchCardHeroVideoRenderer + ->heroImage + ->singleHeroImageRenderer + ->thumbnail + ->thumbnails[0] + ->url, + "ratio" => "16:9" + ], + "url" => + "https://www.youtube.com/watch?v=" . + $video + ->callToAction + ->watchCardHeroVideoRenderer + ->navigationEndpoint + ->watchEndpoint + ->videoId + ] + ); + } + + // get all playlists, ignore videos + $out = null; + + foreach( + $video + ->sections + as $section + ){ + + if( + isset( + $section + ->watchCardSectionSequenceRenderer + ->lists[0] + ->horizontalCardListRenderer + ->cards + ) + ){ + + $out = + $section + ->watchCardSectionSequenceRenderer + ->lists[0] + ->horizontalCardListRenderer + ->cards; + break; + } + } + + if($out !== null){ + + foreach( + $out as $video + ){ + + if( + !isset( + $video + ->searchRefinementCardRenderer + ) + ){ + + continue; + } + + $video = + $video + ->searchRefinementCardRenderer; + + array_push( + $this->out["playlist"], + [ + "title" => + $video + ->query + ->runs[0] + ->text, + "description" => null, + "author" => $author, + "date" => null, + "duration" => null, + "views" => null, + "thumb" => [ + "url" => + $video + ->thumbnail + ->thumbnails[0] + ->url, + "ratio" => "1:1" + ], + "url" => + "https://www.youtube.com" . + $video + ->searchEndpoint + ->commandMetadata + ->webCommandMetadata + ->url + ] + ); + } + } + } + + foreach( + $json + ->contents + ->twoColumnSearchResultsRenderer + ->primaryContents + ->sectionListRenderer + ->contents + as $cont + ){ + + if(isset($cont->continuationItemRenderer)){ + + $this->out["npt"] = [ + "key" => + $ytconfig + ->INNERTUBE_API_KEY, + "post" => [ + "context" => + $ytconfig + ->INNERTUBE_CONTEXT, + "continuation" => + $cont + ->continuationItemRenderer + ->continuationEndpoint + ->continuationCommand + ->token + ] + ]; + break; + } + } + } + + if($this->out["npt"] !== null){ + + $this->out["npt"] = + $this->backend->store( + json_encode( + $this->out["npt"] + ), + "videos", + $proxy + ); + } + + return $this->out; + } + + private function parsevideoobject($video){ + + if(isset($video->videoRenderer)){ + + $video = $video->videoRenderer; + + $description = null; + + if(isset($video->detailedMetadataSnippets)){ + foreach( + $video + ->detailedMetadataSnippets[0] + ->snippetText + ->runs + as $description_part + ){ + + $description .= $description_part->text; + } + } + + if( + isset( + $video + ->badges[0] + ->metadataBadgeRenderer + ->icon + ->iconType + ) && + $video + ->badges[0] + ->metadataBadgeRenderer + ->icon + ->iconType + == "LIVE" + ){ + + $type = "livestream"; + $date = null; + $duration = "_LIVE"; + + if(isset($video->viewCountText->runs[0]->text)){ + + $views = + $this->views2int( + $video + ->viewCountText + ->runs[0] + ->text + ); + }else{ + + $views = null; + } + }else{ + + $type = "video"; + + if(isset($video->publishedTimeText->simpleText)){ + + $date = $this->textualdate2unix( + $video + ->publishedTimeText + ->simpleText + ); + }else{ + + $date = null; + } + + if(isset($video->lengthText->simpleText)){ + + $duration = + $this->hms2int( + $video + ->lengthText + ->simpleText + ); + }else{ + + $duration = null; + } + + if(isset($video->viewCountText->simpleText)){ + + $views = + $this->views2int( + $video + ->viewCountText + ->simpleText + ); + }else{ + + $views = null; + } + } + + if( + $video + ->navigationEndpoint + ->commandMetadata + ->webCommandMetadata + ->webPageType + == "WEB_PAGE_TYPE_SHORTS" + ){ + + // haha you thought you could get me, youtube + // jokes on you i dont go outside + $type = "reel"; + } + + array_push( + $this->out[$type], + [ + "title" => + $video + ->title + ->runs[0] + ->text, + "description" => + $this->titledots($description), + "author" => [ + "name" => + $video + ->longBylineText + ->runs[0] + ->text, + "url" => + "https://www.youtube.com/channel/" . + $video + ->longBylineText + ->runs[0] + ->navigationEndpoint + ->browseEndpoint + ->browseId, + "avatar" => + $this->checkhttpspresence( + $video + ->channelThumbnailSupportedRenderers + ->channelThumbnailWithLinkRenderer + ->thumbnail + ->thumbnails[0] + ->url + ) + ], + "date" => $date, + "duration" => $duration, + "views" => $views, + "thumb" => [ + "url" => + $video + ->thumbnail + ->thumbnails[0] + ->url, + "ratio" => "16:9" + ], + "url" => + "https://www.youtube.com/watch?v=" . + $video + ->videoId + ] + ); + }elseif(isset($video->watchCardCompactVideoRenderer)){ + + $video = + $video + ->watchCardCompactVideoRenderer; + + array_push( + $this->out["video"], + [ + "title" => + $video + ->title + ->simpleText, + "description" => null, + "author" => [ + "name" => + $video + ->byline + ->runs[0] + ->text, + "url" => + "https://www.youtube.com/channel/" . + $video + ->byline + ->runs[0] + ->navigationEndpoint + ->browseEndpoint + ->browseId, + "avatar" => null + ], + "date" => + $this->textualdate2unix( + trim( + explode( + "•", + $video + ->subtitle + ->simpleText, + 2 + )[1] + ) + ), + "duration" => + $this->hms2int( + $video + ->lengthText + ->simpleText + ), + "views" => + $this->truncatedcount2int( + trim( + explode( + "•", + $video + ->subtitle + ->simpleText, + 2 + )[0] + ) + ), + "thumb" => [ + "url" => + $video + ->thumbnail + ->thumbnails[0] + ->url, + "ratio" => "16:9" + ], + "url" => + "https://www.youtube.com/watch?v=" . + $video + ->navigationEndpoint + ->watchEndpoint + ->videoId + ] + ); + + }elseif(isset($video->reelShelfRenderer)){ + + foreach( + $video + ->reelShelfRenderer + ->items + as $reel + ){ + + $reel = + $reel + ->shortsLockupViewModel; + + array_push( + $this->out["reel"], + [ + "title" => + $reel + ->overlayMetadata + ->primaryText + ->content, + "description" => null, + "author" => [ + "name" => null, + "url" => null, + "avatar" => null + ], + "date" => null, + "duration" => null, + "views" => null, + "thumb" => [ + "url" => + $reel + ->thumbnail + ->sources[0] + ->url, + "ratio" => "9:16" + ], + "url" => + "https://www.youtube.com/watch?v=" . + $reel + ->onTap + ->innertubeCommand + ->reelWatchEndpoint + ->videoId + ] + ); + } + } + + elseif(isset($video->channelRenderer)){ + + $video = $video->channelRenderer; + + $description = null; + + if(isset($video->descriptionSnippet)){ + + foreach( + $video + ->descriptionSnippet + ->runs + as $description_part + ){ + + $description .= $description_part->text; + } + } + + array_push( + $this->out["author"], + [ + "title" => + $video + ->title + ->simpleText, + "followers" => + isset( + $video + ->videoCountText + ->simpleText + ) ? + $this->truncatedcount2int( + $video + ->videoCountText + ->simpleText + ) : + 0, + "description" => $this->titledots($description), + "thumb" => + [ + "url" => + $this->checkhttpspresence( + $video + ->thumbnail + ->thumbnails[ + count( + $video + ->thumbnail + ->thumbnails + ) - 1 + ] + ->url + ), + "ratio" => "1:1" + ], + "url" => + "https://www.youtube.com/channel/" . + $video + ->channelId + ] + ); + } + + elseif(isset($video->shelfRenderer)){ + + if( + !is_object( + $video + ->shelfRenderer + ->content + ->verticalListRenderer + ) + ){ + return; + } + + foreach( + $video + ->shelfRenderer + ->content + ->verticalListRenderer + ->items + as $shelfvideo + ){ + + $this->parsevideoobject($shelfvideo); + } + + }elseif(isset($video->radioRenderer)){ + + $video = $video->radioRenderer; + + $description = + $video + ->videoCountText + ->runs[0] + ->text + . "."; + + $tmp = []; + foreach( + $video->videos + as $childvideo + ){ + + $tmp[] = + $childvideo + ->childVideoRenderer + ->title + ->simpleText; + } + + if(count($tmp) !== 0){ + + $description .= + " " . implode(", ", $tmp); + } + + array_push( + $this->out["playlist"], + [ + "title" => + $video + ->title + ->simpleText, + "description" => $description, + "author" => [ + "name" => + $video + ->longBylineText + ->simpleText, + "url" => null, + "avatar" => null + ], + "date" => null, + "duration" => null, + "views" => null, + "thumb" => [ + "url" => + $video + ->thumbnail + ->thumbnails[ + count( + $video + ->thumbnail + ->thumbnails + ) - 1 + ] + ->url, + "ratio" => "16:9" + ], + "url" => + "https://www.youtube.com/watch?v=" . + $video + ->videos[0] + ->childVideoRenderer + ->videoId . + "&list=" . + $video + ->playlistId . + "&start_radio=1" + ] + ); + + }elseif(isset($video->playlistRenderer)){ + + $video = $video->playlistRenderer; + + $description = $video->videoCount . " videos."; + + $tmp = []; + foreach( + $video + ->videos + as $childvideo + ){ + + $tmp[] = + $childvideo + ->childVideoRenderer + ->title + ->simpleText; + } + + if(count($tmp) !== 0){ + + $description .= + " " . implode(", ", $tmp); + } + + array_push( + $this->out["playlist"], + [ + "title" => + $video + ->title + ->simpleText, + "description" => $description, + "author" => [ + "name" => + $video + ->longBylineText + ->runs[0] + ->text, + "url" => + "https://www.youtube.com/channel/" . + $video + ->longBylineText + ->runs[0] + ->navigationEndpoint + ->browseEndpoint + ->browseId, + "picture" => null + ], + "date" => null, + "duration" => null, + "views" => null, + "thumb" => + [ + "url" => + $video + ->thumbnails[0] + ->thumbnails[ + count( + $video + ->thumbnails[0] + ->thumbnails + ) - 1 + ] + ->url, + "ratio" => "16:9" + ], + "url" => + "https://www.youtube.com/watch?v=" . + $video + ->videos[0] + ->childVideoRenderer + ->videoId . + "&list=" . + $video + ->playlistId . + "&start_radio=1" + ] + ); + + }/*else{ + if(!isset($video->searchPyvRenderer)){ + echo json_encode($video); + die();} + }*/ + } + + private function textualdate2unix($number){ + + $number = + explode( + " ", + str_replace( + [ + " ago", + "seconds", + "minutes", + "hours", + "days", + "weeks", + "months", + "years" + ], + [ + "", + "second", + "minute", + "hour", + "day", + "week", + "month", + "year" + ], + $number + ), + 2 + ); + + $time = 0; + switch($number[1]){ + + case "second": + $time = (int)$number[0]; + break; + + case "minute": + $time = (int)$number[0] * 60; + break; + + case "hour": + $time = (int)$number[0] * 3600; + break; + + case "day": + $time = (int)$number[0] * 86400; + break; + + case "week": + $time = (int)$number[0] * 604800; + break; + + case "month": + $time = (int)$number[0] * 2629746; + break; + + case "year": + $time = (int)$number[0] * 31556952; + break; + } + + return time() - $time; + } + + private function checkhttpspresence($link){ + + if(substr($link, 0, 2) == "//"){ + + return "https:" . $link; + } + + return $link; + } + + private function textualtime2int($number){ + + $number = explode(" - ", $number); + + if(count($number) >= 2){ + + $number = $number[count($number) - 2]; + }else{ + + $number = $number[0]; + } + + $number = + str_replace( + [ + " ", + "seconds", + "minutes", + "hours", + ], + [ + "", + "second", + "minute", + "hour" + ], + $number + ); + + preg_match_all( + '/([0-9]+)(second|minute|hour)/', + $number, + $number + ); + + $time = 0; + + for($i=0; $i<count($number[0]); $i++){ + + switch($number[2][$i]){ + + case "second": + $time = $time + (int)$number[1][$i]; + break; + + case "minute": + $time = $time + ((int)$number[1][$i] * 60); + break; + + case "hour": + $time = $time + ((int)$number[1][$i] * 3600); + break; + } + } + + return $time; + } + + private function views2int($views){ + + return + (int)str_replace( + ",", "", + explode(" ", $views, 2)[0] + ); + } + + private function hms2int($time){ + + $parts = explode(":", $time, 3); + $time = 0; + + if(count($parts) === 3){ + + // hours + $time = $time + ((int)$parts[0] * 3600); + array_shift($parts); + } + + if(count($parts) === 2){ + + // minutes + $time = $time + ((int)$parts[0] * 60); + array_shift($parts); + } + + // seconds + $time = $time + (int)$parts[0]; + + return $time; + } + + private function truncatedcount2int($number){ + + // decimal should always be 1 number long + $number = explode(" ", $number, 2); + $number = $number[0]; + + $unit = strtolower($number[strlen($number) - 1]); + + $tmp = explode(".", $number, 2); + $number = (int)$number; + + if(count($tmp) === 2){ + + $decimal = (int)$tmp[1]; + }else{ + + $decimal = 0; + } + + switch($unit){ + + case "k": + $exponant = 1000; + break; + + case "m": + $exponant = 1000000; + break; + + case "b"; + $exponant = 1000000000; + break; + + default: + $exponant = 1; + break; + } + + return ($number * $exponant) + ($decimal * ($exponant / 10)); + } + + private function titledots($title){ + + $substr = substr($title, -3); + + if( + $substr == "..." || + $substr == "…" + ){ + + return trim(substr($title, 0, -3), " \n\r\t\v\x00\0\x0B\xc2\xa0"); + } + + return trim($title, " \n\r\t\v\x00\0\x0B\xc2\xa0"); + } +} diff --git a/settings.php b/settings.php new file mode 100644 index 0000000..75bc373 --- /dev/null +++ b/settings.php @@ -0,0 +1,601 @@ +<?php + +include "data/config.php"; + +/* + Define settings +*/ +$settings = [ + [ + "name" => "General", + "settings" => [ + [ + "description" => "Allow NSFW content", + "parameter" => "nsfw", + "options" => [ + [ + "value" => "yes", + "text" => "Yes" + ], + [ + "value" => "maybe", + "text" => "Maybe" + ], + [ + "value" => "no", + "text" => "No" + ] + ] + ], + [ + "description" => "Theme", + "parameter" => "theme", + "options" => [] + ], + [ + "description" => "Prevent clicking background elements when image viewer is open", + "parameter" => "bg_noclick", + "options" => [ + [ + "value" => "no", + "text" => "No" + ], + [ + "value" => "yes", + "text" => "Yes" + ] + ] + ] + ] + ], + [ + "name" => "Scrapers to use", + "settings" => [ + [ + "description" => "Autocomplete<br><i>Picking <span class=\"code-inline\">Auto</span> changes the source dynamically depending of the page's scraper<br><b>Warning:</b> If you edit this field, you will need to re-add the search engine so that the new autocomplete settings are applied!</i>", + "parameter" => "scraper_ac", + "options" => [ + [ + "value" => "disabled", + "text" => "Disabled" + ], + [ + "value" => "auto", + "text" => "Auto" + ], + [ + "value" => "brave", + "text" => "Brave" + ], + [ + "value" => "ddg", + "text" => "DuckDuckGo" + ], + [ + "value" => "yandex", + "text" => "Yandex" + ], + [ + "value" => "google", + "text" => "Google" + ], + [ + "value" => "startpage", + "text" => "Startpage" + ], + [ + "value" => "kagi", + "text" => "Kagi" + ], + [ + "value" => "qwant", + "text" => "Qwant" + ], + [ + "value" => "ghostery", + "text" => "Ghostery" + ], + [ + "value" => "yep", + "text" => "Yep" + ], + [ + "value" => "marginalia", + "text" => "Marginalia" + ], + [ + "value" => "yt", + "text" => "YouTube" + ], + [ + "value" => "sc", + "text" => "SoundCloud" + ] + ] + ], + [ + "description" => "Web", + "parameter" => "scraper_web", + "options" => [ + [ + "value" => "ddg", + "text" => "DuckDuckGo" + ], + [ + "value" => "brave", + "text" => "Brave" + ], + [ + "value" => "yandex", + "text" => "Yandex" + ], + [ + "value" => "google", + "text" => "Google" + ], + [ + "value" => "google_cse", + "text" => "Google CSE" + ], + [ + "value" => "startpage", + "text" => "Startpage" + ], + [ + "value" => "qwant", + "text" => "Qwant" + ], + [ + "value" => "ghostery", + "text" => "Ghostery" + ], + [ + "value" => "yep", + "text" => "Yep" + ], + [ + "value" => "greppr", + "text" => "Greppr" + ], + [ + "value" => "crowdview", + "text" => "Crowdview" + ], + [ + "value" => "mwmbl", + "text" => "Mwmbl" + ], + [ + "value" => "mojeek", + "text" => "Mojeek" + ], + [ + "value" => "baidu", + "text" => "Baidu" + ], + [ + "value" => "coccoc", + "text" => "Cốc Cốc" + ], + [ + "value" => "marginalia", + "text" => "Marginalia" + ], + [ + "value" => "wiby", + "text" => "wiby" + ], + [ + "value" => "curlie", + "text" => "Curlie" + ] + ] + ], + [ + "description" => "Images", + "parameter" => "scraper_images", + "options" => [ + [ + "value" => "ddg", + "text" => "DuckDuckGo" + ], + [ + "value" => "yandex", + "text" => "Yandex" + ], + [ + "value" => "brave", + "text" => "Brave" + ], + [ + "value" => "google", + "text" => "Google" + ], + [ + "value" => "google_cse", + "text" => "Google CSE" + ], + [ + "value" => "startpage", + "text" => "Startpage" + ], + [ + "value" => "qwant", + "text" => "Qwant" + ], + [ + "value" => "yep", + "text" => "Yep" + ], + [ + "value" => "baidu", + "text" => "Baidu" + ], + [ + "value" => "pinterest", + "text" => "Pinterest" + ], + [ + "value" => "cara", + "text" => "Cara" + ], + [ + "value" => "flickr", + "text" => "Flickr" + ], + [ + "value" => "fivehpx", + "text" => "500px" + ], + [ + "value" => "vsco", + "text" => "VSCO" + ], + [ + "value" => "imgur", + "text" => "Imgur" + ], + [ + "value" => "ftm", + "text" => "FindThatMeme" + ] + ] + ], + [ + "description" => "Videos", + "parameter" => "scraper_videos", + "options" => [ + [ + "value" => "yt", + "text" => "YouTube" + ], + [ + "value" => "vimeo", + "text" => "Vimeo" + ], + [ + "value" => "sepiasearch", + "text" => "Sepia Search" + ], + [ + "value" => "ddg", + "text" => "DuckDuckGo" + ], + [ + "value" => "brave", + "text" => "Brave" + ], + [ + "value" => "yandex", + "text" => "Yandex" + ], + [ + "value" => "google", + "text" => "Google" + ], + [ + "value" => "startpage", + "text" => "Startpage" + ], + [ + "value" => "qwant", + "text" => "Qwant" + ], + [ + "value" => "baidu", + "text" => "Baidu" + ], + [ + "value" => "coccoc", + "text" => "Cốc Cốc" + ] + ] + ], + [ + "description" => "News", + "parameter" => "scraper_news", + "options" => [ + [ + "value" => "ddg", + "text" => "DuckDuckGo" + ], + [ + "value" => "brave", + "text" => "Brave" + ], + [ + "value" => "google", + "text" => "Google" + ], + [ + "value" => "startpage", + "text" => "Startpage" + ], + [ + "value" => "qwant", + "text" => "Qwant" + ], + [ + "value" => "yep", + "text" => "Yep" + ], + [ + "value" => "mojeek", + "text" => "Mojeek" + ], + [ + "value" => "baidu", + "text" => "Baidu" + ] + ] + ], + [ + "description" => "Music", + "parameter" => "scraper_music", + "options" => [ + [ + "value" => "sc", + "text" => "SoundCloud" + ]//, + //[ + // "value" => "spotify", + // "text" => "Spotify" + //] + ] + ] + ] + ] +]; + +/* + Set theme collection +*/ +$themes = glob("static/themes/*"); + +$settings[0]["settings"][1]["options"][] = [ + "value" => "Dark", + "text" => "Dark" +]; + +foreach($themes as $theme){ + + $theme = explode(".", basename($theme))[0]; + + $settings[0]["settings"][1]["options"][] = [ + "value" => $theme, + "text" => $theme + ]; +} + +/* + Set cookies +*/ +if($_POST){ + + $loop = &$_POST; +}elseif(count($_GET) !== 0){ + + // redirect user to front page + $loop = &$_GET; + header("Location: /"); + +}else{ + // refresh cookie dates + $loop = &$_COOKIE; +} + +foreach($loop as $key => $value){ + + if($key == "theme"){ + + if($value == config::DEFAULT_THEME){ + + unset($_COOKIE[$key]); + + setcookie( + "theme", + "", + [ + "expires" => -1, // removes cookie + "samesite" => "Lax", + "path" => "/" + ] + ); + continue; + } + }else{ + + foreach($settings as $title){ + + foreach($title["settings"] as $list){ + + if( + $list["parameter"] == $key && + $list["options"][0]["value"] == $value + ){ + + unset($_COOKIE[$key]); + + setcookie( + $key, + "", + [ + "expires" => -1, // removes cookie + "samesite" => "Lax", + "path" => "/" + ] + ); + + continue 3; + } + } + } + } + + if(!is_string($value)){ + + continue; + } + + $key = trim($key); + $value = trim($value); + + $_COOKIE[$key] = $value; + + setcookie( + $key, + $value, + [ + "expires" => strtotime("+400 days"), // maximal cookie ttl in chrome + "samesite" => "Lax", + "path" => "/" + ] + ); +} + +include "lib/frontend.php"; +$frontend = new frontend(); + +echo + $frontend->load( + "header_nofilters.html", + [ + "title" => "Settings", + "class" => "" + ] + ); + +$left = + '<h1>Settings</h1>' . + '<form method="post" autocomplete="off">' . + 'By clicking <div class="code-inline">Update settings!</div>, a plaintext <div class="code-inline">key=value</div> cookie will be stored on your browser. When selecting a default setting, the parameter is removed from your cookies.'; + +$c = count($_COOKIE); +$code = ""; + +if($c !== 0){ + + $left .= + '<br><br>Your current cookie looks like this:' . + '<div class="code">'; + + $ca = 0; + foreach($_COOKIE as $key => $value){ + + $code .= $key . "=" . $value; + + $ca++; + if($ca !== $c){ + + $code .= "; "; + } + } + + $left .= $frontend->highlightcode($code); + + $left .= '</div>'; +}else{ + + $left .= + '<br><br>You currently don\'t have any cookies set.'; +} + +$left .= + '<div class="settings">'; + +foreach($settings as $title){ + + $left .= '<h2>' . $title["name"] . '</h2>'; + + foreach($title["settings"] as $setting){ + + $left .= + '<div class="setting">' . + '<div class="title">' . $setting["description"] . '</div>' . + '<select name="' . $setting["parameter"] . '">'; + + if($setting["parameter"] == "theme"){ + + if(!isset($_COOKIE["theme"])){ + + $_COOKIE["theme"] = config::DEFAULT_THEME; + } + } + + foreach($setting["options"] as $option){ + + $left .= + '<option value="' . $option["value"] . '"'; + + if( + isset($_COOKIE[$setting["parameter"]]) && + $_COOKIE[$setting["parameter"]] == $option["value"] + ){ + $left .= ' selected'; + } + + $left .= '>' . $option["text"] . '</option>'; + } + + $left .= '</select></div>'; + } +} + +$left .= + '</div>' . + '<div class="settings-submit">' . + '<input type="submit" value="Update settings!">' . + '<a href="../">< Go back</a>' . + '</div>' . + '</form>'; + +if(count($_GET) === 0){ + + $code = []; + foreach($_COOKIE as $key => $value){ + + $code[] = rawurlencode($key) . "=" . rawurlencode($value); + } + + $code = implode("&", $code); + + if($code != ""){ + + $code = "?" . $code; + } + + echo + $frontend->load( + "search.html", + [ + "timetaken" => null, + "class" => "", + "right-left" => + '<div class="infobox"><h2>Preference link</h2>Following this link will re-apply all cookies configured here and will redirect you to the front page. Useful if your browser clears out cookies after a browsing session.<br><br>' . + '<a href="settings' . $code . '">Bookmark me!</a>' . + '</div>', + "right-right" => "", + "left" => $left + ] + ); +} diff --git a/sitemap.php b/sitemap.php new file mode 100644 index 0000000..80bda66 --- /dev/null +++ b/sitemap.php @@ -0,0 +1,35 @@ +<?php + +header("Content-Type: application/xml"); +include "data/config.php"; + +$domain = + htmlspecialchars( + (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on" ? "https" : "http") . + '://' . $_SERVER["HTTP_HOST"] + ); + +echo + '<?xml version="1.0" encoding="UTF-8"?>' . + '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . + '<url>' . + '<loc>' . $domain . '/</loc>' . + '<lastmod>2023-07-31T07:56:12+03:00</lastmod>' . + '</url>' . + '<url>' . + '<loc>' . $domain . '/about</loc>' . + '<lastmod>2023-07-31T07:56:12+03:00</lastmod>' . + '</url>' . + '<url>' . + '<loc>' . $domain . '/instances</loc>' . + '<lastmod>2023-07-31T07:56:12+03:00</lastmod>' . + '</url>' . + '<url>' . + '<loc>' . $domain . '/settings</loc>' . + '<lastmod>2023-07-31T07:56:12+03:00</lastmod>' . + '</url>' . + '<url>' . + '<loc>' . $domain . '/api.txt</loc>' . + '<lastmod>2023-07-31T07:56:12+03:00</lastmod>' . + '</url>' . + '</urlset>'; diff --git a/static/404.png b/static/404.png Binary files differnew file mode 100644 index 0000000..e8588cf --- /dev/null +++ b/static/404.png diff --git a/static/client.js b/static/client.js new file mode 100644 index 0000000..5935f92 --- /dev/null +++ b/static/client.js @@ -0,0 +1,985 @@ + +/* + Global functions +*/ +function htmlspecialchars(str){ + + var map = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + } + + return str.replace(/[&<>"']/g, function(m){return map[m];}); +} + +function htmlspecialchars_decode(str){ + + var map = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + } + + return str.replace(/&|<|>|"|'/g, function(m){return map[m];}); +} + +function is_click_within(elem, classname, is_id = false){ + + while(true){ + + if(elem === null){ + + return false; + } + + if( + ( + is_id === false && + elem.className == classname + ) || + ( + is_id === true && + elem.id == classname + ) + ){ + + return elem; + } + + elem = elem.parentElement; + } +} + + + +/* + Prevent GET parameter pollution +*/ +var form = document.getElementsByTagName("form"); + +if( + form.length !== 0 && + window.location.pathname != "/" && + window.location.pathname != "/settings.php" && + window.location.pathname != "/settings" +){ + form = form[0]; + + var scraper_dropdown = document.getElementsByName("scraper")[0]; + + scraper_dropdown.addEventListener("change", function(choice){ + + submit(form); + }); + + form.addEventListener("submit", function(e){ + + e.preventDefault(); + submit(e.srcElement); + }); +} + +function submit(e){ + + var GET = ""; + var first = true; + + if((s = document.getElementsByName("s")).length !== 0){ + + GET += "?s=" + encodeURIComponent(s[0].value).replaceAll("%20", "+"); + first = false; + } + + Array.from( + e.getElementsByTagName("select") + ).concat( + Array.from( + e.getElementsByTagName("input") + ) + ).forEach(function(el){ + + var firstelem = el.getElementsByTagName("option"); + + if( + ( + ( + firstelem.length === 0 || + firstelem[0].value != el.value + ) && + el.name != "" && + el.value != "" && + el.name != "s" + ) || + el.name == "scraper" || + el.name == "nsfw" + ){ + + if(first){ + + GET += "?"; + first = false; + }else{ + + GET += "&"; + } + + GET += encodeURIComponent(el.name).replaceAll("%20", "+") + "=" + encodeURIComponent(el.value).replaceAll("%20", "+"); + } + }); + + window.location.href = GET; +} + + + +/* + Hide show more button when it's not needed on answers +*/ +var answer_div = document.getElementsByClassName("answer"); + +if(answer_div.length !== 0){ + answer_div = Array.from(answer_div); + var spoiler_button_div = Array.from(document.getElementsByClassName("spoiler-button")); + + // execute on pageload + hide_show_more(); + + window.addEventListener("resize", hide_show_more); + + function hide_show_more(){ + + var height = window.innerWidth >= 1000 ? 600 : 200; + + for(i=0; i<answer_div.length; i++){ + + if(answer_div[i].scrollHeight < height){ + + spoiler_button_div[i].style.display = "none"; + + document.getElementById(spoiler_button_div[i].htmlFor).checked = true; + }else{ + + spoiler_button_div[i].style.display = "block"; + } + } + } +} + +switch(document.location.pathname){ + + case "/web": + case "/web.php": + var image_class = "image"; + break; + + case "/images": + case "/images.php": + var image_class = "thumb"; + break; + + default: + var image_class = null; +} + +if(image_class !== null){ + + /* + Add popup to document + */ + var popup_bg = document.createElement("div"); + popup_bg.id = "popup-bg"; + document.body.appendChild(popup_bg); + + // enable/disable pointer events + if(!document.cookie.includes("bg_noclick=yes")){ + + popup_bg.style.pointerEvents = "none"; + } + + var popup_status = document.createElement("div"); + popup_status.id = "popup-status"; + document.body.appendChild(popup_status); + + var popup_body = document.createElement("div"); + popup_body.id = "popup"; + document.body.appendChild(popup_body); + + // import popup + var popup_body = document.getElementById("popup"); + var popup_status = document.getElementById("popup-status"); + var popup_image = null; // is set later on popup click + + // image metadata + var collection = []; // will contain width, height, image URL + var collection_index = 0; + + // event handling helper variables + var is_popup_shown = false; + var mouse_down = false; + var mouse_move = false; + var move_x = 0; + var move_y = 0; + var target_is_popup = false; + var mirror_x = false; + var mirror_y = false; + var rotation = 0; + + /* + Image dragging (mousedown) + */ + document.addEventListener("mousedown", function(div){ + + if(div.buttons !== 1){ + + return; + } + + mouse_down = true; + mouse_move = false; + + if(is_click_within(div.target, "popup", true) === false){ + + target_is_popup = false; + }else{ + + target_is_popup = true; + + var pos = popup_body.getBoundingClientRect(); + move_x = div.x - pos.x; + move_y = div.y - pos.y; + } + }); + + /* + Image dragging (mousemove) + */ + document.addEventListener("mousemove", function(pos){ + + if( + target_is_popup && + mouse_down + ){ + + mouse_move = true; + movepopup(popup_body, pos.clientX - move_x, pos.clientY - move_y); + } + }); + + /* + Image dragging (mouseup) + */ + document.addEventListener("mouseup", function(){ + + mouse_down = false; + }); + + /* + Image popup open + */ + document.addEventListener("click", function(click){ + + // should our click trigger image open? + if( + elem = is_click_within(click.target, image_class) || + click.target.classList.contains("openimg") + ){ + + event.preventDefault(); + is_popup_shown = true; + + // reset position params + mirror_x = false; + mirror_y = false; + rotation = 0; + scale = 60; + collection_index = 0; + + // get popup data + if(elem === true){ + // we clicked a simple image preview + elem = click.target; + var image_url = elem.getAttribute("src"); + + if(image_url.startsWith("/proxy")){ + + var match = image_url.match(/i=([^&]+)/); + + if(match !== null){ + + image_url = decodeURIComponent(match[1]); + } + }else{ + + image_url = htmlspecialchars_decode(image_url); + } + + var w = Math.round(click.target.naturalWidth); + var h = Math.round(click.target.naturalHeight); + + if( + w === 0 || + h === 0 + ){ + + w = 100; + h = 100; + } + + collection = [ + { + "url": image_url, + "width": w, + "height": h + } + ]; + + var title = "No description provided"; + + if(click.target.title != ""){ + + title = click.target.title; + }else{ + + if(click.target.alt != ""){ + + title = click.target.alt; + } + } + }else{ + + if(image_class == "thumb"){ + // we're inside image.php + + elem = + elem + .parentElement + .parentElement; + + var image_url = elem.getElementsByTagName("a")[1].href; + }else{ + + // we're inside web.php + var image_url = elem.href; + } + + collection = + JSON.parse( + elem.getAttribute("data-json") + ); + + var imagesize = elem.getElementsByTagName("img")[0]; + + var imagesize_w = 0; + var imagesize_h = 0; + + if(imagesize.complete){ + + imagesize_w = imagesize.naturalWidth; + imagesize_h = imagesize.naturalHeight; + } + + if( + imagesize_w === 0 || + imagesize_h === 0 + ){ + + imagesize_w = 100; + imagesize_h = 100; + } + + for(var i=0; i<collection.length; i++){ + + if(collection[i].width === null){ + + collection[i].width = imagesize_w; + collection[i].height = imagesize_h; + } + } + + var title = elem.title; + } + + // prepare HTML + var html = + '<div id="popup-num">(' + collection.length + ')</div>' + + '<div id="popup-dropdown">' + + '<select name="viewer-res" onchange="changeimage(event)">'; + + for(i=0; i<collection.length; i++){ + + if(collection[i].url.startsWith("data:")){ + + var domain = "<Base64 Data>"; + }else{ + + var domain = new URL(collection[i].url).hostname; + } + + html += '<option value="' + i + '">' + '(' + collection[i].width + 'x' + collection[i].height + ') ' + domain + '</option>'; + } + + popup_status.innerHTML = + html + '</select></div>' + + '<a href="' + htmlspecialchars(image_url) + '" rel="noreferrer nofollow "id="popup-title">' + htmlspecialchars(title) + '</a>'; + + popup_body.innerHTML = + '<img src="' + getproxylink(collection[0].url) + '" draggable="false" id="popup-image">'; + + // make changes to DOM + popup_body.style.display = "block"; + popup_bg.style.display = "block"; + popup_status.style.display = "table"; + + // store for rotation functions & changeimage() + popup_image = document.getElementById("popup-image"); + + scalepopup(collection[collection_index], scale); + centerpopup(); + }else{ + + // click inside the image viewer + // resize image + if(is_click_within(click.target, "popup", true)){ + + if(mouse_move === false){ + scale = 80; + scalepopup(collection[collection_index], scale); + centerpopup(); + } + }else{ + + if(is_click_within(click.target, "popup-status", true) === false){ + + // click outside the popup while its open + // close it + if(is_popup_shown){ + + hidepopup(); + } + } + } + } + }); + + /* + Scale image viewer + */ + popup_body.addEventListener("wheel", function(scroll){ + + event.preventDefault(); + + if( + scroll.altKey || + scroll.ctrlKey || + scroll.shiftKey + ){ + + var increment = 7; + }else{ + + var increment = 14; + } + + if(scroll.wheelDelta > 0){ + + // scrolling up + scale = scale + increment; + }else{ + + // scrolling down + if(scale - increment > 7){ + scale = scale - increment; + } + } + + // calculate relative size before scroll + var pos = popup_body.getBoundingClientRect(); + var x = (scroll.x - pos.x) / pos.width; + var y = (scroll.y - pos.y) / pos.height; + + scalepopup(collection[collection_index], scale); + + // move popup to % we found + pos = popup_body.getBoundingClientRect(); + + movepopup( + popup_body, + scroll.clientX - (x * pos.width), + scroll.clientY - (y * pos.height) + ); + }); + + /* + Keyboard controls + */ + + document.addEventListener("keydown", function(key){ + + // close popup + if( + is_popup_shown && + key.keyCode === 27 + ){ + + hidepopup(); + return; + } + + if(is_popup_shown === false){ + + return; + } + + if( + key.altKey || + key.ctrlKey || + key.shiftKey + ){ + + // mirror image + switch(key.keyCode){ + + case 37: + // left + key.preventDefault(); + mirror_x = true; + break; + + case 38: + // up + key.preventDefault(); + mirror_y = false; + break; + + case 39: + // right + key.preventDefault(); + mirror_x = false; + break; + + case 40: + // down + key.preventDefault(); + mirror_y = true; + break; + } + }else{ + + // rotate image + switch(key.keyCode){ + + case 37: + // left + key.preventDefault(); + rotation = -90; + break; + + case 38: + // up + key.preventDefault(); + rotation = 0; + break; + + case 39: + // right + key.preventDefault(); + rotation = 90; + break; + + case 40: + // down + key.preventDefault(); + rotation = -180; + break; + } + } + + popup_image.style.transform = + "scale(" + + (mirror_x ? "-1" : "1") + + ", " + + (mirror_y ? "-1" : "1") + + ") " + + "rotate(" + + rotation + "deg" + + ")"; + }); +} + +function getproxylink(url){ + + if(url.startsWith("data:")){ + + return htmlspecialchars(url); + }else{ + + return '/proxy?i=' + encodeURIComponent(url); + } +} + +function hidepopup(){ + + is_popup_shown = false; + popup_status.style.display = "none"; + popup_body.style.display = "none"; + popup_bg.style.display = "none"; +} + +function scalepopup(size, scale){ + + var ratio = + Math.min( + (window.innerWidth * (scale / 100)) / collection[collection_index].width, (window.innerHeight * (scale / 100)) / collection[collection_index].height + ); + + popup_body.style.width = size.width * ratio + "px"; + popup_body.style.height = size.height * ratio + "px"; +} + +function centerpopup(){ + + var size = popup_body.getBoundingClientRect(); + var size = { + "width": parseInt(size.width), + "height": parseInt(size.height) + }; + + movepopup( + popup_body, + (window.innerWidth / 2) - (size.width / 2), + (window.innerHeight / 2) - (size.height / 2) + ); +} + +function movepopup(popup_body, x, y){ + + popup_body.style.left = x + "px"; + popup_body.style.top = y + "px"; +} + +function changeimage(event){ + + // reset rotation params + mirror_x = false; + mirror_y = false; + rotation = 0; + + scale = 60; + + collection_index = parseInt(event.target.value); + + // we set innerHTML otherwise old image lingers a little + popup_body.innerHTML = + '<img src="' + getproxylink(collection[collection_index].url) + '" draggable="false" id="popup-image">'; + + // store for rotation functions & changeimage() + popup_image = document.getElementById("popup-image"); + + scalepopup(collection[collection_index], scale); + centerpopup(); +} + +var searchbox_wrapper = document.getElementsByClassName("searchbox"); + +if(searchbox_wrapper.length !== 0){ + + searchbox_wrapper = searchbox_wrapper[0]; + var searchbox = searchbox_wrapper.getElementsByTagName("input")[1]; + + /* + Textarea shortcuts + */ + document.addEventListener("keydown", function(key){ + + switch(key.keyCode){ + + case 191: + // 191 = / + if(document.activeElement.tagName == "INPUT"){ + + // already focused, ignore + break; + } + + if( + typeof is_popup_shown != "undefined" && + is_popup_shown + ){ + + hidepopup(); + } + + window.scrollTo(0, 0); + searchbox.focus(); + key.preventDefault(); + break; + } + }); + + /* + Autocompleter + */ + if( // make sure the user wants it + document.cookie.includes("scraper_ac=") && + document.cookie.includes("scraper_ac=disabled") === false + ){ + + var autocomplete_cache = []; + var focuspos = -1; + var list = []; + var autocomplete_div = document.getElementsByClassName("autocomplete")[0]; + + if( + document.cookie.includes("scraper_ac=auto") && + typeof scraper_dropdown != "undefined" + ){ + + var ac_req_appendix = "&scraper=" + scraper_dropdown.value; + }else{ + + var ac_req_appendix = ""; + } + + function getsearchboxtext(){ + + var value = + searchbox.value + .trim() + .replace( + / +/g, + " " + ) + .toLowerCase(); + + return value; + } + + searchbox.addEventListener("input", async function(){ + + // ratelimit on input only + // dont ratelimit if we already have res + if(typeof autocomplete_cache[getsearchboxtext()] != "undefined"){ + + await getac(); + }else{ + + await getac_ratelimit(); + } + }); + + async function getac(){ + + var curvalue = getsearchboxtext(); + + if(curvalue == ""){ + + // hide autocompleter + autocomplete_div.style.display = "none"; + return; + } + + if(typeof autocomplete_cache[curvalue] == "undefined"){ + + /* + Fetch autocomplete + */ + // make sure we dont fetch same thing twice + autocomplete_cache[curvalue] = []; + + var res = await fetch("/api/v1/ac?s=" + (encodeURIComponent(curvalue).replaceAll("%20", "+")) + ac_req_appendix); + if(!res.ok){ + + return; + } + + var json = await res.json(); + + autocomplete_cache[curvalue] = json[1]; + + if(curvalue == getsearchboxtext()){ + + render_ac(curvalue, autocomplete_cache[curvalue]); + } + return; + } + + render_ac(curvalue, autocomplete_cache[curvalue]); + } + + var ac_func = null; + function getac_ratelimit(){ + + return new Promise(async function(resolve, reject){ + + if(ac_func !== null){ + + clearTimeout(ac_func); + }//else{ + + // no ratelimits + //getac(); + //} + + ac_func = + setTimeout(function(){ + + ac_func = null; + getac(); // get results after 100ms of no keystroke + resolve(); + }, 200); + }); + } + + function render_ac(query, list){ + + if(list.length === 0){ + + autocomplete_div.style.display = "none"; + return; + } + + html = ""; + + // prepare regex + var highlight = query.split(" "); + var regex = []; + + for(var k=0; k<highlight.length; k++){ + + // espace regex + regex.push( + highlight[k].replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + ); + } + + regex = new RegExp(highlight.join("|"), "gi"); + + for(var i=0; i<list.length; i++){ + + html += + '<div tabindex="0" class="entry" onclick="handle_entry_click(this);">' + + htmlspecialchars( + list[i] + ).replace( + regex, + '<u>$&</u>' + ) + + '</div>'; + } + + autocomplete_div.innerHTML = html; + autocomplete_div.style.display = "block"; + } + + var should_focus = false; + document.addEventListener("keydown", function(event){ + + if(event.key == "Escape"){ + + document.activeElement.blur(); + focuspos = -1; + autocomplete_div.style.display = "none"; + return; + } + + if( + is_click_within(event.target, "searchbox") === false || + typeof autocomplete_cache[getsearchboxtext()] == "undefined" + ){ + + return; + } + + switch(event.key){ + + case "ArrowUp": + event.preventDefault(); + focuspos--; + if(focuspos === -2){ + + focuspos = autocomplete_cache[getsearchboxtext()].length - 1; + } + break; + + case "ArrowDown": + case "Tab": + event.preventDefault(); + + focuspos++; + if(focuspos >= autocomplete_cache[getsearchboxtext()].length){ + + focuspos = -1; + } + break; + + case "Enter": + should_focus = true; + + if(focuspos !== -1){ + + // replace input content + event.preventDefault(); + searchbox.value = + autocomplete_div.getElementsByClassName("entry")[focuspos].innerText; + break; + } + break; + + default: + focuspos = -1; + break; + } + + if(focuspos === -1){ + + searchbox.focus(); + return; + } + + autocomplete_div.getElementsByClassName("entry")[focuspos].focus(); + }); + + window.addEventListener("blur", function(){ + + autocomplete_div.style.display = "none"; + }); + + document.addEventListener("keyup", function(event){ + + // handle ENTER key on entry + if(should_focus){ + + should_focus = false; + searchbox.focus(); + } + }); + + document.addEventListener("mousedown", function(event){ + + // hide input if click is outside + if(is_click_within(event.target, "searchbox") === false){ + + autocomplete_div.style.display = "none"; + return; + } + }); + + function handle_entry_click(event){ + + searchbox.value = event.innerText; + focuspos = -1; + searchbox.focus(); + } + + searchbox.addEventListener("focus", function(){ + + focuspos = -1; + getac(); + }); + } +} diff --git a/static/icon/amazon.png b/static/icon/amazon.png Binary files differnew file mode 100644 index 0000000..043a7e2 --- /dev/null +++ b/static/icon/amazon.png diff --git a/static/icon/appstore.png b/static/icon/appstore.png Binary files differnew file mode 100644 index 0000000..85663bb --- /dev/null +++ b/static/icon/appstore.png diff --git a/static/icon/call.png b/static/icon/call.png Binary files differnew file mode 100644 index 0000000..c91bece --- /dev/null +++ b/static/icon/call.png diff --git a/static/icon/directions.png b/static/icon/directions.png Binary files differnew file mode 100644 index 0000000..699da40 --- /dev/null +++ b/static/icon/directions.png diff --git a/static/icon/facebook.png b/static/icon/facebook.png Binary files differnew file mode 100644 index 0000000..0ae3137 --- /dev/null +++ b/static/icon/facebook.png diff --git a/static/icon/gamespot.png b/static/icon/gamespot.png Binary files differnew file mode 100644 index 0000000..3453e07 --- /dev/null +++ b/static/icon/gamespot.png diff --git a/static/icon/github.png b/static/icon/github.png Binary files differnew file mode 100644 index 0000000..f78f0c0 --- /dev/null +++ b/static/icon/github.png diff --git a/static/icon/googleplay.png b/static/icon/googleplay.png Binary files differnew file mode 100644 index 0000000..05ffc19 --- /dev/null +++ b/static/icon/googleplay.png diff --git a/static/icon/imdb.png b/static/icon/imdb.png Binary files differnew file mode 100644 index 0000000..d8ccb2f --- /dev/null +++ b/static/icon/imdb.png diff --git a/static/icon/instagram.png b/static/icon/instagram.png Binary files differnew file mode 100644 index 0000000..41d9bf2 --- /dev/null +++ b/static/icon/instagram.png diff --git a/static/icon/itunes.png b/static/icon/itunes.png Binary files differnew file mode 100644 index 0000000..99a1dff --- /dev/null +++ b/static/icon/itunes.png diff --git a/static/icon/microsoft.png b/static/icon/microsoft.png Binary files differnew file mode 100644 index 0000000..46d048a --- /dev/null +++ b/static/icon/microsoft.png diff --git a/static/icon/quora.png b/static/icon/quora.png Binary files differnew file mode 100644 index 0000000..00746b3 --- /dev/null +++ b/static/icon/quora.png diff --git a/static/icon/reddit.png b/static/icon/reddit.png Binary files differnew file mode 100644 index 0000000..6522815 --- /dev/null +++ b/static/icon/reddit.png diff --git a/static/icon/rottentomatoes.png b/static/icon/rottentomatoes.png Binary files differnew file mode 100644 index 0000000..dd462e7 --- /dev/null +++ b/static/icon/rottentomatoes.png diff --git a/static/icon/sciencedirect.png b/static/icon/sciencedirect.png Binary files differnew file mode 100644 index 0000000..20cef17 --- /dev/null +++ b/static/icon/sciencedirect.png diff --git a/static/icon/soundcloud.png b/static/icon/soundcloud.png Binary files differnew file mode 100644 index 0000000..a12ba39 --- /dev/null +++ b/static/icon/soundcloud.png diff --git a/static/icon/spotify.png b/static/icon/spotify.png Binary files differnew file mode 100644 index 0000000..c7a35ca --- /dev/null +++ b/static/icon/spotify.png diff --git a/static/icon/steam.png b/static/icon/steam.png Binary files differnew file mode 100644 index 0000000..ab3e73d --- /dev/null +++ b/static/icon/steam.png diff --git a/static/icon/twitter.png b/static/icon/twitter.png Binary files differnew file mode 100644 index 0000000..bce2863 --- /dev/null +++ b/static/icon/twitter.png diff --git a/static/icon/w3html.png b/static/icon/w3html.png Binary files differnew file mode 100644 index 0000000..2f107db --- /dev/null +++ b/static/icon/w3html.png diff --git a/static/icon/website.png b/static/icon/website.png Binary files differnew file mode 100644 index 0000000..aa691f8 --- /dev/null +++ b/static/icon/website.png diff --git a/static/icon/wikipedia.png b/static/icon/wikipedia.png Binary files differnew file mode 100644 index 0000000..b3e778e --- /dev/null +++ b/static/icon/wikipedia.png diff --git a/static/icon/youtube.png b/static/icon/youtube.png Binary files differnew file mode 100644 index 0000000..542d7f0 --- /dev/null +++ b/static/icon/youtube.png diff --git a/static/misc/christmas-dark-bg.png b/static/misc/christmas-dark-bg.png Binary files differnew file mode 100644 index 0000000..83f7c0a --- /dev/null +++ b/static/misc/christmas-dark-bg.png diff --git a/static/misc/christmas-hat.png b/static/misc/christmas-hat.png Binary files differnew file mode 100644 index 0000000..91d96ad --- /dev/null +++ b/static/misc/christmas-hat.png diff --git a/static/misc/christmas-white-bg.png b/static/misc/christmas-white-bg.png Binary files differnew file mode 100644 index 0000000..a627775 --- /dev/null +++ b/static/misc/christmas-white-bg.png diff --git a/static/misc/snow.png b/static/misc/snow.png Binary files differnew file mode 100644 index 0000000..d157188 --- /dev/null +++ b/static/misc/snow.png diff --git a/static/serverping.js b/static/serverping.js new file mode 100644 index 0000000..6b680d5 --- /dev/null +++ b/static/serverping.js @@ -0,0 +1,473 @@ + +function htmlspecialchars(str){ + + if(str === null){ + + return "<i><Empty></i>"; + } + + var map = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + } + + return str.replace(/[&<>"']/g, function(m){return map[m];}); +} + +// initialize garbage +var list = []; +var pinged_list = []; +var reqs = 0; +var errors = 0; +var sort = 6; // highest version first + +// check for instance redirect stuff +var redir = []; +var target = "/web?"; +new URL(window.location.href) + .searchParams + .forEach( + function(value, key){ + + if(key == "target"){ + + target = "/" + encodeURIComponent(value) + "?"; + return; + } + + if(key == "npt"){ return; } + redir.push(encodeURIComponent(key) + "=" + encodeURIComponent(value)) + } + ); + +if(redir.length !== 0){ + + redir = target + redir.join("&"); +}else{ + + redir = ""; +} + +var quote = document.createElement("div"); +quote.className = "quote"; +quote.innerHTML = 'Pinged <b>0</b> servers (<b>0</b> failed requests)'; +var [div_servercount, div_failedreqs] = + quote.getElementsByTagName("b"); + +var noscript = document.getElementsByTagName("noscript")[0]; +document.body.insertBefore(quote, noscript.nextSibling); + +// create table +var table = document.createElement("table"); +table.innerHTML = + '<thead>' + + '<tr>' + + '<th class="extend">Server</th>' + + '<th>Address</th>' + + '<th>Bot protection</th>' + + '<th title="Amount of legit requests processed since the last APCU cache clear (usually happens at midnight)">Real reqs (?)</th>' + + '<th title="Amount of filtered requests processed since the last APCU cache clear (usually happens at midnight)">Bot reqs (?)</th>' + + '<th>API</th>' + + '<th><div class="arrow up"></div>Version</th>' + + '</tr>' + + '</thead>' + + '<tbody></tbody>'; + +document.body.insertBefore(table, quote.nextSibling); + +// handle sorting clicks +var tbody = table.getElementsByTagName("tbody")[0]; +var th = table.getElementsByTagName("th"); + +for(var i=0; i<th.length; i++){ + + th[i].addEventListener("click", function(event){ + + if(event.target.className.includes("arrow")){ + + var div = event.target.parentElement; + }else{ + + var div = event.target; + } + + var arrow = div.getElementsByClassName("arrow"); + var orientation = 0; // up + + if(arrow.length === 0){ + + // delete arrow and add new one + arrow = document.getElementsByClassName("arrow"); + arrow[0].remove(); + + arrow = document.createElement("div"); + arrow.className = "arrow up"; + div.insertBefore(arrow, event.target.firstChild); + }else{ + + // switch arrow position + if(arrow[0].className == "arrow down"){ + + arrow[0].className = "arrow up"; + }else{ + + arrow[0].className = "arrow down"; + orientation = 1; + } + } + + switch(div.textContent.toLowerCase()){ + + case "server": sort = 0 + orientation; break; + case "address": sort = 2 + orientation; break; + case "bot protection": sort = 4 + orientation; break; + case "real reqs (?)": sort = 6 + orientation; break; + case "bot reqs (?)": sort = 8 + orientation; break; + case "api": sort = 10 + orientation; break; + case "version": sort = 12 + orientation; break; + } + + render_list(); + }); +} + +function validate_url(url, allow_http = false){ + + try{ + + url = new URL(url); + if( + url.protocol == "https:" || + ( + ( + allow_http === true || + window.location.protocol == "http:" + ) && + url.protocol == "http:" + ) + ){ + + return true; + } + }catch(error){} // do nothing + + return false; +} + +function number_format(int){ + + return new Intl.NumberFormat().format(int); +} + +// parse initial server list +fetch_server(window.location.origin); + +async function fetch_server(server){ + + if(!validate_url(server)){ + console.warn("Invalid server URL: " + server); + return; + } + + // make sure baseURL is origin + server = new URL(server).origin; + // prevent multiple fetches + for(var i=0; i<list.length; i++){ + + if(list[i] == server){ + + // serber was already fetched + return; + } + } + + // prevent future fetches + list.push(server); + + var data = null; + + try{ + + var payload = await fetch(server + "/ami4get"); + + if(payload.status !== 200){ + + // endpoint is not available + errors++; + div_failedreqs.textContent = number_format(errors); + console.warn(server + ": Invalid HTTP code " + payload.status); + return; + } + + data = await payload.json(); + + }catch(error){ + + errors++; + div_failedreqs.textContent = number_format(errors); + console.warn(server + ": Could not fetch or decode JSON"); + return; + } + + // sanitize data + if( + typeof data.status != "string" || + data.status != "ok" || + typeof data.server != "object" || + !( + typeof data.server.name == "string" || + ( + typeof data.server.name == "object" && + data.server.name === null + ) + ) || + typeof data.service != "string" || + data.service != "4get" || + ( + typeof data.server.description != "string" && + data.server.description !== null + ) || + typeof data.server.bot_protection != "number" || + typeof data.server.real_requests != "number" || + typeof data.server.bot_requests != "number" || + typeof data.server.api_enabled != "boolean" || + typeof data.server.alt_addresses != "object" || + typeof data.server.version != "number" || + typeof data.instances != "object" + ){ + + errors++; + div_failedreqs.textContent = number_format(errors); + console.warn(server + ": Malformed JSON"); + return; + } + + data.server.ip = server; + + reqs++; + div_servercount.textContent = number_format(reqs); + + var total = pinged_list.push(data) - 1; + pinged_list[total].index = total; + + render_list(); + + // get more serbers + for(var i=0; i<data.instances.length; i++){ + + fetch_server(data.instances[i]); + } +} + +function sorta(object, element, order){ + + return object.slice().sort( + function(a, b){ + + if(order){ + + return a.server[element] - b.server[element]; + } + + return b.server[element] - a.server[element]; + } + ); +} + +function textsort(object, element, order){ + + var sort = object.slice().sort( + function(a, b){ + + return a.server[element].localeCompare(b.server[element]); + } + ); + + if(!order){ + return sort.reverse(); + } + + return sort; +} + +function render_list(){ + + var sorted_list = []; + + // sort + var filter = Boolean(sort % 2); + + switch(sort){ + + case 0: + case 1: + sorted_list = textsort(pinged_list, "name", filter === true ? false : true); + break; + + case 2: + case 3: + sorted_list = textsort(pinged_list, "ip", filter === true ? false : true); + break; + + case 4: + case 5: + sorted_list = sorta(pinged_list, "bot_protection", filter === true ? false : true); + break; + + case 6: + case 7: + sorted_list = sorta(pinged_list, "real_requests", filter); + break; + + case 8: + case 9: + sorted_list = sorta(pinged_list, "bot_requests", filter); + break; + + case 10: + case 11: + sorted_list = sorta(pinged_list, "api_enabled", filter); + break; + + case 12: + case 13: + sorted_list = sorta(pinged_list, "version", filter); + break; + } + + // render tabloid + var html = ""; + + for(var k=0; k<sorted_list.length; k++){ + + html += '<tr onclick="show_server(' + sorted_list[k].index + ');">'; + + for(var i=0; i<7; i++){ + + html += '<td'; + + switch(i){ + + // server name + case 0: html += ' class="extend">' + htmlspecialchars(sorted_list[k].server.name); break; + case 1: html += '>' + htmlspecialchars(new URL(sorted_list[k].server.ip).host); break; + case 2: // bot protection + switch(sorted_list[k].server.bot_protection){ + + case 0: + html += '><span style="color:var(--green);">Disabled</span>'; + break; + + case 1: + html += '><span style="color:var(--yellow);">Image captcha</span>'; + break; + + case 2: + html += '><span style="color:var(--red);">Invite only</span>'; + break; + + default: + html += '>Unknown'; + } + break; + + case 3: // real reqs + html += '>' + number_format(sorted_list[k].server.real_requests); + break; + + case 4: // bot reqs + html += '>' + number_format(sorted_list[k].server.bot_requests); + break; + + case 5: // api enabled + + if(sorted_list[k].server.api_enabled){ + + html += '><span style="color:var(--green);">Yes</span>'; + }else{ + + html += '><span style="color:var(--red);">No</span>'; + } + break; + + // version + case 6: html += ">v" + sorted_list[k].server.version; break; + } + + html += '</td>'; + } + + html += '</tr>'; + } + + console.log(html); + + tbody.innerHTML = html; +} + +var popup_bg = document.getElementById("popup-bg"); +var popup_wrapper = document.getElementsByClassName("popup-wrapper")[0]; +var popup = popup_wrapper.getElementsByClassName("popup")[0]; +var popup_shown = false; + +popup_bg.addEventListener("click", function(){ + + popup_wrapper.style.display = "none"; + popup_bg.style.display = "none"; +}); + +function show_server(serverid){ + + var html = + '<h2>' + htmlspecialchars(pinged_list[serverid].server.name) + '</h2>' + + 'Description' + + '<div class="code">' + htmlspecialchars(pinged_list[serverid].server.description) + '</div>'; + + var url_obj = new URL(pinged_list[serverid].server.ip); + var url = htmlspecialchars(url_obj.origin); + var domain = url_obj.hostname; + + html += + 'URL: <a rel="noreferer" target="_BLANK" href="' + url + redir + '">' + url + '</a> <a rel="noreferer" target="_BLANK" href="https://browserleaks.com/ip/' + encodeURIComponent(domain) + '">(IP lookup)</a>' + + '<br><br>Alt addresses:'; + + var len = pinged_list[serverid].server.alt_addresses.length; + + if(len === 0){ + + html += ' <i><Empty></i>'; + }else{ + + html += '<ul>'; + + for(var i=0; i<len; i++){ + + var url_obj = new URL(pinged_list[serverid].server.alt_addresses[i]); + var url = htmlspecialchars(url_obj.origin); + var domain = url_obj.hostname; + + if(validate_url(pinged_list[serverid].server.alt_addresses[i], true)){ + + html += '<li><a rel="noreferer" href="' + url + redir + '" target="_BLANK">' + url + '</a> <a rel="noreferer" target="_BLANK" href="https://browserleaks.com/ip/' + encodeURIComponent(domain) + '">(IP lookup)</a></li>'; + }else{ + + console.warn(pinged_list[serverid].server.ip + ": Invalid peer URL => " + pinged_list[serverid].server.alt_addresses[i]); + } + } + + html += '</ul>'; + } + popup.innerHTML = html; + + popup_wrapper.style.display = "block"; + popup_bg.style.display = "block"; +} + +function hide_server(){ + + popup_wrapper.style.display = "none"; + popup_bg.style.display = "none"; +} diff --git a/static/style.css b/static/style.css new file mode 100644 index 0000000..6276417 --- /dev/null +++ b/static/style.css @@ -0,0 +1,1384 @@ +:root{ + /* background */ + --1d2021: #1d2021; + --282828: #282828; + --3c3836: #3c3836; + --504945: #504945; + + /* font */ + --928374: #928374; + --a89984: #a89984; + --bdae93: #bdae93; + --8ec07c: #8ec07c; + --ebdbb2: #ebdbb2; + + /* code highlighter */ + --comment: #9e8e73; + --default: #d4be98; + --keyword: #d8a657; + --string: #7daea7; + + /* color codes for instance list */ + --green: #b8bb26; + --yellow: #d8a657; + --red: #fb4934; +} + +audio{ + max-width:100%; + display:block; +} + +.left audio{ + margin-top:7px; +} + +.right-wrapper audio{ + margin-bottom:17px; +} + +body,html{ + padding:0; + margin:0; +} + +body{ + background:var(--1d2021); + color:var(--a89984); + font-size:16px; + box-sizing:border-box; + font-family:sans-serif; + margin:15px 7% 45px; + word-wrap:anywhere; + line-height:22px; + max-width:2000px; + position:relative; +} + +.navigation{ + position:absolute; + top:0; + right:0; + font-size:14px; + line-height:40px; +} + +.navigation a{ + color:var(--bdae93); + text-decoration:none; +} + +.navigation a:hover{ + text-decoration:underline; +} + +.navigation a:not(:last-child)::after{ + content:"|"; + padding:0 7px; + display:inline-block; + color:var(--504945); +} + +h1,h2,h3,h4,h5,h6{ + padding:0; + margin:0 0 7px 0; + line-height:initial; + color:var(--bdae93); +} + +h3,h4,h5,h6{ + margin-bottom:14px; +} + +/* + Web styles +*/ +#overflow{ + overflow:hidden; +} + +/* Searchbox */ +.searchbox{ + width:40%; + height:36px; + border:1px solid var(--504945); + background:var(--282828); + border-radius:2px; + margin-bottom:10px; + position:relative; +} + +.searchbox .wrapper{ + overflow:hidden; +} + +.searchbox input[type="text"]{ + width:100%; + padding-left:10px; +} + +.searchbox input[type="text"]::placeholder{ + color:var(--928374); +} + +.searchbox input[type="submit"]{ + float:right; + cursor:pointer; + padding:0 10px; +} + +.searchbox input[type="submit"]:hover{ + text-decoration:underline; +} + +.searchbox input{ + all:unset; + line-height:36px; + box-sizing:border-box; + height:36px; + color:var(--bdae93); +} + +.searchbox:focus-within{ + border:1px solid var(--928374); +} + +.autocomplete{ + display:none; + position:absolute; + top:35px; + left:-1px; + right:-1px; + background:var(--282828); + border:1px solid var(--928374); + border-top:none; + border-radius:0 0 2px 2px; + z-index:10; + overflow:hidden; +} + +.autocomplete .entry{ + overflow:hidden; + padding:4px 10px; + cursor:pointer; + outline:none; + user-select:none; +} + +.autocomplete .entry:hover{ + background:var(--3c3836); +} + +.autocomplete .entry:focus{ + background:var(--3c3836); +} + +/* Tabs */ +.tabs, .filters{ + overflow:hidden; + overflow-x:auto; + white-space:nowrap; +} + +.tabs{ + padding-bottom:10px; +} + +.tabs .tab{ + text-decoration:none; + color:var(--bdae93); + padding:4px 10px; + display:inline-block; +} + +.tabs .tab:hover{ + text-decoration:underline; +} + +.tabs .tab.selected{ + border-bottom:2px solid var(--bdae93); +} + +/* Filters */ +.filters{ + margin-bottom:7px; +} + +.filters .filter{ + display:inline-block; + margin-right:7px; + vertical-align:bottom; +} + +.filters .filter .title{ + font-size:13px; + margin:0 4px; +} + +.filters .filter input, +.filters .filter select{ + all:unset; + user-select:none; + display:block; + border:1px solid var(--504945); + border-radius:2px; + font-size:14px; + padding:0 4px; + width:127px; + height:24px; +} + +.timetaken{ + font-size:14px; + font-weight:bold; + margin-bottom:10px; +} + + +/* + HOME +*/ +.home{ + min-height:100vh; + margin:0 auto; + display:table; + text-align:center; +} + +.home .logo{ + max-width:400px; + height:100px; + margin:0 auto 17px auto; +} + +.home img{ + line-height:100px; + font-size:60px; + text-align:center; + font-family:Times; + width:100%; + height:100%; + background:var(--282828); + display:block; + object-fit:contain; +} + +.home #center{ + display:table-cell; + vertical-align:middle; + width:500px; +} + +.home .searchbox{ + width:100%; + text-align:left; + margin-bottom:20px; +} + +.home a{ + color:inherit; +} + +.home .subtext{ + margin-top:17px; + line-height:16px; + font-size:12px; +} + + +/* + WEB +*/ + +/* Captcha */ +.captcha-wrapper{ + position:relative; + max-width:400px; + margin:17px auto 0; + border:1px solid var(--928374); +} + +.captcha{ + padding-bottom:100%; + padding-top:6.2%; +} + +.captcha-wrapper img{ + position:absolute; + top:0; + left:0; + width:100%; + height:100%; +} + +.captcha-controls{ + position:absolute; + top:0; + left:0; + bottom:0; + right:0; + top:6.3%; +} + +.captcha-wrapper img{ + display:block; + background:#282828; +} + +.captcha-wrapper input{ + display:none; +} + +.captcha-wrapper label{ + float:left; + width:25%; + height:25%; + position:relative; + cursor:pointer; +} + +.captcha-wrapper label:hover{ + background:rgba(255,255,255,0.2); +} + +.captcha-wrapper input:checked + label{ + background:rgba(0,0,0,0.5); +} + +.captcha-wrapper input:checked + label:after{ + content:""; + position:absolute; + left:39%; + top:29%; + width:20%; + height:30%; + transform:rotate(45deg); + border-right:7px solid var(--ebdbb2); + border-bottom:7px solid var(--ebdbb2); + box-sizing:border-box; +} + +.captcha-submit{ + float:right; + margin:12px 0 4px; +} + +.web .left{ + width:40%; + float:left; +} + +/* infobox */ +.infobox{ + border:1px dashed var(--504945); + padding:10px; + margin-bottom:17px; + overflow:hidden; +} + +.infobox .code{ + white-space:initial; +} + +.infobox ul{ + padding-left:27px; + margin-bottom:0; +} + +.infobox a{ + color:var(--bdae93); +} + +.infobox a:hover{ + text-decoration:underline; +} + +/* text-result */ +.web .text-result{ + margin-bottom:30px; +} + +.web .description{ + white-space:pre-line; +} + +.web .type{ + border:1px solid var(--928374); + background:var(--282828); + padding:0 4px; + border-radius:2px; + font-size:14px; + line-height:16px; + float:left; + margin:2px 7px 0 0; +} + +.web .url{ + position:relative; +} + +.web .url .part{ + font-size:15px; + text-decoration:none; + color:var(--928374); +} + +.web .separator::before{ + content:"/"; + padding:0 4px; + color:var(--504945); + font-size:12px; +} + +.web .part:hover{ + text-decoration:underline; +} + +.web .hover{ + display:block; + text-decoration:none; + color:var(--a89984); + overflow:hidden; + clear:left; + padding-top:7px; +} + +.web .text-result .title{ + font-size:18px; + color:var(--bdae93); + margin-bottom:7px; +} + +.web .text-result a:visited .title{ + color:var(--928374) !important; +} + +.theme-white .web .text-result a:visited .title{ + color:#7c6f64 !important; +} + +.web .text-result .hover:hover .title{ + text-decoration:underline; +} + +.web .text-result .author{ + font-style:italic; +} + +.web .text-result .greentext{ + font-size:14px; + color:var(--8ec07c); +} + +.web .right-right .text-result:last-child, +.web .right-left .text-result:last-child{ + margin-bottom:0; +} + +/* favicon */ +.favicon{ + all:unset; + float:left; + cursor:pointer; +} + +.favicon-dropdown{ + display:none; + position:absolute; + top:25px; + background:var(--282828); + border:1px solid var(--504945); + border-radius:2px; + z-index:3; + word-wrap:normal; +} + +.favicon-dropdown::before{ + content:""; + position:absolute; + top:-10px; + left:2px; + border:5px solid transparent; + border-bottom:5px solid var(--504945); +} + +.favicon-dropdown a{ + text-decoration:none; + color:var(--bdae93); + display:block; + padding:2px 7px 2px 5px; + font-size:13px; +} + +.favicon-dropdown a:hover{ + text-decoration:underline; +} + +.favicon-dropdown:hover, +.favicon:focus + .favicon-dropdown, +.favicon-dropdown:focus-within{ + display:block; +} + +.web .favicon img, +.favicon-dropdown img{ + margin:3px 7px 0 0; + width:16px; + height:16px; + font-size:12px; + line-height:16px; + text-align:center; + display:block; + text-align:left; + white-space:nowrap; +} + +.favicon-dropdown img{ + float:left; + margin:2px 7px 0 0; +} + +/* thumbnails */ +.thumb-wrap{ + position:relative; + float:right; + width:160px; + height:90px; + background:var(--282828); + border:1px solid var(--504945); + margin-left:7px; +} + +.duration{ + position:absolute; + right:0; + bottom:0; + padding:1px 2px; + line-height:14px; + background:var(--3c3836); + font-size:12px; + border-left:1px solid var(--504945); + border-top:1px solid var(--504945); + font-family:monospace; +} + +.web .text-result:hover .thumb-wrap .duration{ + display:none; +} + +.thumb-wrap .thumb{ + display:block; + object-fit:contain; + width:100%; + height:100%; +} + +.thumb-wrap.portrait{ + width:50px; +} + +.thumb-wrap.square{ + width:90px; +} + +/* Next page */ +.nextpage{ + margin:0 0 30px; + text-align:center; + display:block; + padding:10px; + border:1px solid var(--504945); + border-radius:2px; + text-decoration:none; + color:var(--bdae93); +} + +.nextpage:hover{ + text-decoration:underline; +} + +/* Right wrapper */ +.web .right-wrapper{ + width:60%; + float:right; + overflow:hidden; + padding-left:15px; + box-sizing:border-box; +} + +.web .right-right, +.web .right-left{ + float:right; + width:50%; + padding:0 15px; + box-sizing:border-box; + overflow:hidden; + min-height:1px; +} + +.web .right-right{ + padding-right:0; +} + +/* + Tables +*/ +table{ + width:100%; + text-align:left; + border-collapse:collapse; +} + +table td{ + width:50%; + padding:0; + vertical-align:top; +} + +table tr td:first-child{ + padding-right:7px; +} + +table a{ + display:block; + text-decoration:none; + color:var(--a89984); + padding:0 10px 0 0; +} + +table tr a:last-child{ + padding-right:0; +} + +/* Related */ +.related{ + margin-bottom:20px; +} + +.related a{ + padding-bottom:10px; + color:var(--bdae93); +} + +.related a:hover{ + text-decoration:underline; +} + +/* + Answers +*/ +.web .answer{ + max-height:600px; + overflow:hidden; + padding-bottom:17px; + position:relative; +} + +.web .answer::after{ + content:""; + position:absolute; + bottom:0; + width:100%; + height:17px; + background:linear-gradient(transparent, var(--1d2021)); + pointer-events:none; +} + +.web .answer-title{ + text-decoration:none; + color:var(--a89984); +} + +.web .answer-title a:hover{ + text-decoration:underline; +} + +.web .spoiler:checked + .answer{ + overflow:initial; + max-height:initial; +} + +.web .spoiler{ + display:none; +} + +.web .spoiler-button{ + display:block; + border:1px solid var(--504945); + border-radius:2px; + line-height:30px; + padding:0 7px; + text-align:center; + cursor:pointer; +} + +.web .answer-wrapper{ + margin-bottom:27px; +} + +.web .spoiler-button:hover{ + text-decoration:underline; +} + +.web .spoiler-button::before{ + content:"Show more"; +} + +.web .spoiler:checked + .answer + .spoiler-button::before{ + content:"Show less"; +} + +/* Tables on left handside */ +.web .info-table{ + margin:10px 0; + font-size:15px; + color:var(--928374); + background:var(--282828); + border:1px dashed var(--504945); +} + +.web .info-table td{ + padding:4px 10px; +} + +.web .info-table tr td:first-child{ + width:1%; + white-space:nowrap; + padding-right:17px; + color:var(--a89984); +} + +.web .info-table tr:nth-child(even){ + background:var(--1d2021); +} + +.web .sublinks{ + padding:17px 10px 0; + font-size:15px; + color:var(--#928374); +} + +.web .sublinks table td{ + padding-bottom:17px; +} + +.web .sublinks table tr:last-child td:last-child{ + padding-bottom:0; +} + +.web .sublinks a:hover .title{ + text-decoration:underline; +} + +/* Wikipedia head */ +.web .wiki-head .photo{ + float:right; + margin:0 1px 10px 10px; +} +.web .wiki-head .photo img{ + display:block; + max-width:200px; + max-height:200px; + filter:drop-shadow(1px 0 0 var(--504945)) drop-shadow(-1px 0 0 var(--504945)) drop-shadow(0 -1px 0 var(--504945)) drop-shadow(0 1px 0 var(--504945)); +} + +.web .wiki-head .description{ + clear:left; + padding-top:7px; + overflow:hidden; +} + +.web .wiki-head table, .about table{ + margin-top:17px; + border:1px dashed var(--504945); + background:var(--1d2021); +} + +.web .wiki-head table td{ + white-space:pre-line; +} + +.web .wiki-head td, .about table td{ + padding:4px 7px; + vertical-align:middle; +} + +.web .wiki-head tr td:first-child, .about table tr td:first-child{ + width:30%; + min-width:150px; +} + +.web .wiki-head tr:nth-child(odd), .about table tr:nth-child(odd){ + background:var(--282828); +} + +.web .wiki-head .socials{ + overflow:hidden; + margin-top:17px; +} + +.web .wiki-head .socials a{ + width:74px; + height:80px; + padding-right:4px; + float:left; + color:var(--bdae93); + text-decoration:none; + display:table; +} + +.web .wiki-head .socials a:hover .title{ + text-decoration:underline; +} + +.web .wiki-head .socials .center{ + display:table-cell; + vertical-align:middle; +} + +.web .wiki-head .socials img{ + margin:0 auto; + display:block; + text-align:center; + width:36px; + height:36px; + line-height:36px; +} + +.web .wiki-head .socials .title{ + margin-top:7px; + text-align:center; + font-size:13px; + line-height:13px; +} + +.web .fullimg{ + display:block; + max-width:100%; + max-height:150px; + margin:7px 0 17px; + box-sizing:border-box; + border:1px solid var(--504945); +} + +/* + Code tags +*/ +.code{ + white-space:pre; + font-family:monospace; + background:var(--3c3836); + color:var(--bdae93); + padding:7px; + margin:4px 0 13px 0; + overflow-x:auto; + border-radius:2px; + border:1px solid var(--504945); +} + +.code-inline{ + display:inline; + font-family:monospace; + background:var(--282828); + color:var(--bdae93); + border:1px solid var(--928374); + padding:0 4px; + border-radius:2px; +} + +/* Wiki-head titles and quotes */ +.web .wiki-head h2{ + font-size:20px; + margin:20px 0 13px 0; +} + +.web .wiki-head h2:first-child{ + margin-top:10px; +} + +.web .wiki-head a{ + color:var(--bdae93); +} + +.quote{ + font-style:italic; + margin:10px 0 13px; + padding-left:10px; + border-left:1px solid #504945; +} + +/* + Web images +*/ +.web .images{ + overflow:hidden; + margin:0 -5px; + font-size:0; +} + +.web .images .duration{ + display:none; + border:1px solid var(--504945); + right:5px; + bottom:5px; +} + +.web .images .image:hover .duration{ + display:block; +} + +.web .images .image{ + width:90px; + height:90px; + padding:5px; + position:relative; + line-height:90px; + display:inline-block; + text-align:center; + color:inherit; +} + +.web .images .image img{ + max-width:100%; + max-height:100%; + vertical-align:middle; +} + + +/* + Images tab +*/ + +#images{ + overflow:hidden; + margin-bottom:10px; +} + +#images .infobox{ + width:40%; + box-sizing:border-box; +} + +#images .image-wrapper{ + line-height:15px; + width:20%; + float:left; +} + +#images .image{ + margin:0 auto; + width:250px; + max-width:100%; + padding:7px 7px 30px 7px; + box-sizing:border-box; + font-size:14px; +} + +#images a{ + color:inherit; + text-decoration:none; + display:block; +} + +#images a:hover .title{ + text-decoration:underline; +} + +#images .thumb{ + display:block; + height:180px; + margin-bottom:10px; + position:relative; +} + +#images .duration{ + display:block; + border:1px solid #504945; +} + +#images .image:hover .duration{ + display:none; +} + +#images img{ + width:100%; + height:100%; + object-fit:contain; +} + +#images .image .title{ + white-space:nowrap; + overflow:hidden; + margin-bottom:7px; + font-weight:bold; +} + +#images .image .description{ + overflow:hidden; + height:45px; +} + +.nextpage.img{ + width:50%; + margin:0 auto 50px; +} + +#popup{ + display:none; + position:fixed; + top:0; + left:0; + cursor:grab; + user-select:none; + pointer-events:none; + z-index:5; +} + +#popup:active{ + cursor:grabbing; +} + +#popup-image{ + border:1px solid var(--928374); + display:block; + margin:0 auto; + pointer-events:all; + width:100%; + height:100%; + object-fit:contain; + background:var(--282828); +} + +#popup-status{ + display:none; + position:fixed; + top:0; + left:0; + width:100%; + height:35px; + background:var(--1d2021); + border-bottom:1px solid var(--928374); + z-index:4; +} + +#popup-bg{ + background:var(--1d2021); + opacity:.5; + position:fixed; + top:0; + left:0; + width:100%; + height:100%; + display:none; + z-index:3; +} + +#popup-status select{ + display:block; + width:250px; +} + +#popup-num, +#popup-title{ + display:table-cell; + width:0; + word-wrap:normal; + padding:0 10px; + line-height:35px; + color:var(--ebdbb2); + text-decoration:none; +} + +#popup-title:hover{ + text-decoration:underline; +} + +#popup-title{ + width:initial; + overflow:hidden; + height:35px; + display:block; +} + +#popup-num{ + font-weight:bold; +} + +#popup-dropdown{ + display:table-cell; + vertical-align:middle; + width:0; +} + +/* + Settings page +*/ +.web .settings{ + margin-top:17px; + border:1px dashed var(--504945); + padding:7px 10px 0; +} + +.web .setting{ + margin-bottom:17px; +} + +.web .setting .title{ + font-size:14px; +} + +.web .settings-submit{ + margin:17px 10px; +} + +.web .settings-submit input{ + float:right; +} + +.web .settings-submit a{ + margin-right:17px; + color:var(--bdae93); +} + +/* + About page +*/ +.about a{ + color:var(--bdae93); +} + +.about h1, .about h2{ + margin-top:17px; +} + +.about table{ + margin-bottom:17px; +} + +.about table a{ + display:inline; +} + + +/* + Syntax highlight +*/ +.c-comment{ + color:var(--comment); +} +.c-default{ + color:var(--default); +} +.c-html{ + color:var(--html); +} +.c-keyword{ + color:var(--keyword); + font-weight:bold; +} +.c-string{ + color:var(--string); +} + +/* + Instances page +*/ +.instances table{ + white-space:nowrap; + margin-top:17px; +} + +.instances a{ + color:var(--bdae93); +} + +.instances tbody tr:nth-child(even){ + background:var(--282828); +} + +.instances thead{ + outline:1px solid var(--928374); + outline-offset:-1px; + background:var(--3c3836); + user-select:none; + z-index:2; + position:sticky; + top:0; +} + +.instances th{ + cursor:row-resize; +} + +.instances th:hover{ + background:var(--504945); +} + +.instances tbody{ + outline:1px solid var(--504945); + outline-offset:-1px; + position:relative; + top:-1px; +} + +.instances tbody tr:hover{ + background:var(--3c3836); + cursor:pointer; +} + +.instances .arrow{ + display:inline-block; + position:relative; + top:6px; + margin-right:7px; + width:0; + height:0; + border:6px solid transparent; + border-top:10px solid var(--bdae93); +} + +.instances .arrow.up{ + top:0; + border:6px solid transparent; + border-bottom:10px solid var(--bdae93); +} + +.instances th, .instances td{ + padding:4px 7px; + width:0; +} + +.instances .extend{ + width:unset; + overflow:hidden; + max-width:200px; +} + +.instances .popup-wrapper{ + display:none; + position:fixed; + left:50%; + top:50%; + transform:translate(-50%, -50%); + width:800px; + max-width:100%; + max-height:100%; + overflow-x:auto; + padding:17px; + box-sizing:border-box; + pointer-events:none; + z-index:3; +} + +.instances .popup{ + border:1px solid var(--928374); + background:var(--282828); + padding:7px 10px; + pointer-events:initial; +} + +.instances ul{ + padding-left:20px; +} + +.instances .go-back{ + margin-top:17px; + display:inline-block; +} + + +/* + Responsive image +*/ +@media only screen and (max-width: 1454px){ #images .image-wrapper{ width:25%; } } +@media only screen and (max-width: 1161px){ #images .image-wrapper{ width:33.3333%; } } +@media only screen and (max-width: 750px){ #images .image-wrapper{ width:50%; } } +@media only screen and (max-width: 450px){ #images .image-wrapper{ width:100%; } } + + +/* + Responsive design +*/ +@media only screen and (max-width: 1550px){ + + .web .right-right, + .web .right-left{ + float:none; + width:initial; + padding:0 0 0 15px; + } + + .web .left, + .searchbox, + #images .infobox{ + width:60%; + } + + .web .right-wrapper{ + width:40%; + } +} + +@media only screen and (max-width: 1000px){ + form{ + padding-top:27px; + } + + .navigation{ + left:0; + right:unset; + line-height:22px; + } + + .nextpage.img{ + width:initial; + } + + .web .right-right, + .web .right-left{ + border:none; + padding:0; + } + + .web .right-wrapper{ + float:none; + padding:0; + width:initial; + } + + .web .left, + .searchbox{ + width:100%; + } + + body:not(.instances) table td{ + display:block; + width:100%; + } + + table a{ + padding:0; + } + + .web.has-answer .left::before{ + display:block; + content:"Results"; + font-size:24px; + font-weight:bold; + margin-bottom:17px; + color:var(--bdae93); + } + + .web .answer{ + max-height:200px; + } + + .web .wiki-head tr td:first-child, + .web .info-table tr td:first-child{ + text-decoration:underline; + } + + #images .infobox{ + width:100%; + } +} diff --git a/static/themes/Catppuccin Latte.css b/static/themes/Catppuccin Latte.css new file mode 100644 index 0000000..7c70549 --- /dev/null +++ b/static/themes/Catppuccin Latte.css @@ -0,0 +1,20 @@ +:root{ + /* background */ + --1d2021: #eff1f5; + --282828: #eff1f5; + --3c3836: #dce0e8; + --504945: #5c5f77; + + /* font */ + --928374: #8c8fa1; + --a89984: #4c4f69; + --bdae93: #4c4f69; + --8ec07c: #df8e1d; + --ebdbb2: #4c4f69; + + /* code highlighter */ + --comment: #e64553; + --default: #eff1f5; + --keyword: #df8e1d; + --string: #209fb5; +} diff --git a/static/themes/Catppuccin Mocha.css b/static/themes/Catppuccin Mocha.css new file mode 100644 index 0000000..03a3fa8 --- /dev/null +++ b/static/themes/Catppuccin Mocha.css @@ -0,0 +1,20 @@ +:root{ + /* background */ + --1d2021: #1e1e2e; + --282828: #313244; + --3c3836: #45475a; + --504945: #585b70; + + /* font */ + --928374: #bac2de; + --a89984: #a6adc8; + --bdae93: #cdd6f4; + --8ec07c: #a6e3a1; + --ebdbb2: #f9e2af; + + /* code highlighter */ + --comment: #f5e0dc; + --default: #f2cdcd; + --keyword: #fab387; + --string: #74c7ec; +} diff --git a/static/themes/Cream.css b/static/themes/Cream.css new file mode 100644 index 0000000..3d6b615 --- /dev/null +++ b/static/themes/Cream.css @@ -0,0 +1,31 @@ +:root{ + /* background */ + --1d2021: #bdae93; + --282828: #a89984; + --3c3836: #a89984; + --504945: #504945; + + /* font */ + --928374: #1d2021; + --a89984: #282828; + --bdae93: #3c3836; + --8ec07c: #52520e; + --ebdbb2: #1d2021; + + /* code highlighter */ + --comment: #6a4400; + --default: #d4be98; + --keyword: #4a4706; + --string: #076678; + + /* color codes for instance list */ + --green: #636311; + --yellow: #8a6214; + --red: #711410; +} + +.autocomplete .entry:hover, +.instances th:hover +{ + background:#928374; +} diff --git a/static/themes/Dark Christmas.css b/static/themes/Dark Christmas.css new file mode 100644 index 0000000..0a097f1 --- /dev/null +++ b/static/themes/Dark Christmas.css @@ -0,0 +1,95 @@ +body{ + background-image:url("/static/misc/christmas-dark-bg.png"); +} + +.home::before{ + content:""; + position:fixed; + top:0; + left:0; + width:100%; + height:100%; + background-image:url("/static/misc/snow.png"); + pointer-events:none; + z-index:-1; + animation:snowfall 12s linear infinite; + opacity:.6; +} + +.home{ + background:#1d2021; +} + +@keyframes snowfall{ + from{ + background-position:0% 0px; + } + + to{ + background-position:0% 600px; + } +} + +.web .answer::after{ + display:none; +} + +:root{ + /* background */ + --1d2021: #1d2021; + --282828: #282828; + --3c3836: #3c3836; + --504945: #504945; + + /* font */ + --928374: #928374; + --a89984: #bdae93; + --bdae93: #d5c4a1; + --8ec07c: #8ec07c; + --ebdbb2: #ebdbb2; + + /* code highlighter */ + --comment: #9e8e73; + --default: #d4be98; + --keyword: #d8a657; + --string: #7daea7; + + /* color codes for instance list */ + --green: #b8bb26; + --yellow: #d8a657; + --red: #fb4934; +} + +.web .wiki-head table, .about table, .web .info-table, .instances table{ + background:#1d202170; + color:#bdae93; +} + +.web .wiki-head tr:nth-child(odd), .about table tr:nth-child(odd), .web .info-table tr:nth-child(even), .nextpage, .spoiler-button, .instances tbody tr:nth-child(even){ + background:#28282870; + color:#bdae93; +} + +.instances tbody tr:hover{ + background:#3c383690; +} + +.wiki-head .description{ + overflow:initial !important; +} + +.wiki-head .photo{ + position:relative; +} + +.wiki-head .photo::after{ + content:""; + position:absolute; + width:100px; + height:100px; + background-image:url("/static/misc/christmas-hat.png"); + background-size:contain; + top:-61px; + left:-31px; + transform:rotate(310deg); +} diff --git a/static/themes/Gore's shitty theme.css b/static/themes/Gore's shitty theme.css new file mode 100644 index 0000000..d32f44a --- /dev/null +++ b/static/themes/Gore's shitty theme.css @@ -0,0 +1,322 @@ +:root{ + --1d2021:#1d2021; + --282828:#282828; + --3c3836:#3c3836; + --504945:#504945; + + /* font */ + --928374:#928374; + --a89984:#c9c5bf; + --bdae93:#bdae93; + --8ec07c:#8ec07c; + --ebdbb2:#ebdbb2; +} + +body{ + padding:15px 4% 40px; + margin:unset; +} + +h1, h2, h3, h4, h5, h6{ + padding:0; + margin:0 0 7px 0; + line-height:initial; + color:var(--bdae93); +} + +h3, h4, h5, h6{ + margin-bottom:14px; +} + +/* + Web styles +*/ + +.searchbox input[type="submit"]{ + float:right; + cursor:pointer; + padding:0 10px; + border-left:1px solid var(--504945); + background:#723c0b; +} + +.searchbox input{ + all:unset; + line-height:36px; + box-sizing:border-box; + height:36px; +} + +.searchbox:focus-within{ + border:1px solid #ee8a9c; +} + +.autocomplete{ + display:none; + position:absolute; + top:35px; + left:-1px; + right:-1px; + background:var(--282828); + border:1px solid var(--504945); + border-top:none; + border-radius:0 0 2px 2px; + z-index:10; +} + +.autocomplete .entry{ + overflow:hidden; + padding:4px 10px; + cursor:pointer; +} + +.autocomplete .title{ + float:left; +} + +.autocomplete .subtext{ + float:right; + font-size:14px; + color:var(--928374); + margin-left:7px; +} + +/* Tabs */ + +.tabs{ + padding-bottom:0px; +} + +.tabs .tab{ + text-decoration:none; + color:#d3d0c1; + padding:0px 10px; + display:inline-block; +} + +.tabs .tab.selected{ + border-bottom:2px solid #fc92a5; +} + +/* Filters */ +.filters{ + padding-bottom:12px; + padding-top:7px; + margin-bottom:7px; + background-color:#232525; +} + +.filters .filter{ + display:inline-block; + margin-right:7px; +} + +.filters .filter .title{ + font-size:13px; +} + +.filters .filter input, +.filters .filter select{ + all:unset; + display:block; + border:1px solid var(--504945); + border-radius:2px; + font-size:14px; + padding:0 2px; + width:127px; + height:22px; +} + +/* infobox */ +.web .infobox{ + border:1px dashed var(--504945); + padding:10px; + margin-bottom:17px; +} + +.web .infobox .code{ + white-space:initial; +} + +.web .infobox ul{ + padding-left:27px; + margin-bottom:0; +} + +.web .infobox a{ + color:var(--bdae93); +} + +.web .infobox a:hover{ + text-decoration:underline; +} + +/* text-result */ + +.web .url .part{ + font-size:15px; + text-decoration:none; + color:#90c186; +} + +.web .separator::before{ + content:"/"; + padding:0 4px; + color:#5ab442; + font-size:12px; +} + +.web .hover{ + display:block; + text-decoration:none; + color:var(--a89984); + overflow:hidden; + clear:left; + padding-top:3px; +} + +.web .text-result .title{ + font-size:18px; + color:#81b5f4; + margin-bottom:5px; +} + +.web .text-result a:visited .title{ + color:#aa77c1 !important; +} + +.theme-white .web .text-result a:visited .title{ + color:#9760b1 !important; +} + +.web .text-result .greentext{ + font-size:14px; + color:var(--bdae93); +} + +/* favicon */ + +.favicon-dropdown a{ + text-decoration:none; + color:#d3d0c1; + display:block; + padding:2px 7px 2px 5px; + font-size:13px; +} + +.web .favicon img, .favicon-dropdown img{ + margin:3px 7px 0 0; + height:16px; + font-size:12px; + line-height:16px; + display:block; + text-align:left; +} + +.web .sublinks{ + padding:17px 10px; + font-size:15px; + color:var(--#928374); +} + +.web .text-result .sublinks:last-child{ + padding-bottom:0; +} + +/* Wikipedia head */ +.wiki-head{ + padding:5px; + background-color:#322f2b; +} + +/* + Images tab +*/ + +#images{ + line-height:15px; + overflow:hidden; + margin-bottom:10px; +} + +#images .image-wrapper{ + width:20%; + float:left; +} + +#images .image .title{ + white-space:nowrap; + overflow:hidden; + margin-bottom:7px; + font-weight:bold; + color:var(--bdae93); +} + +#popup-status{ + display:none; + position:fixed; + top:0; + left:0; + width:100%; + height:35px; + background:var(--1d2021); + border-bottom:1px solid var(--928374); +} + +/* + Settings page +*/ + +.web .settings-submit a{ + margin-right:17px; + color:#bdae93; +} + +/* + Responsive image +*/ +@media only screen and (max-width:1454px){ + #images .image-wrapper{ + width:25%; + } +} + +@media only screen and (max-width:1161px){ + #images .image-wrapper{ + width:25%; + } +} + +@media only screen and (max-width:750px){ + #images .image-wrapper{ + width:50%; + } +} + +@media only screen and (max-width:450px){ + #images .image-wrapper{ + width:100%; + } +} + +/* + Responsive design +*/ + +@media only screen and (max-width:1550px){ +.web .left, + .searchbox{ + width:60%; + } +} + +@media only screen and (max-width:1100px){ +.web .left, + .searchbox{ + width:100%; + } +} + +.type{ + color:var(--bdae93); +} diff --git a/static/themes/Kuuro.css b/static/themes/Kuuro.css new file mode 100644 index 0000000..fdb60e5 --- /dev/null +++ b/static/themes/Kuuro.css @@ -0,0 +1,17 @@ +:root{ + --1d2021: #101010; + --282828: #1a1a1a; + --3c3836: #1e1e1e; + --504945: #232323; + + --928374: #949494; + --a89984: #d2d2d2; + --bdae93: #d2d2d2; + --8ec07c: #99c794; + --ebdbb2: #d2d2d2; + + --comment: #5f6364; + --default: #cccece; + --keyword: #c594c5; + --string: #99c794; +}
\ No newline at end of file diff --git a/static/themes/White Christmas.css b/static/themes/White Christmas.css new file mode 100644 index 0000000..5368596 --- /dev/null +++ b/static/themes/White Christmas.css @@ -0,0 +1,94 @@ +body{ + background:#e7e7e7; + background-image:url("/static/misc/christmas-white-bg.png"); +} + +.home::before{ + content:""; + position:fixed; + top:0; + left:0; + width:100%; + height:100%; + background:#b9b5b380; + background-image:url("/static/misc/snow.png"); + pointer-events:none; + z-index:-1; + animation:snowfall 12s linear infinite; +} + +.web .answer::after{ + display:none; +} + +@keyframes snowfall{ + from{ + background-position:0% 0px; + } + + to{ + background-position:0% 600px; + } +} + +:root{ + /* background */ + --1d2021: #bdae93; + --282828: #e7e7e7; + --3c3836: #e7e7e7; + --504945: #504945; + + /* font */ + --928374: #1d2021; + --a89984: #282828; + --bdae93: #3c3836; + --8ec07c: #52520e; + --ebdbb2: #1d2021; + + /* code highlighter */ + --comment: #6a4400; + --default: #d4be98; + --keyword: #4a4706; + --string: #076678; + + /* color codes for instance list */ + --green: #636311; + --yellow: #8a6214; + --red: #711410; +} + +.autocomplete .entry:hover{ + background:#92837480; +} + +.web .wiki-head table, .about table, .web .info-table, .instances table{ + background:#a8998470; +} + +.web .wiki-head tr:nth-child(odd), .about table tr:nth-child(odd), .web .info-table tr:nth-child(even), .nextpage, .spoiler-button, .instances tbody tr:nth-child(even){ + background:#bdae9370; +} + +.instances tbody tr:hover{ + background:#92837480; +} + +.wiki-head .description{ + overflow:initial !important; +} + +.wiki-head .photo{ + position:relative; +} + +.wiki-head .photo::after{ + content:""; + position:absolute; + width:100px; + height:100px; + background-image:url("/static/misc/christmas-hat.png"); + background-size:contain; + top:-61px; + left:-31px; + transform:rotate(310deg); +} diff --git a/static/themes/Wine.css b/static/themes/Wine.css new file mode 100644 index 0000000..2d79f02 --- /dev/null +++ b/static/themes/Wine.css @@ -0,0 +1,40 @@ +:root +{ + --accent : #f79e98; + --1d2021 : #180d0c; + --282828 : #180d0c; + --3c3836 : #251615; + --504945 : #251615; + --928374 : var(--accent); + --a89984 : #d8c5c4; + --bdae93 : #d8c5c4; + --8ec07c : var(--accent); + --ebdbb2 : #d8c5c4; + --comment: #928374; + --default: #DCC9BC; + --keyword: #F07342; + --string : var(--accent); + --green : #959A6B; + --yellow : #E39C45; + --red : #CF223E; + --white : var(--a89984); + --black : var(--1d2021); + --hover : #b18884 +} + + a.link, a { color: var(--accent); text-decoration: none; } + .searchbox { width: 23%; } + .filters filter select { color: #E39C45; } + .web .separator::before { color: var(--white) } + .searchbox input[type="text"]::placeholder { color: var(--white); } + a.link:hover + { + color: var(--hover); + text-shadow: 0 0 .2rem var(--hover); + } + .code-inline + { border-color: var(--default); font-family: monospace;} + .home #center a + { color: var(--accent); } + .home .subtext + { color: var(--white); } diff --git a/static/themes/gentoo.css b/static/themes/gentoo.css new file mode 100644 index 0000000..b727108 --- /dev/null +++ b/static/themes/gentoo.css @@ -0,0 +1,20 @@ +:root{ + /* background */ + --1d2021: #21222d; + --282828: #393657; + --3c3836: #27273c; + --504945: #aa85e1; + + /* font */ + --928374: #906be3; + --a89984: #9794ac; + --bdae93: #cec0f2; + --8ec07c: #5db6e1; + --ebdbb2: #b194f5; + + /* code highlighter */ + --comment: #a0c0a4; + --default: #f00; + --keyword: #9376e4; + --string: #ecd78f; +} diff --git a/template/about.html b/template/about.html new file mode 100644 index 0000000..6398884 --- /dev/null +++ b/template/about.html @@ -0,0 +1,77 @@ +<a href="/" class="link">< Go back</a> + +<h1>Set as default search engine</h1> +<a href="#firefox"><h2 id="firefox">On Firefox and other Gecko based browsers</h2></a> +To set this as your default search engine on Firefox, right click the URL bar and select <div class="code-inline">Add "4get"</div>. Then, visit <a href="about:preferences#search" target="_BLANK" class="link">about:preferences#search</a> and select <div class="code-inline">4get</div> in the dropdown menu. + +<a href="#chrome"><h2 id="chrome">On Chromium and Blink based browsers</h2></a> +Click the 3 superpositioned dots at the top right of the screen and click on <div class="code-inline">Settings</div>, then search for <div class="code-inline">default search engine</div>, or visit <a href="chrome://settings/searchEngines">chrome://settings/searchEngines</a>.<br><br> + +Once you're there, click the pencil on the last entry under "Search engines" (it's probably DuckDuckGo). Once you do that, a popup will appear. Populate it with the following information: + +<table> + <tr> + <td><b>Field</b></td> + <td><b>Value</b></td> + </tr> + <tr> + <td>Search engine</td> + <td>{%server_name%}</td> + </tr> + <tr> + <td>Shortcut</td> + <td>{%server_name%}</td> + </tr> + <tr> + <td>URL with %s in place of query</td> + <td>https://4get.ca/web?s=%s</td> + </tr> +</table> + +Once that's done, click <div class="code-inline">Save</div>. Then, on the right handside of the newly created entry, open the dropdown menu and select <div class="code-inline">Make default</div>. + +<h1>Frequently asked questions</h1> +<a href="#what-is-this"><h2 id="what-is-this">What is this?</h2></a> +This is a metasearch engine that gets results from other engines, and strips away all of the tracking parameters and Microsoft/globohomo bullshit they add. Most of the other alternatives to Google jack themselves off about being ""privacy respecting"" or whatever the fuck but it always turns out to be a total lie, and I just got fed up with their shit honestly. Alternatives like Searx or YaCy all fucking sucks so I made my own thing. + +<a href="#goal"><h2 id="goal">My goal</h2></a> +Provide users with a privacy oriented, extremely lightweight, ad free, free as in freedom (and free beer!) way to search for documents around the internet, with minimal, optional javascript code. My long term goal would be to build my own index (that doesn't suck) and provide users with an unbiased search engine, with no political inclinations. + +<a href="#logs"><h2 id="logs">Do you keep logs?</h2></a> +I store data temporarly to get the next page of results. This might include search queries, filters and tokens. These parameters are encrypted using <div class="code-inline">libsodium</div> on the serber, for which I give you a decryption key (also known internally as <div class="code-inline">npt</div> token). When you make a request to get the next page, you supply the token, the data is decrypted and the request is fulfilled. This encrypted data is deleted after 15 minutes, or after it's used, whichever comes first.<br><br> + +I <b>don't</b> log IP addresses, user agents, or anything else. The <div class="code-inline">npt</div> tokens are the only thing that are stored (in RAM, mind you), temporarly, encrypted. + +<a href="#information-sharing"><h2 id="information-sharing">Do you share information with third parties?</h2></a> +Your search queries and supplied filters are shared with the scraper you chose (so I can get the search results, duh). I don't share anything else (that means I don't share your IP address, location, or anything of this kind). There is no way that site can know you're the one searching for something, <u>unless you send out a search query that de-anonymises you.</u> For example, a search query like "hello my full legal name is jonathan gallindo and i want pictures of cloacas" would definitively blow your cover. 4get doesn't contain ads or any third party javascript applets or trackers. I don't profile you, and quite frankly, I don't give a shit about what you search on there.<br><br> + +TL;DR assume those websites can see what you search for, but can't see who you are (unless you're really dumb). + +<a href="#hosting"><h2 id="hosting">Where is this website hosted?</h2></a> +Please head over to the <a href="/instances">4get instances</a> page, select an instance and click on "IP lookup". + +<a href="#keyboard-shortcuts"><h2 id="keyboard-shortcuts">Keyboard shortcuts?</h2></a> +Use <div class="code-inline">/</div> to focus the search box.<br><br> + +When the image viewer is open, you can use the following keybinds:<br> +<div class="code-inline">Up</div>, <div class="code-inline">Down</div>, <div class="code-inline">Left</div>, <div class="code-inline">Right</div> to rotate the image.<br> +<div class="code-inline">CTRL+Up</div>, <div class="code-inline">CTRL+Down</div>, <div class="code-inline">CTRL+Left</div>, <div class="code-inline">CTRL+Right</div> to mirror the image.<br> +<div class="code-inline">Escape</div> to exit the image viewer. + +<a href="#schizo"><h2 id="schizo">How can I trust you?</h2></a> +You just sort of have to take my word for it right now. If you'd rather trust yourself instead of me (I believe in you!!), all of the code on this website is available trough my <a href="https://git.lolcat.ca/lolcat" class="link">git page</a> for you to host on your own machines. Just a reminder: if you're the sole user of your instance, it doesn't take immense brain power for Microshit to figure out you basically just switched IP addresses. Invite your friends to use your instance! + +<a href="#donate"><h2 id="donate">Support the project</h2></a> +Donate to me trough ko-fi: <a href="https://ko-fi.com/lolcat" target="BLANK" rel="noreferrer">ko-fi.com/lolcat</a><br> +Please donate I sent myself a donation for testing if it works and it looks fucking dumb. Reasons to donate are listed on there. Thank you! + +<a href="#contact"><h2 id="contact">I want to report abuse or have erotic roleplay trough email</h2></a> +I don't know about that second part but if you want to talk to me, just drop me an email...<br><br> + +<b>Message to all DMCA enforcers:</b> I don't host any of the content. Everything you see here is <u>proxied</u> trough my shitbox with no moderation. Please reach out to the people hosting the infringing content instead.<br><br> + +<a href="https://lolcat.ca" rel="dofollow" class="link">Click here to contact me!</a><br><br> + +<a href="https://validator.w3.org/nu/?doc=https%3A%2F%2F4get.ca" title="W3 Valid!"> + <img src="/static/icon/w3html.png" alt="Valid W3C HTML 4.01" width="88" height="31"> +</a> diff --git a/template/donate.html b/template/donate.html new file mode 100644 index 0000000..f6f45bf --- /dev/null +++ b/template/donate.html @@ -0,0 +1,20 @@ +<a href="/" class="link">< Go back</a> + +<h1>Donate to the project</h1> +This project takes up most of my free time and costs money to run. If you feel like this project is worthy of a donation, please do so using the resources on this page!<br><br> + +To run smoothly, 4get requires 20$/month for the server fees and 15-25$ for residential proxies. I also have plans to build my own index to provide better search results; funds raised here will go directly towards better hardware for these purposes. According to the number of captchas solved, <a href="https://4get.ca">4get.ca</a> serves between 800-1400 users every day, or around 7000-10000 searches! + +<h2>Ko-fi</h2> +This is the most convenient way to donate. Supports PayPal. +<ul> + <li><a href="https://ko-fi.com/lolcat">ko-fi.com/lolcat</a></li> +</ul> + +<h2>Monero</h2> +Due to popular demand, I have added an XMR addy. I'm planning to reward users who donate to me once paid tiers are introduced to 4get, so please let me know through email that you donated to me (don't forget your transaction ID)! +<ul> + <li><a href="monero:85G95fXXfuh72oQd9LmdMHNqDTqsUPKkLCBEYE7XnnMLPvBfkdnan2FVTmVAwT4JEuXsRL7xPgqzuV2YdbFkWmxK2FgGBmB?tx_description=4get+donation">85G95fXXfuh72oQd9LmdMHNqDTqsUPKkLCBEYE7XnnMLPvBfkdnan2FVTmVAwT4JEuXsRL7xPgqzuV2YdbFkWmxK2FgGBmB</a></li> +</ul> + +Thank you all for your generous support!! diff --git a/template/header.html b/template/header.html new file mode 100644 index 0000000..accd4cd --- /dev/null +++ b/template/header.html @@ -0,0 +1,34 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> + <title>{%title%}</title> + <link title="{%server_name%}" href="/opensearch{%ac%}" rel="search" type="application/opensearchdescription+xml"> + <link rel="stylesheet" href="/static/style.css?v{%version%}"> + {%style%} + <meta name="viewport" content="width=device-width,initial-scale=1"> + <meta name="robots" content="{%index%}index,{%index%}follow"> + <link rel="icon" type="image/x-icon" href="/favicon.ico"> + <meta name="description" content="{%server_name%}: {%description%}"> + </head> + <body> + <div class="navigation"> + <a href="/">Home</a> + <a href="/settings">Settings</a> + <a href="https://git.lolcat.ca/lolcat/4get_news" target="_BLANK">News</a> + </div> + <form method="GET" autocomplete="off"> + <div class="searchbox"> + <input type="submit" value="Search" tabindex="-1"> + <div class="wrapper"> + <input type="text" value="{%search%}" maxlength="500" name="s" placeholder="Proxy search..." required> + </div> + <div class="autocomplete"></div> + </div> + <div class="tabs"> + {%tabs%} + </div> + <div class="filters"> + {%filters%} + </div> + </form> diff --git a/template/header_nofilters.html b/template/header_nofilters.html new file mode 100644 index 0000000..116eef6 --- /dev/null +++ b/template/header_nofilters.html @@ -0,0 +1,14 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> + <title>{%title%}</title> + <link title="{%server_name%}" href="/opensearch{%ac%}" rel="search" type="application/opensearchdescription+xml"> + <link rel="stylesheet" href="/static/style.css?v{%version%}"> + {%style%} + <meta name="viewport" content="width=device-width,initial-scale=1"> + <meta name="robots" content="index,follow"> + <link rel="icon" type="image/x-icon" href="/favicon.ico"> + <meta name="description" content="{%server_name%}: {%title%}"> +</head> +<body{%class%}> diff --git a/template/home.html b/template/home.html new file mode 100644 index 0000000..3033052 --- /dev/null +++ b/template/home.html @@ -0,0 +1,40 @@ +<!DOCTYPE html> +<html lang="en"> + <head> + <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> + <title>{%server_name%}</title> + <link title="{%server_name%}" href="/opensearch{%ac%}" rel="search" type="application/opensearchdescription+xml"> + <link rel="sitemap" type="application/xml" title="Sitemap" href="/sitemap"> + <meta name="viewport" content="width=device-width,initial-scale=1"> + <link rel="stylesheet" href="/static/style.css?v{%version%}"> + {%style%} + <meta name="robots" content="index,follow"> + <link rel="icon" type="image/x-icon" href="/favicon.ico"> + <meta name="description" content="{%server_name%}: {%server_short_description%}"> + </head> + <body class="home"> + <div id="center"> + <form method="GET" autocomplete="off" action="web"> + <div class="logo"> + <a href="/"> + <img src="{%banner%}" alt="4get"> + </a> + </div> + <div class="searchbox"> + <input type="submit" value="Search" tabindex="-1"> + <div class="wrapper"> + <input type="text" maxlength="500" name="s" placeholder="Proxy search..." required autofocus> + </div> + <div class="autocomplete"></div> + </div> + </form> + <a href="settings">Settings</a> • <a href="instances">Instances</a> • <a href="https://git.lolcat.ca/lolcat/4get_news">News</a> • <a href="api.txt">API</a> • <a href="about">About</a> • <a href="https://git.lolcat.ca/lolcat/4get">Source</a><br> + <a href="/donate"><b>Donate to the project</b></a> + <div class="subtext"> + <a href="https://4get.ca">Clearnet</a> • <a href="http://4getwebfrq5zr4sxugk6htxvawqehxtdgjrbcn2oslllcol2vepa23yd.onion">Tor</a> • <a href="https://lolcat.ca">Report a problem</a><br> + Running on <b>v{%version%}</b>!! + </div> + </div> + <script src="/static/client.js?v{%version%}"></script> + </body> +</html> diff --git a/template/images.html b/template/images.html new file mode 100644 index 0000000..f8c8d26 --- /dev/null +++ b/template/images.html @@ -0,0 +1,8 @@ + {%timetaken%} + <div id="images"> + {%images%} + </div> + {%nextpage%} + <script src="/static/client.js?v{%version%}"></script> + </body> +</html> diff --git a/template/instances.html b/template/instances.html new file mode 100644 index 0000000..06752c0 --- /dev/null +++ b/template/instances.html @@ -0,0 +1,37 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> + <title>Instance browser</title> + <link title="{%server_name%}" href="/opensearch{%ac%}" rel="search" type="application/opensearchdescription+xml"> + <link rel="stylesheet" href="/static/style.css?v{%version%}"> + {%style%} + <meta name="viewport" content="width=device-width,initial-scale=1"> + <meta name="robots" content="index,follow"> + <link rel="icon" type="image/x-icon" href="/favicon.ico"> + <meta name="description" content="{%server_name%}: Instances"> +</head> +<body class="instances"> + <h1>Instance browser</h1> + Learn how to setup your own instance here! <a href="https://git.lolcat.ca/lolcat/4get" target="_BLANK">https://git.lolcat.ca/lolcat/4get</a> + <noscript> + <div class="quote">For a better experience, whitelist javascript usage on this page.</div> + <table> + <thead> + <tr> + <th class="expand">Server</th> + </tr> + </thead> + <tbody> + {%instances_html%} + </tbody> + </table> + </noscript> + <a href="../" class="go-back">< Go back</a> + <div id="popup-bg"></div> + <div class="popup-wrapper"> + <div class="popup"></div> + </div> + <script src="static/serverping.js?v{%version%}"></script> +</body> +</html> diff --git a/template/search.html b/template/search.html new file mode 100644 index 0000000..e1c979c --- /dev/null +++ b/template/search.html @@ -0,0 +1,17 @@ + {%timetaken%} + <div id="overflow" class="web{%class%}"> + <div class="right-wrapper"> + <div class="right-right"> + {%right-right%} + </div> + <div class="right-left"> + {%right-left%} + </div> + </div> + <div class="left"> + {%left%} + </div> + </div> + <script src="/static/client.js?v{%version%}"></script> + </body> +</html> diff --git a/videos.php b/videos.php new file mode 100644 index 0000000..35f3cbb --- /dev/null +++ b/videos.php @@ -0,0 +1,231 @@ +<?php + +/* + Initialize random shit +*/ +include "data/config.php"; + +include "lib/frontend.php"; +$frontend = new frontend(); + +[$scraper, $filters] = $frontend->getscraperfilters("videos"); + +$get = $frontend->parsegetfilters($_GET, $filters); + +/* + Captcha +*/ +include "lib/bot_protection.php"; +new bot_protection($frontend, $get, $filters, "videos", true); + +$payload = [ + "timetaken" => microtime(true), + "class" => "", + "right-left" => "", + "right-right" => "", + "left" => "" +]; + +try{ + $results = $scraper->video($get); + +}catch(Exception $error){ + + $frontend->drawscrapererror($error->getMessage(), $get, "videos", $payload["timetaken"]); +} + +$categories = [ + "video" => "", + "author" => "", + "livestream" => "", + "playlist" => "", + "reel" => "" +]; + +/* + Set the main container +*/ +$main = null; + +if(count($results["video"]) !== 0){ + + $main = "video"; + +}elseif(count($results["playlist"]) !== 0){ + + $main = "playlist"; + +}elseif(count($results["livestream"]) !== 0){ + + $main = "livestream"; + +}elseif(count($results["author"]) !== 0){ + + $main = "author"; + +}elseif(count($results["reel"]) !== 0){ + + $main = "reel"; +}else{ + + // No results found! + echo + $frontend->drawerror( + "Nobody here but us chickens!", + 'Have you tried:' . + '<ul>' . + '<li>Using a different scraper</li>' . + '<li>Using fewer keywords</li>' . + '<li>Defining broader filters (Is NSFW turned off?)</li>' . + '</ul>' . + '</div>' + ); + die(); +} + +/* + Generate list of videos +*/ +foreach($categories as $name => $data){ + + foreach($results[$name] as $item){ + + $greentext = []; + + if( + isset($item["date"]) && + $item["date"] !== null + ){ + + $greentext[] = date("jS M y @ g:ia", $item["date"]); + } + + if( + isset($item["views"]) && + $item["views"] !== null + ){ + + $views = number_format($item["views"]); + + if($name != "livestream"){ + + $views .= " views"; + }else{ + + $views .= " watching"; + } + + $greentext[] = $views; + } + + if( + isset($item["followers"]) && + $item["followers"] !== null + ){ + + $greentext[] = number_format($item["followers"]) . " followers"; + } + + if( + isset($item["author"]["name"]) && + $item["author"]["name"] !== null + ){ + + $greentext[] = $item["author"]["name"]; + } + + $greentext = implode(" • ", $greentext); + + if( + isset($item["duration"]) && + $item["duration"] !== null + ){ + + $duration = $frontend->s_to_timestamp($item["duration"]); + }else{ + + $duration = null; + } + + $tabindex = $name == $main ? true : false; + + $categories[$name] .= $frontend->drawtextresult($item, $greentext, $duration, $get["s"], $tabindex); + } +} + +$payload["left"] = $categories[$main]; + +// dont re-draw the category +unset($categories[$main]); + +/* + Populate right handside +*/ + +$i = 1; +foreach($categories as $name => $value){ + + if($value == ""){ + + continue; + } + + if($i % 2 === 1){ + + $write = "right-left"; + }else{ + + $write = "right-right"; + } + + $payload[$write] .= + '<div class="answer-wrapper">' . + '<input id="answer' . $i . '" class="spoiler" type="checkbox">' . + '<div class="answer">' . + '<div class="answer-title">' . + '<a class="answer-title" href="?s=' . urlencode($get["s"]); + + switch($name){ + + case "playlist": + $payload[$write] .= + '&type=playlist"><h2>Playlists</h2></a>'; + break; + + case "livestream": + $payload[$write] .= + '&feature=live"><h2>Livestreams</h2></a>'; + break; + + case "author": + $payload[$write] .= + '&type=channel"><h2>Authors</h2></a>'; + break; + + case "reel": + $payload[$write] .= + '&duration=short"><h2>Reels</h2></a>'; + break; + } + + $payload[$write] .= + '</div>' . + $categories[$name] . + '</div>' . + '<label class="spoiler-button" for="answer' . $i . '"></label></div>'; + + $i++; +} + +if($i !== 1){ + + $payload["class"] = " has-answer"; +} + +if($results["npt"] !== null){ + + $payload["left"] .= + '<a href="' . $frontend->htmlnextpage($get, $results["npt"], "videos") . '" class="nextpage">Next page ></a>'; +} + +echo $frontend->load("search.html", $payload); @@ -0,0 +1,514 @@ +<?php + +/* + Initialize random shit +*/ +include "data/config.php"; + +include "lib/frontend.php"; +$frontend = new frontend(); + +[$scraper, $filters] = $frontend->getscraperfilters("web"); + +$get = $frontend->parsegetfilters($_GET, $filters); + +/* + Captcha +*/ +include "lib/bot_protection.php"; +new bot_protection($frontend, $get, $filters, "web", true); + +$payload = [ + "timetaken" => microtime(true), + "class" => "", + "right-left" => "", + "right-right" => "", + "left" => "" +]; + +try{ + $results = $scraper->web($get); + +}catch(Exception $error){ + + $frontend->drawscrapererror($error->getMessage(), $get, "web", $payload["timetaken"]); +} + +/* + Prepend Oracle output, if applicable +*/ +include("oracles/encoder.php"); +include("oracles/calc.php"); +include("oracles/time.php"); +include("oracles/numerics.php"); +$oracles = [new calculator(), new encoder(), new time(), new numerics()]; +$fortune = ""; +foreach ($oracles as $oracle) { + if ($oracle->check_query($_GET["s"])) { + $resp = $oracle->generate_response($_GET["s"]); + if ($resp != "") { + $fortune .= "<div class=\"infobox\">"; + foreach ($resp as $title => $r) { + if ($title) { + $fortune .= "<h3>".htmlspecialchars($title)."</h3><div class=\"code\">".htmlspecialchars($r)."</div>"; + } + else { + $fortune .= "<i>".$r."</i><br>"; + } + } + $fortune .= "<small>Answer provided by oracle: ".$oracle->info["name"]."</small></div>"; + } + break; + } +} +$payload["left"] = $fortune; + +$answerlen = 0; + +/* + Spelling checker +*/ +if($results["spelling"]["type"] != "no_correction"){ + + switch($results["spelling"]["type"]){ + + case "including": + $type = "Including results for"; + break; + + case "not_many": + $type = "Not many results contains"; + break; + } + + $payload["left"] .= + '<div class="infobox">' . + $type . ' <b>' . htmlspecialchars($results["spelling"]["using"]) . '</b>.<br>' . + 'Did you mean <a href="?s=' . + urlencode($results["spelling"]["correction"]) . + '&' . + $frontend->buildquery($get, true) . + '&spellcheck=no">' . + htmlspecialchars($results["spelling"]["correction"]) . + '</a>?' . + '</div>'; +} + +/* + Populate links +*/ +if(count($results["web"]) === 0){ + + $payload["left"] .= + '<div class="infobox">' . + "<h1>Nobody here but us chickens!</h1>" . + 'Have you tried:' . + '<ul>' . + '<li>Using a different scraper</li>' . + '<li>Using fewer keywords</li>' . + '<li>Defining broader filters (Is NSFW turned off?)</li>' . + '</ul>' . + '</div>'; +} + +foreach($results["web"] as $site){ + + $n = null; + + if($site["date"] !== null){ + + $date = date("jS M y @ g:ia", $site["date"]); + }else{ + + $date = null; + } + + $payload["left"] .= $frontend->drawtextresult($site, $date, $n, $get["s"]); +} + +$right = []; + +/* + Generate images +*/ +if(count($results["image"]) !== 0){ + + $answerlen++; + $right["image"] = + '<div class="answer-wrapper">' . + '<input id="answer' . $answerlen . '" class="spoiler" type="checkbox">' . + '<div class="answer">' . + '<div class="answer-title">' . + '<a class="answer-title" href="/images?s=' . urlencode($get["s"]) . '"><h2>Images</h2></a>' . + '</div>' . + '<div class="images">'; + + foreach($results["image"] as $image){ + + $right["image"] .= + '<a class="image" href="' . htmlspecialchars($image["url"]) . '" rel="noreferrer nofollow" title="' . htmlspecialchars($image["title"]) . '" data-json="' . htmlspecialchars(json_encode($image["source"])) . '" tabindex="-1">' . + '<img src="' . $frontend->htmlimage($image["source"][count($image["source"]) - 1]["url"], "square") . '" alt="thumb">'; + + if( + $image["source"][0]["width"] !== null && + $image["source"][0]["height"] !== null + ){ + + $right["image"] .= '<div class="duration">' . $image["source"][0]["width"] . 'x' . $image["source"][0]["height"] . '</div>'; + } + + $right["image"] .= '</a>'; + } + + $right["image"] .= + '</div></div>' . + '<label class="spoiler-button" for="answer' . $answerlen . '"></label></div>'; +} + +/* + Generate videos +*/ +if(count($results["video"]) !== 0){ + + $answerlen++; + $right["video"] = + '<div class="answer-wrapper">' . + '<input id="answer' . $answerlen . '" class="spoiler" type="checkbox">' . + '<div class="answer">' . + '<div class="answer-title">' . + '<a class="answer-title" href="/videos?s=' . urlencode($get["s"]) . '"><h2>Videos</h2></a>' . + '</div>'; + + foreach($results["video"] as $video){ + + if($video["views"] !== null){ + + $greentext = number_format($video["views"]) . " views"; + }else{ + + $greentext = null; + } + + if($video["date"] !== null){ + + if($greentext !== null){ + + $greentext .= " • "; + } + + $greentext .= date("jS M y @ g:ia", $video["date"]); + } + + if($video["duration"] !== null){ + + if($video["duration"] == "_LIVE"){ + + $duration = 'LIVE'; + }else{ + + $duration = $frontend->s_to_timestamp($video["duration"]); + } + }else{ + + $duration = null; + } + + $right["video"] .= $frontend->drawtextresult($video, $greentext, $duration, $get["s"], false); + } + + $right["video"] .= + '</div>' . + '<label class="spoiler-button" for="answer' . $answerlen . '"></label></div>'; +} + +/* + Generate news +*/ +if(count($results["news"]) !== 0){ + + $answerlen++; + $right["news"] = + '<div class="answer-wrapper">' . + '<input id="answer' . $answerlen . '" class="spoiler" type="checkbox">' . + '<div class="answer">' . + '<div class="answer-title">' . + '<a class="answer-title" href="/news?s=' . urlencode($get["s"]) . '"><h2>News</h2></a>' . + '</div>'; + + foreach($results["news"] as $news){ + + if($news["date"] !== null){ + + $greentext = date("jS M y @ g:ia", $news["date"]); + }else{ + + $greentext = null; + } + + $right["news"] .= $frontend->drawtextresult($news, $greentext, null, $get["s"], false); + } + + $right["news"] .= + '</div>' . + '<label class="spoiler-button" for="answer' . $answerlen . '"></label></div>'; +} + +/* + Generate answers +*/ +if(count($results["answer"]) !== 0){ + + $right["answer"] = ""; + + foreach($results["answer"] as $answer){ + + $answerlen++; + $right["answer"] .= + '<div class="answer-wrapper">' . + '<input id="answer' . $answerlen . '" class="spoiler" type="checkbox">' . + '<div class="answer"><div class="wiki-head">'; + + if(!empty($answer["title"])){ + + $right["answer"] .= + '<div class="answer-title">'; + + if(!empty($answer["url"])){ + + $right["answer"] .= '<a class="answer-title" href="' . htmlspecialchars($answer["url"]) . '" rel="noreferrer nofollow">'; + } + + $right["answer"] .= '<h1>' . htmlspecialchars($answer["title"]) . '</h1>'; + + if(!empty($answer["url"])){ + + $right["answer"] .= '</a>'; + } + + + $right["answer"] .= '</div>'; + } + + if(!empty($answer["url"])){ + + $right["answer"] .= + $frontend->drawlink($answer["url"]); + } + + $right["answer"] .= '<div class="description">'; + + if(!empty($answer["thumb"])){ + + $right["answer"] .= + '<a href="' . htmlspecialchars($answer["thumb"]) . '" rel="noreferrer nofollow" class="photo">' . + '<img src="' . $frontend->htmlimage($answer["thumb"], "cover") . '" alt="thumb" class="openimg">' . + '</a>'; + } + + foreach($answer["description"] as $description){ + + switch($description["type"]){ + + case "text": + $right["answer"] .= $frontend->highlighttext($get["s"], $description["value"]); + break; + + case "title": + $right["answer"] .= + '<h2>' . + htmlspecialchars($description["value"]) . + '</h2>'; + break; + + case "italic": + $right["answer"] .= + '<i>' . + $frontend->highlighttext($get["s"], $description["value"]) . + '</i>'; + break; + + case "quote": + $right["answer"] .= + '<div class="quote">' . + $frontend->highlighttext($get["s"], $description["value"]) . + '</div>'; + break; + + case "code": + $right["answer"] .= + '<div class="code" tabindex="-1">' . + $frontend->highlightcode($description["value"], true) . + '</div>'; + break; + + case "inline_code": + $right["answer"] .= + '<div class="code-inline">' . + htmlspecialchars($description["value"]) . + '</div>'; + break; + + case "link": + $right["answer"] .= + '<a href="' . htmlspecialchars($description["url"]) . '" rel="noreferrer nofollow" class="underline" tabindex="-1">' . htmlspecialchars($description["value"]) . '</a>'; + break; + + case "image": + $right["answer"] .= + '<a href="' . htmlspecialchars($description["url"]) . '" rel="noreferrer nofollow" tabindex="-1"><img src="' . $frontend->htmlimage($description["url"], "thumb") . '" alt="image" class="fullimg openimg"></a>'; + break; + + case "audio": + $right["answer"] .= + '<audio src="/audio/linear?s=' . urlencode($description["url"]) . '" controls><a href="/audio/linear?s=' . urlencode($description["url"]) . '">Listen to the pronunciation audio</a></audio>'; + break; + } + } + + $right["answer"] .= '</div>'; + + if(count($answer["table"]) !== 0){ + + $right["answer"] .= '<table>'; + + foreach($answer["table"] as $info => $value){ + + $right["answer"] .= + '<tr>' . + '<td>' . $info . '</td>' . + '<td>' . $value . '</td>' . + '</tr>'; + } + + $right["answer"] .= '</table>'; + } + + if(count($answer["sublink"]) !== 0){ + + $right["answer"] .= '<div class="socials">'; + $icons = glob("static/icon/*"); + + foreach($answer["sublink"] as $website => $url){ + + $flag = false; + $icon = str_replace(" ", "", strtolower($website)); + + foreach($icons as $path){ + + if(pathinfo($path, PATHINFO_FILENAME) == $icon){ + + $flag = true; + break; + } + } + + if($flag === false){ + + $icon = "website"; + } + + $right["answer"] .= + '<a href="' . htmlspecialchars($url) . '" rel="noreferrer nofollow" tabindex="-1">' . + '<div class="center">' . + '<img src="/static/icon/' . $icon . '.png" alt="icon">' . + '<div class="title">' . $website . '</div>' . + '</div>' . + '</a>'; + } + + $right["answer"] .= '</div>'; + } + + $right["answer"] .= + '</div></div>' . + '<label class="spoiler-button" for="answer' . $answerlen . '"></label></div>'; + } +} + +/* + Add right containers +*/ +if(isset($right["answer"])){ + + if(count($right) >= 2){ + + $payload["right-right"] = $right["answer"]; + unset($right["answer"]); + } +} + +$c = 0; +foreach($right as $snippet){ + + if($c % 2 === 0){ + + $payload["right-left"] .= $snippet; + }else{ + + $payload["right-right"] .= $snippet; + } + + $c++; +} + +if($c !== 0){ + + $payload["class"] = " has-answer"; +} + +/* + Generate related searches +*/ +$c = count($results["related"]); + +if($c !== 0){ + $payload["left"] .= '<h3>Related searches</h3><table class="related">'; + + $opentr = false; + + for($i=0; $i<$c; $i++){ + + if(($i % 2) === 0){ + + $opentr = true; + $payload["left"] .= '<tr>'; + }else{ + + $opentr = false; + } + + $payload["left"] .= + '<td>' . + '<a href="/web?s=' . + urlencode($results["related"][$i]) . "&" . + $frontend->buildquery($get, true) . + '">' . + htmlspecialchars($results["related"][$i]) . + '</a>'; + + $payload["left"] .= '</td>'; + + if($opentr === false){ + + $payload["left"] .= '</tr>'; + } + } + + if($opentr === true){ + + $payload["left"] .= '<td></td></tr>'; + } + + $payload["left"] .= '</table>'; +} + +/* + Load next page +*/ +if($results["npt"] !== null){ + + $payload["left"] .= + '<a href="' . $frontend->htmlnextpage($get, $results["npt"], "web") . '" class="nextpage">Next page ></a>'; +} + +echo $frontend->load("search.html", $payload); |