From cdf958d29333d448f4521f4d2faa2592b58e9b27 Mon Sep 17 00:00:00 2001 From: lolcat Date: Sun, 10 Aug 2025 21:55:15 -0400 Subject: fix wikipedia crash --- .dockerignore | 1 + .gitignore | 28 + Dockerfile | 17 + README.md | 61 + about.php | 39 + ami4get.php | 27 + api.txt | 357 ++++ api/index.php | 10 + api/v1/ac.php | 243 +++ api/v1/images.php | 39 + api/v1/index.php | 10 + api/v1/music.php | 39 + api/v1/news.php | 39 + api/v1/videos.php | 39 + api/v1/web.php | 52 + audio/linear.php | 20 + audio/sc.php | 224 +++ audio/seekable.php | 20 + audio/spotify.php | 214 +++ banner/4get-default.png | Bin 0 -> 21969 bytes captcha.php | 203 +++ data/config.php | 178 ++ data/fonts/captcha.ttf | Bin 0 -> 125972 bytes data/proxies/.gitignore | 3 + data/proxies/onion.txt | 13 + docker-compose.yaml | 20 + docker/apache/http/conf.d/ssl.conf | 1 + docker/apache/http/httpd.conf | 97 ++ docker/apache/https/conf.d/ssl.conf | 19 + docker/apache/https/httpd.conf | 102 ++ docker/docker-entrypoint.sh | 34 + docker/gen_config.php | 90 + docker/tor/Dockerfile | 18 + docker/tor/torrc | 1 + docs/apache2-example.md | 195 +++ docs/apache2.md | 216 +++ docs/caddy.md | 58 + docs/configure.md | 93 + docs/docker.md | 152 ++ docs/docker_tor.md | 174 ++ docs/nginx.md | 194 +++ docs/tor.md | 16 + donate.php | 39 + favicon.ico | Bin 0 -> 193 bytes favicon.php | 368 ++++ icons/lolcat.ca.png | Bin 0 -> 753 bytes images.php | 77 + index.php | 15 + instances.php | 55 + lib/anubis.php | 100 ++ lib/backend.php | 178 ++ lib/bingcache-todo-fix.php | 144 ++ lib/bot_protection.php | 281 ++++ lib/curlproxy.php | 660 ++++++++ lib/favicon404.png | Bin 0 -> 744 bytes lib/frontend.php | 1356 +++++++++++++++ lib/fuckhtml.php | 622 +++++++ lib/img404.png | Bin 0 -> 216 bytes lib/type-todo.php | 132 ++ license.txt | 661 ++++++++ music.php | 222 +++ news.php | 86 + opensearch.php | 42 + oracles/base.php | 36 + oracles/calc.php | 165 ++ oracles/encoder.php | 40 + oracles/numerics.php | 54 + oracles/time.php | 45 + proxy.php | 180 ++ robots.txt | 28 + scraper/baidu.php | 2229 ++++++++++++++++++++++++ scraper/brave.php | 1860 ++++++++++++++++++++ scraper/cara.php | 847 ++++++++++ scraper/coccoc.php | 672 ++++++++ scraper/crowdview.php | 145 ++ scraper/curlie.php | 309 ++++ scraper/ddg.php | 2246 +++++++++++++++++++++++++ scraper/facebook.php | 820 +++++++++ scraper/fivehpx.php | 262 +++ scraper/flickr.php | 415 +++++ scraper/ftm.php | 161 ++ scraper/ghostery.php | 320 ++++ scraper/google.php | 2989 +++++++++++++++++++++++++++++++++ scraper/google_cse.php | 1054 ++++++++++++ scraper/greppr.php | 435 +++++ scraper/imgur.php | 282 ++++ scraper/marginalia.php | 580 +++++++ scraper/mojeek.php | 1194 +++++++++++++ scraper/mwmbl.php | 236 +++ scraper/pinterest.php | 439 +++++ scraper/qwant.php | 993 +++++++++++ scraper/sc.php | 512 ++++++ scraper/sepiasearch.php | 541 ++++++ scraper/solofield.php | 668 ++++++++ scraper/spotify.php | 726 ++++++++ scraper/startpage.php | 1584 +++++++++++++++++ scraper/vimeo.php | 754 +++++++++ scraper/vsco.php | 257 +++ scraper/wiby.php | 246 +++ scraper/yandex.php | 1248 ++++++++++++++ scraper/yep.php | 741 ++++++++ scraper/yt.php | 1727 +++++++++++++++++++ settings.php | 601 +++++++ sitemap.php | 35 + static/404.png | Bin 0 -> 216 bytes static/client.js | 985 +++++++++++ static/icon/amazon.png | Bin 0 -> 1223 bytes static/icon/appstore.png | Bin 0 -> 1763 bytes static/icon/call.png | Bin 0 -> 2155 bytes static/icon/directions.png | Bin 0 -> 1673 bytes static/icon/facebook.png | Bin 0 -> 555 bytes static/icon/gamespot.png | Bin 0 -> 1663 bytes static/icon/github.png | Bin 0 -> 508 bytes static/icon/googleplay.png | Bin 0 -> 1046 bytes static/icon/imdb.png | Bin 0 -> 1259 bytes static/icon/instagram.png | Bin 0 -> 1804 bytes static/icon/itunes.png | Bin 0 -> 1721 bytes static/icon/microsoft.png | Bin 0 -> 1218 bytes static/icon/quora.png | Bin 0 -> 835 bytes static/icon/reddit.png | Bin 0 -> 1086 bytes static/icon/rottentomatoes.png | Bin 0 -> 468 bytes static/icon/sciencedirect.png | Bin 0 -> 354 bytes static/icon/soundcloud.png | Bin 0 -> 592 bytes static/icon/spotify.png | Bin 0 -> 689 bytes static/icon/steam.png | Bin 0 -> 622 bytes static/icon/twitter.png | Bin 0 -> 698 bytes static/icon/w3html.png | Bin 0 -> 1000 bytes static/icon/website.png | Bin 0 -> 1792 bytes static/icon/wikipedia.png | Bin 0 -> 1068 bytes static/icon/youtube.png | Bin 0 -> 1316 bytes static/misc/christmas-dark-bg.png | Bin 0 -> 115320 bytes static/misc/christmas-hat.png | Bin 0 -> 13077 bytes static/misc/christmas-white-bg.png | Bin 0 -> 109889 bytes static/misc/snow.png | Bin 0 -> 192815 bytes static/serverping.js | 473 ++++++ static/style.css | 1384 +++++++++++++++ static/themes/Catppuccin Latte.css | 20 + static/themes/Catppuccin Mocha.css | 20 + static/themes/Cream.css | 31 + static/themes/Dark Christmas.css | 95 ++ static/themes/Gore's shitty theme.css | 322 ++++ static/themes/Kuuro.css | 17 + static/themes/White Christmas.css | 94 ++ static/themes/Wine.css | 40 + static/themes/gentoo.css | 20 + template/about.html | 77 + template/donate.html | 20 + template/header.html | 34 + template/header_nofilters.html | 14 + template/home.html | 40 + template/images.html | 8 + template/instances.html | 37 + template/search.html | 17 + videos.php | 231 +++ web.php | 514 ++++++ 155 files changed, 41563 insertions(+) create mode 100644 .dockerignore create mode 100644 .gitignore create mode 100644 Dockerfile create mode 100644 README.md create mode 100644 about.php create mode 100644 ami4get.php create mode 100644 api.txt create mode 100644 api/index.php create mode 100644 api/v1/ac.php create mode 100644 api/v1/images.php create mode 100644 api/v1/index.php create mode 100644 api/v1/music.php create mode 100644 api/v1/news.php create mode 100644 api/v1/videos.php create mode 100644 api/v1/web.php create mode 100644 audio/linear.php create mode 100644 audio/sc.php create mode 100644 audio/seekable.php create mode 100644 audio/spotify.php create mode 100644 banner/4get-default.png create mode 100755 captcha.php create mode 100644 data/config.php create mode 100644 data/fonts/captcha.ttf create mode 100644 data/proxies/.gitignore create mode 100644 data/proxies/onion.txt create mode 100644 docker-compose.yaml create mode 100644 docker/apache/http/conf.d/ssl.conf create mode 100644 docker/apache/http/httpd.conf create mode 100644 docker/apache/https/conf.d/ssl.conf create mode 100644 docker/apache/https/httpd.conf create mode 100755 docker/docker-entrypoint.sh create mode 100644 docker/gen_config.php create mode 100644 docker/tor/Dockerfile create mode 100644 docker/tor/torrc create mode 100644 docs/apache2-example.md create mode 100644 docs/apache2.md create mode 100644 docs/caddy.md create mode 100644 docs/configure.md create mode 100644 docs/docker.md create mode 100644 docs/docker_tor.md create mode 100644 docs/nginx.md create mode 100644 docs/tor.md create mode 100644 donate.php create mode 100644 favicon.ico create mode 100644 favicon.php create mode 100644 icons/lolcat.ca.png create mode 100644 images.php create mode 100644 index.php create mode 100644 instances.php create mode 100644 lib/anubis.php create mode 100644 lib/backend.php create mode 100644 lib/bingcache-todo-fix.php create mode 100644 lib/bot_protection.php create mode 100644 lib/curlproxy.php create mode 100644 lib/favicon404.png create mode 100644 lib/frontend.php create mode 100644 lib/fuckhtml.php create mode 100644 lib/img404.png create mode 100644 lib/type-todo.php create mode 100644 license.txt create mode 100644 music.php create mode 100644 news.php create mode 100644 opensearch.php create mode 100644 oracles/base.php create mode 100644 oracles/calc.php create mode 100644 oracles/encoder.php create mode 100644 oracles/numerics.php create mode 100644 oracles/time.php create mode 100644 proxy.php create mode 100644 robots.txt create mode 100644 scraper/baidu.php create mode 100644 scraper/brave.php create mode 100644 scraper/cara.php create mode 100644 scraper/coccoc.php create mode 100644 scraper/crowdview.php create mode 100644 scraper/curlie.php create mode 100644 scraper/ddg.php create mode 100644 scraper/facebook.php create mode 100644 scraper/fivehpx.php create mode 100644 scraper/flickr.php create mode 100644 scraper/ftm.php create mode 100644 scraper/ghostery.php create mode 100644 scraper/google.php create mode 100644 scraper/google_cse.php create mode 100644 scraper/greppr.php create mode 100644 scraper/imgur.php create mode 100644 scraper/marginalia.php create mode 100644 scraper/mojeek.php create mode 100644 scraper/mwmbl.php create mode 100644 scraper/pinterest.php create mode 100644 scraper/qwant.php create mode 100644 scraper/sc.php create mode 100644 scraper/sepiasearch.php create mode 100644 scraper/solofield.php create mode 100644 scraper/spotify.php create mode 100644 scraper/startpage.php create mode 100644 scraper/vimeo.php create mode 100644 scraper/vsco.php create mode 100644 scraper/wiby.php create mode 100644 scraper/yandex.php create mode 100644 scraper/yep.php create mode 100644 scraper/yt.php create mode 100644 settings.php create mode 100644 sitemap.php create mode 100644 static/404.png create mode 100644 static/client.js create mode 100644 static/icon/amazon.png create mode 100644 static/icon/appstore.png create mode 100644 static/icon/call.png create mode 100644 static/icon/directions.png create mode 100644 static/icon/facebook.png create mode 100644 static/icon/gamespot.png create mode 100644 static/icon/github.png create mode 100644 static/icon/googleplay.png create mode 100644 static/icon/imdb.png create mode 100644 static/icon/instagram.png create mode 100644 static/icon/itunes.png create mode 100644 static/icon/microsoft.png create mode 100644 static/icon/quora.png create mode 100644 static/icon/reddit.png create mode 100644 static/icon/rottentomatoes.png create mode 100644 static/icon/sciencedirect.png create mode 100644 static/icon/soundcloud.png create mode 100644 static/icon/spotify.png create mode 100644 static/icon/steam.png create mode 100644 static/icon/twitter.png create mode 100644 static/icon/w3html.png create mode 100644 static/icon/website.png create mode 100644 static/icon/wikipedia.png create mode 100644 static/icon/youtube.png create mode 100644 static/misc/christmas-dark-bg.png create mode 100644 static/misc/christmas-hat.png create mode 100644 static/misc/christmas-white-bg.png create mode 100644 static/misc/snow.png create mode 100644 static/serverping.js create mode 100644 static/style.css create mode 100644 static/themes/Catppuccin Latte.css create mode 100644 static/themes/Catppuccin Mocha.css create mode 100644 static/themes/Cream.css create mode 100644 static/themes/Dark Christmas.css create mode 100644 static/themes/Gore's shitty theme.css create mode 100644 static/themes/Kuuro.css create mode 100644 static/themes/White Christmas.css create mode 100644 static/themes/Wine.css create mode 100644 static/themes/gentoo.css create mode 100644 template/about.html create mode 100644 template/donate.html create mode 100644 template/header.html create mode 100644 template/header_nofilters.html create mode 100644 template/home.html create mode 100644 template/images.html create mode 100644 template/instances.html create mode 100644 template/search.html create mode 100644 videos.php create mode 100644 web.php 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 @@ +## Donate to the project here! + +# 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 documentation index. I recommend following the apache2 guide. + +## Contact +Shit breaks all the time but I repair it all the time too. Email me here: will (at) lolcat.ca 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 @@ +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 @@ + "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 + ] +); diff --git a/api.txt b/api.txt new file mode 100644 index 0000000..4d2626b --- /dev/null +++ b/api.txt @@ -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 + 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/?s= + + ++ /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 + + 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 @@ + "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 @@ +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 @@ + "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 @@ + "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 @@ + "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 @@ + "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 @@ + "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 @@ + "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 @@ +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 @@ +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; $iproxy->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 @@ +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 @@ +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 new file mode 100644 index 0000000..c075175 Binary files /dev/null and b/banner/4get-default.png differ diff --git a/captcha.php b/captcha.php new file mode 100755 index 0000000..286a277 --- /dev/null +++ b/captcha.php @@ -0,0 +1,203 @@ + "#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; $iannotateImage( + $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 @@ + 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 new file mode 100644 index 0000000..13f5dc7 Binary files /dev/null and b/data/fonts/captcha.ttf differ 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: +# :
::: +# +# 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 + + + 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 + + +# deny access to private resources + + Require all denied + + Require all denied + + + +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 + + +User apache +Group apache + + + + + + AllowOverride none + Require all denied + + + + + + + DirectoryIndex index.html + + + + Require all denied + + + + + + RequestHeader unset Proxy early + + + + TypesConfig /etc/apache2/mime.types + AddType application/x-compress .Z + AddType application/x-gzip .gz .tgz + + + + MIMEMagicFile /etc/apache2/magic + + +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 + + + SSLEngine on + SSLCertificateFile /etc/4get/certs/fullchain.pem + SSLCertificateKeyFile /etc/4get/certs/privkey.pem + + + + 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 + + +# deny access to private resources + + Require all denied + + Require all denied + + + +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 + + +User apache +Group apache + + + + + + AllowOverride none + Require all denied + + + + + + + DirectoryIndex index.html + + + + Require all denied + + + + + + RequestHeader unset Proxy early + + + + TypesConfig /etc/apache2/mime.types + AddType application/x-compress .Z + AddType application/x-gzip .gz .tgz + + + + MIMEMagicFile /etc/apache2/magic + + +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 @@ + 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 = " $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? go here.. + +```xml + + 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 + + + + 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 + + + Options -MultiViews + AllowOverride All + Require all granted + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^([^\.]+)$ $1.php [NC,L] + + + # deny access to private resources + + Order Deny,allow + Deny from all + + + + + 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 + + + + 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 + + + Options -MultiViews + AllowOverride All + Require all granted + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^([^\.]+)$ $1.php [NC,L] + + + + + 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 + + + + 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 + + + Options -MultiViews + AllowOverride All + Require all granted + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^([^\.]+)$ $1.php [NC,L] + + + + + 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 + + + + 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 + +``` 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 + + # no domain = go to 4get.ca + RedirectMatch 301 ^(.*)$ https://4get.ca$1 + +``` + +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 + + ServerName lolcat.ca + RedirectMatch 301 ^(.*)$ https://lolcat.ca$1 + +``` + +3. Subdomains won't be matched by the above rule, so I recommend you also add them to be more explicit: +```xml + + ServerName www.lolcat.ca + RedirectMatch 301 ^(.*)$ https://lolcat.ca$1 + +``` + +... 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 + + # 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 + + Order Deny,allow + Deny from all + + +``` +To make the above snippet work, please refer to our tor site guide. + +## 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 + + 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 + +``` + +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 + + 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 + + + Options -MultiViews + AllowOverride All + Require all granted + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME} !-d + RewriteCond %{REQUEST_FILENAME} !-f + RewriteRule ^([^\.]+)$ $1.php [NC,L] + + + # deny access to private resources + + Order Deny,allow + Deny from all + + +``` + +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 check out my real-world config file I use on 4get.ca. + +## 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 configure 4get 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 + + RewriteEngine On + RewriteCond %{REQUEST_FILENAME}.php -f + RewriteRule (.*) $1.php [L] + Options Indexes FollowSymLinks + AllowOverride All + Require all granted + +``` 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 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 @@ +

Installation of 4get in NGINX

+ +
+ +> NOTE: As the previous version stated, it is better to follow the Apache2 guide instead of the Nginx one. + +> NOTE: This is going to guess that you're using either a Arch-based system or a Debian-based system, although you can still follow it with minor issues. + +
+ +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 this 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` + +
+ +> 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]. + +
+ +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. + +

Encryption setup

+ +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. + +

Tor Setup

+ +
+ +> IMPORTANT: Tor onion addresses are very long compared to traditional domains, so, Before doing anything, edit `nginx.conf` and increase server_names_hash_bucket_size to your needs. + +
+ +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 the Tor guide to setup your onion site. + +

Other important things

+ +1. Configuration guide: Things to do after setup. +2. Apache2 guide: Fallback to this if you couldn't get something to work, or you don't know something. + +

Known issues

+ +1. https://git.lolcat.ca/lolcat/4get/issues + +[^1]: lolcat/4get#40, If having issues with `libsodium`, or `php-apcu`. +[^2]: git.nadeko.net 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 apache2 guide 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 @@ +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 new file mode 100644 index 0000000..a54beb0 Binary files /dev/null and b/favicon.ico differ diff --git a/favicon.php b/favicon.php new file mode 100644 index 0000000..0694a12 --- /dev/null +++ b/favicon.php @@ -0,0 +1,368 @@ +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"] = ''; + + // 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 $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 new file mode 100644 index 0000000..bf47a44 Binary files /dev/null and b/icons/lolcat.ca.png differ diff --git a/images.php b/images.php new file mode 100644 index 0000000..99fc9d6 --- /dev/null +++ b/images.php @@ -0,0 +1,77 @@ +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"] = + '
' . + "

Nobody here but us chickens!

" . + 'Have you tried:' . + '
    ' . + '
  • Using a different scraper
  • ' . + '
  • Using fewer keywords
  • ' . + '
  • Defining broader filters (Is NSFW turned off?)
  • ' . + '
' . + '
'; +} + +foreach($results["image"] as $image){ + + $payload["images"] .= + ''; +} + +if($results["npt"] !== null){ + + $payload["nextpage"] = + 'Next page >'; +} + +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 @@ +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 @@ + $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 .= '' . htmlspecialchars($instance) . ''; +} + +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 @@ +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 @@ +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 @@ + + +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( + '/
/', + $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 @@ +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; $irandomchars(); + + 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 = "
You were kicked out of Mensa. Please try again.
"; + } + } + + $key = "c" . apcu_inc("captcha_gen", 1) . "." . $this->randomchars(); + + $payload = [ + "timetaken" => microtime(true), + "class" => "", + "right-left" => "", + "right-right" => "", + "left" => + '
' . + '

IQ test

' . + 'IQ test has been enabled due to bot abuse on the network.
' . + 'Solving this IQ test will let you make 100 searches today. I will add an invite system to bypass this soon...' . + $error . + '
' . + '
' . + '
' . + 'Captcha image' . + '
' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '' . + '
' . + '
' . + '
' . + '' . + '' . + '
' . + '
' + ]; + + $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 @@ +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 new file mode 100644 index 0000000..fa8f4d1 Binary files /dev/null and b/lib/favicon404.png differ 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 @@ +'; + }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"] = '
Took ' . number_format(microtime(true) - $replacements["timetaken"], 2) . 's
'; + } + + $handle = fopen("template/{$template}", "r"); + $data = fread($handle, filesize("template/{$template}")); + fclose($handle); + + $data = explode("\n", $data); + $html = ""; + + for($i=0; $i $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 contact the administrator.' + ); + 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" => + '
' . + '

' . htmlspecialchars($title) . '

' . + $error . + '
' + ]); + die(); + } + + public function drawscrapererror($error, $get, $target, $timetaken = null){ + + if($timetaken === null){ + + $timetaken = microtime(true); + } + + $this->drawerror( + "Shit", + 'This scraper returned an error:' . + '
' . htmlspecialchars($error) . '
' . + 'Things you can try:' . + '
' . + 'If the error persists, please contact the administrator.', + $timetaken + ); + } + + public function drawtextresult($site, $greentext = null, $duration = null, $keywords, $tabindex = true, $customhtml = null){ + + $payload = + '
'; + + // add favicon, link and archive links + $payload .= $this->drawlink($site["url"]); + + /* + Draw title + description + filetype + */ + $payload .= + '' . + 'thumb'; + + if($duration !== null){ + + $payload .= + '
' . + htmlspecialchars($duration) . + '
'; + } + + $payload .= + '
'; + } + + $payload .= + '
'; + + if( + isset($site["type"]) && + $site["type"] != "web" + ){ + + $payload .= '
' . strtoupper($site["type"]) . '
'; + } + + $payload .= + $this->highlighttext($keywords, $site["title"]) . + '
'; + + if($greentext !== null){ + + $payload .= + '
' . + htmlspecialchars($greentext) . + '
'; + } + + if($site["description"] !== null){ + + $payload .= + '
' . + $this->highlighttext($keywords, $site["description"]) . + '
'; + } + + $payload .= $customhtml; + + $payload .= '
'; + + /* + Sublinks + */ + if( + isset($site["sublink"]) && + !empty($site["sublink"]) + ){ + + usort($site["sublink"], function($a, $b){ + + return strlen($a["description"]) > strlen($b["description"]); + }); + + $payload .= + ''; + } + + if( + isset($site["table"]) && + !empty($site["table"]) + ){ + + $payload .= ''; + + foreach($site["table"] as $title => $value){ + + $payload .= + '' . + '' . + '' . + ''; + } + + $payload .= '
' . htmlspecialchars($title) . '' . htmlspecialchars($value) . '
'; + } + + return $payload . '
'; + } + + 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, + '${0}', + $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( + '/]+>/', + "", + str_replace( + [ + "
", + " ", + "
",
+							"
", + "
" + ], + [ + "\n", + " ", + "", + "", + "" + ], + explode( + "<?php", + highlight_string("', '', $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 = + '
' . + '' . + '
'; + + /* + 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' . + '' . $archives[$i][0] . $archives[$i][1] . '' . + $archives[$i] . + ''; + } + } + } + + $payload .= + 'arArchive.org' . + 'arArchive.is' . + 'ghGhostarchive' . + 'arArquivo.pt' . + 'biBing cache' . + 'meMegalodon' . + '
'; + + /* + 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 .= + '' . + htmlspecialchars(urldecode($parts[$i])) . + ''; + + if($i !== $c - 1){ + + $payload .= ''; + } + } + + return $payload . '
'; + } + + 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 .= '' . ucfirst($type) . ''; + } + + 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 = + '
' . + '
' . htmlspecialchars($filter_values["display"]) . '
'; + + if(is_array($filter_values["option"])){ + + $tmp .= ''; + }else{ + + switch($filter_values["option"]){ + + case "_DATE": + $tmp .= ' $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 @@ +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 +
... + */ + + 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 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 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 "!" . $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 $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. + 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. + + + Copyright (C) + + 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 . + +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 +. diff --git a/music.php b/music.php new file mode 100644 index 0000000..c49fc08 --- /dev/null +++ b/music.php @@ -0,0 +1,222 @@ +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:' . + '
    ' . + '
  • Using a different scraper
  • ' . + '
  • Using fewer keywords
  • ' . + '
  • Defining broader filters (Is NSFW turned off?)
  • ' . + '
' . + '
' + ); + 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 = + '
' + ); + 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] .= + '
' . + '' . + '
' . + '
' . + '

Playlists

'; + break; + + case "livestream": + $payload[$write] .= + '&feature=live">

Livestreams

'; + break; + + case "author": + $payload[$write] .= + '&type=channel">

Authors

'; + break; + + case "reel": + $payload[$write] .= + '&duration=short">

Reels

'; + break; + } + + $payload[$write] .= + '
' . + $categories[$name] . + '
' . + '
'; + + $i++; +} + +if($i !== 1){ + + $payload["class"] = " has-answer"; +} + +if($results["npt"] !== null){ + + $payload["left"] .= + 'Next page >'; +} + +echo $frontend->load("search.html", $payload); diff --git a/web.php b/web.php new file mode 100644 index 0000000..a1588fc --- /dev/null +++ b/web.php @@ -0,0 +1,514 @@ +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 .= "
"; + foreach ($resp as $title => $r) { + if ($title) { + $fortune .= "

".htmlspecialchars($title)."

".htmlspecialchars($r)."
"; + } + else { + $fortune .= "".$r."
"; + } + } + $fortune .= "Answer provided by oracle: ".$oracle->info["name"]."
"; + } + 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"] .= + '
' . + $type . ' ' . htmlspecialchars($results["spelling"]["using"]) . '.
' . + 'Did you mean buildquery($get, true) . + '&spellcheck=no">' . + htmlspecialchars($results["spelling"]["correction"]) . + '?' . + '
'; +} + +/* + Populate links +*/ +if(count($results["web"]) === 0){ + + $payload["left"] .= + '
' . + "

Nobody here but us chickens!

" . + 'Have you tried:' . + '
    ' . + '
  • Using a different scraper
  • ' . + '
  • Using fewer keywords
  • ' . + '
  • Defining broader filters (Is NSFW turned off?)
  • ' . + '
' . + '
'; +} + +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"] = + ''; +} + +/* + Generate videos +*/ +if(count($results["video"]) !== 0){ + + $answerlen++; + $right["video"] = + '
' . + '' . + '
' . + '
' . + '

Videos

' . + '
'; + + 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"] .= + '
' . + '
'; +} + +/* + Generate news +*/ +if(count($results["news"]) !== 0){ + + $answerlen++; + $right["news"] = + '
' . + '' . + '
' . + '
' . + '

News

' . + '
'; + + 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"] .= + '
' . + '
'; +} + +/* + Generate answers +*/ +if(count($results["answer"]) !== 0){ + + $right["answer"] = ""; + + foreach($results["answer"] as $answer){ + + $answerlen++; + $right["answer"] .= + '
' . + '' . + '
'; + + if(!empty($answer["title"])){ + + $right["answer"] .= + '
'; + + if(!empty($answer["url"])){ + + $right["answer"] .= ''; + } + + $right["answer"] .= '

' . htmlspecialchars($answer["title"]) . '

'; + + if(!empty($answer["url"])){ + + $right["answer"] .= '
'; + } + + + $right["answer"] .= '
'; + } + + if(!empty($answer["url"])){ + + $right["answer"] .= + $frontend->drawlink($answer["url"]); + } + + $right["answer"] .= '
'; + + if(!empty($answer["thumb"])){ + + $right["answer"] .= + '' . + 'thumb' . + ''; + } + + foreach($answer["description"] as $description){ + + switch($description["type"]){ + + case "text": + $right["answer"] .= $frontend->highlighttext($get["s"], $description["value"]); + break; + + case "title": + $right["answer"] .= + '

' . + htmlspecialchars($description["value"]) . + '

'; + break; + + case "italic": + $right["answer"] .= + '' . + $frontend->highlighttext($get["s"], $description["value"]) . + ''; + break; + + case "quote": + $right["answer"] .= + '
' . + $frontend->highlighttext($get["s"], $description["value"]) . + '
'; + break; + + case "code": + $right["answer"] .= + '
' . + $frontend->highlightcode($description["value"], true) . + '
'; + break; + + case "inline_code": + $right["answer"] .= + '
' . + htmlspecialchars($description["value"]) . + '
'; + break; + + case "link": + $right["answer"] .= + '' . htmlspecialchars($description["value"]) . ''; + break; + + case "image": + $right["answer"] .= + 'image'; + break; + + case "audio": + $right["answer"] .= + ''; + break; + } + } + + $right["answer"] .= '
'; + + if(count($answer["table"]) !== 0){ + + $right["answer"] .= ''; + + foreach($answer["table"] as $info => $value){ + + $right["answer"] .= + '' . + '' . + '' . + ''; + } + + $right["answer"] .= '
' . $info . '' . $value . '
'; + } + + if(count($answer["sublink"]) !== 0){ + + $right["answer"] .= '
'; + $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"] .= + '' . + '
' . + 'icon' . + '
' . $website . '
' . + '
' . + '
'; + } + + $right["answer"] .= '
'; + } + + $right["answer"] .= + '
' . + '
'; + } +} + +/* + 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"] .= '

Related searches

'; + + $opentr = false; + + for($i=0; $i<$c; $i++){ + + if(($i % 2) === 0){ + + $opentr = true; + $payload["left"] .= ''; + }else{ + + $opentr = false; + } + + $payload["left"] .= + ''; + + if($opentr === false){ + + $payload["left"] .= ''; + } + } + + if($opentr === true){ + + $payload["left"] .= ''; + } + + $payload["left"] .= ''; +} + +/* + Load next page +*/ +if($results["npt"] !== null){ + + $payload["left"] .= + 'Next page >'; +} + +echo $frontend->load("search.html", $payload); -- cgit v1.2.3