├── LICENSE ├── README.md ├── install └── install.sh └── public ├── .htaccess ├── Conf.inc ├── Log.inc ├── ProxyHttpRequest.inc ├── ProxyHttpResponse.inc ├── app-qr.php ├── app.php ├── conf-local-template.inc ├── filters ├── DomUrlFilters.inc ├── TextExternalUrlFilters.inc └── TextInternalUrlFilters.inc ├── index.php ├── main.inc ├── rwb ├── .htaccess ├── RedirectWhenBlockedFull.inc ├── conf │ ├── alt_base_urls.txt │ ├── alt_url_collections.txt │ └── code_update_timestamp.txt ├── jquery-1.11.1.min.js ├── multibyte.inc ├── rwb.appcache ├── rwb.appcache.functions.inc ├── spinner.gif ├── string.inc ├── substitute-page.css ├── substitute-page.js └── substitute-page.php ├── simple_html_dom.php ├── status_tests ├── StatusTest.inc └── enabled │ ├── AltBaseUrlsTest.inc │ └── CurlTest.inc └── url.inc /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014 GreatFire.org 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## Introduction 2 | 3 | Website-mirror-by-proxy is a server-side web proxy designed to host one or multiple dynamic mirror versions of any website. It is based on https://github.com/greatfire/redirect-when-blocked (the full edition). Whereas redirect-when-blocked requires the source/origin website to be modified, website-mirror-by-proxy runs separately and does not need any modification of the source/origin website. 4 | 5 | The Wall Street Journal beautifully illustrated our approach with one inaccuracy. The person inside the country experiencing online censorship does not need any special software to access ban sites. Any regular browser will be able to access the dynamic mirrors. 6 | 7 | ![alt tag](http://si.wsj.net/public/resources/images/BT-AA566A_CFIRE_9U_20150316165711.jpg) 8 | 9 | ## Preparation 10 | 11 | You need to have accounts on CDNs or servers/VPS. You can set up accounts on [most CDNs])(http://www.cdnplanet.com/cdns/) and hosting providers. 12 | 13 | ## How to set up 14 | 1. Install the required dependencies. If you are using Ubuntu or a similar OS you can use the install.sh script. Otherwise, manually install/enable Apache, the Apache rewrite module, PHP and the PHP HTTP extension (http://php.net/manual/en/book.http.php). It has to be version 1 of the HTTP extension since version 2 is not backward compatible. The specific version used in the install script and which this project has been tested successfully on is pecl_http-1.7.6. 15 | 2. Copy conf-local-template.inc to conf-local.inc. 16 | 3. In the conf-local.inc file, add the Conf::$default_upstream_base_url that you want to proxy. The URL should be formatted like this: scheme://domain, without any trailing slash or path. Example: http://example.com. 17 | 4. Make sure that Apache is parsing .htaccess files in the site directory (eg "AllowOverride All"). 18 | 5. Add a list of one or more URLs where the site can be accessed to public/rwb/conf/alt_base_urls.txt. Each URL should include a trailing slash (eg http://localhost/website-mirror-by-proxy/public/ or http://example.com/). 19 | 6. Optionally add a list of one or more third-party URLs, where the user should be redirected to if all of the mirror URLs fail, to public/rwb/conf/alt_url_collections.txt. 20 | 7. Access the site... 21 | 22 | There are many configuration settings, some of which are used by default in the 'main.inc' file. The static classes in the filters directory can be used to fix broken URL rewrites (usually because of URLs generated in javascript) and to proxy URLs on third-party hosts. 23 | 24 | ## Other platforms 25 | This project could run on older versions of PHP, without the HTTP Extension, by replacing the HttpRequest, HTTPMessage etc with other compatible classes. It could run on servers other than Apache by adapting the .htaccess/rewrite functionality. It could also be wholly ported to a non-PHP environemnt, though such an initiative should probably start by porting redirect-when-blocked itself first. 26 | 27 | ## Live examples and screenshots 28 | 29 | https://boxun1.azurewebsites.net/ 30 | 31 | ![alt tag](https://lh3.googleusercontent.com/jxAZsTnTex0gW3ItSuP4yOnPpvEl5CFUQdH-T0nl-oun7mrzSy_lz5TbA2I-5ATVLYBdbYS-ak4uriPL9gwzoMm5bz09LuLKzFF1K20qbek4tOccZcXDIw0jLAUwu8m3cS8axWs) 32 | 33 | ## FAQ 34 | 35 | Does the mirror update in real time and support editing? 36 | 37 | Yes. The mirror site is a proxy of the original site. All changes on the original site will be effective immediately on the mirror sites. Furthermore, users can directly interact with the mirror sites and all changes/forms submitted by users will be immediately uploaded to the original site. 38 | 39 | We will questions and answers to the FAQ here when we receive them. Please submit issues on: https://github.com/greatfire/website-mirror-by-proxy/issues 40 | 41 | ## Security Audit 42 | 43 | Independent security experts have audited the source code. The audit report will be made available once issues detailed in the report are fixed. 44 | 45 | 46 | 47 | ## Contributions 48 | .. are very welcome, as is feedback. Feel free to open issues and to contribute improvements. 49 | -------------------------------------------------------------------------------- /install/install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | function pecl_install { 3 | pecl install $1 4 | echo "extension=$2.so" | sudo tee /etc/php5/mods-available/$2.ini 5 | echo "; priority=$3" | sudo tee -a /etc/php5/mods-available/$2.ini 6 | php5enmod $2 7 | } 8 | 9 | if [ $(/usr/bin/id -u) -ne 0 ]; then 10 | echo "Not running as root" 11 | exit 12 | fi 13 | 14 | echo "Installing Apache and PHP" 15 | apt-get install apache2 php5 php5-curl 16 | 17 | echo "Installing HTTP extension" 18 | apt-get install libpcre3-dev libcurl3-openssl-dev php5-dev php-http php5-mcrypt php-pear 19 | pecl_install pecl/raphf raphf 20 20 | pecl_install pecl/propro propro 20 21 | pecl_install pecl_http http 30 22 | 23 | echo "Enabling Apache modules" 24 | a2enmod proxy 25 | a2enmod proxy_http 26 | a2enmod rewrite 27 | -------------------------------------------------------------------------------- /public/.htaccess: -------------------------------------------------------------------------------- 1 | RewriteEngine On 2 | 3 | # Stream directly for some types. 4 | RewriteCond %{HTTP:X-Requested-With} ShockwaveFlash/.* [OR] 5 | RewriteCond %{REQUEST_URI} \.mp4$ 6 | RewriteRule ^(https?:/)(.*)$ $1/$2 [L,P] 7 | 8 | RewriteCond %{REQUEST_FILENAME} !index.php 9 | RewriteCond %{REQUEST_FILENAME} !rwb/.* 10 | RewriteRule . index.php [L] -------------------------------------------------------------------------------- /public/Conf.inc: -------------------------------------------------------------------------------- 1 | 'Downloading {{APK}} ...', 60 | 'scan_or_click' => 'Scan or click on your Android device to download the app.', 61 | 'weixin' => 'To download {{APK}} click the top right button and select "Open in a browser"' 62 | ); 63 | 64 | public static function addGoogleAnalyticsId($id) 65 | { 66 | static $i; 67 | if (! isset($i)) { 68 | $i = 0; 69 | } 70 | $i ++; 71 | 72 | $name = 'wmbp' . $i; 73 | $ga_script = << 75 | (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ 76 | (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), 77 | m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) 78 | })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); 79 | 80 | ga('create', '$id', 'auto', {'name': '$name'}); 81 | ga('$name.send', 'pageview'); 82 | 83 | 84 | EOF; 85 | // Appends to main page / iframe container. 86 | RedirectWhenBlockedFull::appendToHtmlBody($ga_script); 87 | 88 | // Appends to iframed content. 89 | self::appendToHtmlBody($ga_script); 90 | } 91 | 92 | public static function appendToHtmlBody($str) 93 | { 94 | self::$html_body_appendix .= $str; 95 | } 96 | 97 | public static function appendToHtmlHead($str) 98 | { 99 | self::$html_head_appendix .= $str; 100 | } 101 | 102 | public static function getDefaultUpstreamBaseUrlComponent($name) 103 | { 104 | $components = self::getDefaultUpstreamBaseUrlComponents(); 105 | if (isset($components[$name])) { 106 | return $components[$name]; 107 | } 108 | } 109 | 110 | public static function getDefaultUpstreamBaseUrlComponents() 111 | { 112 | static $components; 113 | if (! isset($components)) { 114 | $components = parse_url(self::$default_upstream_base_url); 115 | } 116 | return $components; 117 | } 118 | } -------------------------------------------------------------------------------- /public/Log.inc: -------------------------------------------------------------------------------- 1 | getUrl(), 13 | $this->getHeaders()); 14 | 15 | if (isset($_POST)) { 16 | 17 | $post_data = $_POST; 18 | 19 | // If charset specified, convert back to upstream charset before adding. 20 | if (Conf::$default_upstream_charset) { 21 | array_walk($post_data, 22 | function (&$value) 23 | { 24 | $value = mb_convert_encoding($value, 25 | Conf::$default_upstream_charset, 'utf-8'); 26 | }); 27 | } 28 | 29 | if ($this->getPostEncType() == self::POST_ENC_TYPE_MULTIPART) { 30 | 31 | // First unset the original content type header. addForm() will automatically add it 32 | // with it's own boundary value. 33 | $this->setHeader('Content-Type', NULL); 34 | 35 | $this->getBody()->addForm($_POST); 36 | } else { 37 | $this->getBody()->append(new http\QueryString($post_data)); 38 | } 39 | 40 | Log::add($post_data, 'post_data'); 41 | } 42 | 43 | $this->setOptions( 44 | [ 45 | 'connecttimeout' => Conf::$proxy_http_request_connecttimeout, 46 | 'dns_cache_timeout' => Conf::$proxy_http_request_dns_cache_timeout, 47 | 'retrycount' => Conf::$proxy_http_request_retrycount, 48 | 'timeout' => Conf::$proxy_http_request_timeout 49 | ]); 50 | 51 | Log::add($this->__toString(), 'ProxyHttpRequest->__toString()'); 52 | } 53 | 54 | public function getHeaders() 55 | { 56 | $headers = getallheaders(); 57 | 58 | $ignored_headers = array( 59 | 60 | // This only applies to the connection between the proxy and the user, 61 | // not the proxy and the upstream origin. 62 | 'Accept-Encoding', 63 | 64 | 'Connection', 65 | 'Content-Length', 66 | 'Fastly-Client', 67 | 'Fastly-Client-IP', 68 | 'Fastly-FF', 69 | 'Fastly-Orig-Host', 70 | 'Fastly-SSL', 71 | 'Host', 72 | 'X-Forwarded-Host', 73 | 'X-Forwarded-Server', 74 | 'X-Varnish', 75 | 76 | // Otherwise CloudfFront to CloudFront requests are denied: 77 | 'Via', 78 | 'X-Amz-Cf-Id' 79 | ); 80 | 81 | if (! Conf::$cookies_enabled) { 82 | $ignored_headers[] = 'Cookie'; 83 | } 84 | 85 | foreach ($ignored_headers as $ignored_header) { 86 | if (isset($headers[$ignored_header])) { 87 | unset($headers[$ignored_header]); 88 | } 89 | 90 | $ignored_header_alt = strtolower($ignored_header); 91 | if (isset($headers[$ignored_header_alt])) { 92 | unset($headers[$ignored_header_alt]); 93 | } 94 | } 95 | 96 | foreach ($headers as $key => &$value) { 97 | TextExternalUrlFilters::applyReverse($value); 98 | } 99 | 100 | // Proxy standard headers. 101 | if (! isset($headers['X-Forwarded-For'])) { 102 | $headers['X-Forwarded-For'] = $_SERVER['REMOTE_ADDR']; 103 | } 104 | 105 | if (! isset($headers['X-Real-IP'])) { 106 | $real_ip = $headers['X-Forwarded-For']; 107 | 108 | // If multiple (command-separated) forwarded IPs, use the first one. 109 | if (strpos($real_ip, ',') !== false) { 110 | list ($real_ip) = explode(',', $real_ip); 111 | } 112 | 113 | $headers['X-Real-IP'] = $real_ip; 114 | } 115 | 116 | return $headers; 117 | } 118 | 119 | public function getUrl() 120 | { 121 | static $url; 122 | if (! isset($url)) { 123 | 124 | if (isset($_GET[RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME]) && $_GET[RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME] == 125 | Conf::OUTPUT_TYPE_APK && Conf::$apk_url) { 126 | 127 | $url = Conf::$apk_url; 128 | $filename = basename(parse_url($url, PHP_URL_PATH)); 129 | header('Content-Disposition: attachment; filename=' . $filename); 130 | 131 | // Run after all other code to override other content-type header. 132 | register_shutdown_function( 133 | function () 134 | { 135 | header( 136 | 'Content-Type: application/vnd.android.package-archive'); 137 | }); 138 | } else { 139 | $url = RedirectWhenBlockedFull::getRequestUriWithoutQueryStringParam(); 140 | $this->removeThisScriptDirFromUrl($url); 141 | 142 | if (startsWith($url, '/http://') || startsWith($url, 143 | '/https://')) { 144 | $url = substr($url, 1); 145 | 146 | if (! TextExternalUrlFilters::matchesUrl($url)) { 147 | header('HTTP/1.0 403 Forbidden'); 148 | exit(); 149 | } 150 | 151 | // If we for some reason have the default upstream host and scheme in the URL, remove them. 152 | $url_components = parse_url($url); 153 | if ($url_components['host'] == 154 | Conf::getDefaultUpstreamBaseUrlComponent('host') && $url_components['scheme'] == 155 | Conf::getDefaultUpstreamBaseUrlComponent('scheme')) { 156 | $new_url = http_build_path_query_fragment( 157 | $url_components); 158 | $new_url = RedirectWhenBlockedFull::getBaseUrl() . 159 | ltrim($new_url, '/'); 160 | header('Location: ' . $new_url); 161 | exit(); 162 | } 163 | 164 | // Use in DomUtlFilters for relative URLs. 165 | $base_url_suffix = rtrim(http_build_scheme_host($url), '/') . 166 | '/'; 167 | RedirectWhenBlockedFull::setBaseUrlSuffix($base_url_suffix); 168 | } else { 169 | 170 | if ($url == '/') { 171 | if (Conf::$default_upstream_url) { 172 | $url = Conf::$default_upstream_url; 173 | } 174 | } 175 | $url = Conf::$default_upstream_base_url . $url; 176 | } 177 | } 178 | } 179 | 180 | // Reverse rewrites of parameters inside URL. 181 | TextExternalUrlFilters::applyReverse($url); 182 | Log::add($url, 'url'); 183 | return $url; 184 | } 185 | 186 | public function getUrlComponent($name) 187 | { 188 | $components = $this->getUrlComponents(); 189 | if (isset($components[$name])) { 190 | return $components[$name]; 191 | } 192 | } 193 | 194 | public function getUrlComponents() 195 | { 196 | static $components; 197 | if (! isset($components)) { 198 | $components = parse_url($this->getUrl()); 199 | } 200 | return $components; 201 | } 202 | 203 | private function getPostEncType() 204 | { 205 | $content_type = $this->getHeader('Content-Type'); 206 | if ($content_type) { 207 | list ($enc_type) = explode(';', $content_type); 208 | if ($enc_type == self::POST_ENC_TYPE_MULTIPART) { 209 | return self::POST_ENC_TYPE_MULTIPART; 210 | } 211 | } 212 | 213 | // Default - used in most forms. 214 | return self::POST_ENC_TYPE_APPLICATION; 215 | } 216 | 217 | private function removeThisScriptDirFromUrl(&$url) 218 | { 219 | $this_script_dir = dirname($_SERVER['SCRIPT_NAME']); 220 | if ($this_script_dir != '/' && 221 | substr($url, 0, strlen($this_script_dir)) == $this_script_dir) { 222 | $url = substr($url, strlen($this_script_dir)); 223 | } 224 | return $url; 225 | } 226 | } 227 | -------------------------------------------------------------------------------- /public/ProxyHttpResponse.inc: -------------------------------------------------------------------------------- 1 | body = $response->getBody()->toString(); 24 | $this->headers = $response->getHeaders(); 25 | $this->response_code = $response->getResponseCode(); 26 | $this->response_info = $response->getInfo(); 27 | 28 | $this->response = $response; 29 | $this->request = $request; 30 | } 31 | 32 | public function getBody() 33 | { 34 | $body = $this->body; 35 | $content_type = $this->getContentType(); 36 | 37 | switch ($content_type) { 38 | 39 | case self::CONTENT_TYPE_JAVASCRIPT: 40 | case self::CONTENT_TYPE_JSON: 41 | case self::CONTENT_TYPE_TEXT_CSS: 42 | case self::CONTENT_TYPE_TEXT_HTML: 43 | $body = $this->getBodyFilteredByContentType($body, 44 | $content_type); 45 | 46 | // These filters apply to all of the above. 47 | TextInternalUrlFilters::applyAll($body); 48 | TextExternalUrlFilters::applyAll($body, $content_type); 49 | 50 | // Run this after the global filters above, to avoid rewriting some URLs twice. 51 | if ($content_type == self::CONTENT_TYPE_TEXT_HTML) { 52 | RedirectWhenBlockedFull::injectBaseTag($body); 53 | } 54 | 55 | // Remove content-length, since this might be different after modification. 56 | if (isset($this->headers['Content-Length'])) { 57 | unset($this->headers['Content-Length']); 58 | } 59 | 60 | Log::add($this->response->__toString(), 61 | '$this->response->__toString()'); 62 | break; 63 | } 64 | 65 | return $body; 66 | } 67 | 68 | public function getHeader($name) 69 | { 70 | if (isset($this->headers[$name])) { 71 | return $this->headers[$name]; 72 | } 73 | } 74 | 75 | public function getHeaders() 76 | { 77 | $headers = $this->headers; 78 | Log::add($headers, 'headers raw'); 79 | 80 | // For HTML content, overwrite upstream cache conf. 81 | if (isset($headers['Cache-Control'])) { 82 | if ($this->getContentType() == $this::CONTENT_TYPE_TEXT_HTML) { 83 | unset($headers['Cache-Control']); 84 | } 85 | } 86 | 87 | // If no cache conf, for some content types, add longer cache. 88 | else { 89 | if ($this->getContentType() == $this::CONTENT_TYPE_OTHER) { 90 | $headers['Cache-Control'] = getCacheControlHeader(60 * 60, 91 | 60 * 60, 60 * 60 * 24); 92 | } 93 | } 94 | 95 | // If redirect, rewrite Location header. 96 | if (isset($headers['Location'])) { 97 | if (parse_url($headers['Location'], PHP_URL_HOST)) { 98 | TextExternalUrlFilters::applyAll($headers['Location']); 99 | } 100 | 101 | // Header redirects require full URLs, with scheme and host. 102 | if (! parse_url($headers['Location'], PHP_URL_HOST)) { 103 | $headers['Location'] = RedirectWhenBlockedFull::getBaseUrl(true) . 104 | ltrim($headers['Location'], '/'); 105 | } 106 | } 107 | 108 | // Rewrite set-cookie headers (or remove if cookies disabled). 109 | if (isset($headers['Set-Cookie'])) { 110 | 111 | if (! Conf::$cookies_enabled) { 112 | unset($headers['Set-Cookie']); 113 | } else { 114 | if (is_array($headers['Set-Cookie'])) { 115 | foreach ($headers['Set-Cookie'] as &$set_cookie) { 116 | $set_cookie = $this->getFilteredSetCookie($set_cookie); 117 | } 118 | } else { 119 | $headers['Set-Cookie'] = $this->getFilteredSetCookie( 120 | $headers['Set-Cookie']); 121 | } 122 | } 123 | } 124 | 125 | // Unset some. 126 | $skip = array( 127 | 'Connection', 128 | 'Content-Encoding', 129 | 'Transfer-Encoding', 130 | 'X-Original-Content-Encoding' 131 | ); 132 | foreach ($skip as $s) { 133 | if (isset($headers[$s])) { 134 | unset($headers[$s]); 135 | } 136 | } 137 | 138 | Log::add($headers, 'headers filtered'); 139 | 140 | return $headers; 141 | } 142 | 143 | public function getResponseCode() 144 | { 145 | return $this->response_code; 146 | } 147 | 148 | public function getResponseInfo() 149 | { 150 | return $this->response_info; 151 | } 152 | 153 | private function destroyDom(&$dom) 154 | { 155 | $dom->clear(); 156 | unset($dom); 157 | } 158 | 159 | private function getBodyFilteredByContentType($body, $content_type) 160 | { 161 | switch ($content_type) { 162 | 163 | case self::CONTENT_TYPE_TEXT_CSS: 164 | 165 | $css_base_url = $this->getCssBaseUrl(); 166 | 167 | // Convert protocol relative URLs to HTTPS. 168 | $body = str_replace('url(//', 'url(https://', $body); 169 | $body = str_replace('url("//', 'url("https://', $body); 170 | $body = str_replace('url(\'//', 'url(\'https://', $body); 171 | 172 | // Disabling this part. Not sure why it was added in the first place. 173 | /* 174 | * $body = str_replace('url("../', 'url("' . $css_base_url . '../', 175 | * $body); 176 | * $body = str_replace('url(\'../', 177 | * 'url(\'' . $css_base_url . '../', $body); 178 | * $body = str_replace('url(../', 'url(' . $css_base_url . '../', 179 | * $body); 180 | */ 181 | 182 | $body = str_replace('url("/', 'url("' . $css_base_url, $body); 183 | $body = str_replace('url(\'/', 'url(\'' . $css_base_url, $body); 184 | $body = str_replace('url(/', 'url(' . $css_base_url, $body); 185 | break; 186 | 187 | case self::CONTENT_TYPE_TEXT_HTML: 188 | 189 | $dom = $this->getDomFromHtml($body); 190 | 191 | if ($dom) { 192 | 193 | foreach ($dom->find('head title') as $title_element) { 194 | $title = mb_convert_encoding_plus( 195 | $title_element->text(), 'UTF-8', 196 | $this->getCharsetFromHeadersOrDom($dom)); 197 | if ($title) { 198 | $title .= ' | 免翻墙镜像'; 199 | 200 | // Update title in DOM. 201 | $title_element->innertext = mb_convert_encoding_plus( 202 | $title, $this->getCharsetFromHeadersOrDom($dom), 203 | 'UTF-8'); 204 | break; 205 | } 206 | } 207 | } 208 | 209 | // Default title. 210 | if (! isset($title) || ! $title) { 211 | $title = '免翻墙镜像'; 212 | } 213 | 214 | // Special - override meta redirects since RWB would just slow them down. 215 | if ($dom && count($dom->find('find('getAttribute('content'); 218 | if ($content) { 219 | $content_chunks = explode(';', $content, 2); 220 | if (isset($content_chunks[1])) { 221 | $url_chunks = explode('=', $content_chunks[1], 222 | 2); 223 | if (isset($url_chunks[1])) { 224 | $url = trim($url_chunks[1], '\'" '); 225 | if ($url) { 226 | $this->headers['Location'] = $url; 227 | return ''; 228 | } 229 | } 230 | } 231 | } 232 | } 233 | } 234 | 235 | if ($this->shouldUseRedirectWhenBlocked()) { 236 | 237 | RedirectWhenBlockedFull::setCharset( 238 | $this->getCharsetFromHeadersOrDom($dom)); 239 | 240 | RedirectWhenBlockedFull::setWebsiteTitle($title); 241 | RedirectWhenBlockedFull::run(); 242 | 243 | if (RedirectWhenBlockedFull::getOutputType() == 244 | RedirectWhenBlockedFull::OUTPUT_TYPE_JSONP) { 245 | 246 | // RWB will turn output into JSONP. Remove content-type header to keep header sent by RWB. 247 | if (isset($this->headers['Content-Type'])) { 248 | unset($this->headers['Content-Type']); 249 | } 250 | 251 | // Also remove charset specification in inline HTML. 252 | if($dom) { 253 | foreach($dom->find('meta[http-equiv=Content-Type], meta[charset]') as $meta) { 254 | $meta->outertext = ''; 255 | } 256 | } 257 | } 258 | } 259 | 260 | // Might be for example JSONP data served with an incorrect header. 261 | if (! $dom || ! $dom->find('body')) { 262 | break; 263 | } 264 | 265 | DomUrlFilters::applyAll($dom, $this->request); 266 | 267 | // Special for iframes. Prevent RWB from hijacking content (iframe in iframe problem). 268 | foreach ($dom->find('iframe') as $iframe) { 269 | $src = $iframe->getAttribute('src'); 270 | if ($src) { 271 | $src = http_add_query_component($src, 272 | RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME, 273 | RedirectWhenBlockedFull::OUTPUT_TYPE_IFRAME); 274 | $iframe->setAttribute('src', $src); 275 | } 276 | } 277 | 278 | // Special for style attributes - apply CSS filter. 279 | foreach ($dom->find('*[style]') as $style_element) { 280 | $style_element->setAttribute('style', 281 | $this->getBodyFilteredByContentType( 282 | $style_element->getAttribute('style'), 283 | self::CONTENT_TYPE_TEXT_CSS)); 284 | } 285 | 286 | $dom_do_reset = false; 287 | 288 | // Don't insert stuff if request failed. 289 | if ($this->getResponseCode() == 200) { 290 | if (Conf::$html_body_appendix) { 291 | foreach ($dom->find('body') as $b) { 292 | $b->innertext .= Conf::$html_body_appendix; 293 | break; 294 | } 295 | 296 | $dom_do_reset = true; 297 | } 298 | 299 | if (Conf::$html_head_appendix) { 300 | foreach ($dom->find('head') as $h) { 301 | $h->innertext .= Conf::$html_head_appendix; 302 | break; 303 | } 304 | 305 | $dom_do_reset = true; 306 | } 307 | } 308 | 309 | if (count($dom->find('script[async]'))) { 310 | 311 | if ($dom_do_reset) { 312 | 313 | // Bug in Simple HTML Dom means that DOM has to be reloaded before further edits. 314 | $this->resetDom($dom); 315 | $dom_do_reset = false; 316 | } 317 | 318 | // Remove 'async' attributes because they break the page in IE11 when loaded in our iframe. 319 | foreach ($dom->find('script[async]') as $x) { 320 | $x->removeAttribute('async', ''); 321 | } 322 | } 323 | 324 | if (count($dom->find('style'))) { 325 | 326 | if ($dom_do_reset) { 327 | 328 | // Bug in Simple HTML Dom means that DOM has to be reloaded before further edits. 329 | $this->resetDom($dom); 330 | $dom_do_reset = false; 331 | } 332 | 333 | foreach ($dom->find('style') as $style) { 334 | $style->innertext = $this->getBodyFilteredByContentType( 335 | $style->innertext, self::CONTENT_TYPE_TEXT_CSS); 336 | } 337 | } 338 | 339 | $body = $dom->__toString(); 340 | $this->destroyDom($dom); 341 | break; 342 | } 343 | 344 | return $body; 345 | } 346 | 347 | private function getCharsetFromHeadersOrDom($dom) 348 | { 349 | // Allow manually overriding this. 350 | if (Conf::$default_upstream_charset) { 351 | return Conf::$default_upstream_charset; 352 | } 353 | 354 | // Get charset from header, if available. 355 | $content_type = $this->response->getHeader('Content-Type'); 356 | if ($content_type) { 357 | $content_type_chunks = explode(';', $content_type, 2); 358 | if (isset($content_type_chunks[1])) { 359 | $charset = trim($content_type_chunks[1]); 360 | $charset_chunks = explode('=', $charset, 2); 361 | if (isset($charset_chunks[1])) { 362 | return $charset_chunks[1]; 363 | } 364 | } 365 | } 366 | 367 | // If no headers, try to find a meta tag. 368 | if ($dom) { 369 | foreach ($dom->find('meta[http-equiv=Content-Type]') as $meta) { 370 | $content = $meta->getAttribute('content'); 371 | if ($content) { 372 | $content_chunks = explode(';', $content, 2); 373 | if (isset($content_chunks[1])) { 374 | $charset_key_value_str = trim($content_chunks[1]); 375 | $charset_key_value_arr = explode('=', 376 | $charset_key_value_str, 2); 377 | if (isset($charset_key_value_arr[1])) { 378 | return $charset_key_value_arr[1]; 379 | } 380 | } 381 | } 382 | } 383 | } 384 | } 385 | 386 | private function getContentType() 387 | { 388 | static $content_type; 389 | if (! isset($content_type)) { 390 | $content_type = $this->getContentTypeFromHeader(); 391 | } 392 | return $content_type; 393 | } 394 | 395 | private function getContentTypeFromHeader() 396 | { 397 | $content_type = $this->getHeader('Content-Type'); 398 | $content_type_chunks = explode(';', $content_type, 2); 399 | if (count($content_type_chunks) > 1) { 400 | $content_type = $content_type_chunks[0]; 401 | } 402 | $content_type = strtolower($content_type); 403 | 404 | switch ($content_type) { 405 | 406 | case 'application/json': 407 | return self::CONTENT_TYPE_JSON; 408 | 409 | case 'application/javascript': 410 | case 'application/x-javascript': 411 | case 'text/javascript': 412 | return self::CONTENT_TYPE_JAVASCRIPT; 413 | 414 | case 'text/css': 415 | return self::CONTENT_TYPE_TEXT_CSS; 416 | 417 | case 'text/html': 418 | 419 | // This indicates it's an ajax request. Some servers don't set 420 | // the content-type header correctly. 421 | if ($this->request->getHeader('X-Requested-With')) { 422 | return self::CONTENT_TYPE_JAVASCRIPT; 423 | } 424 | 425 | // This indicates JSON. Same as above. 426 | if (stripos($this->request->getHeader('Accept'), 427 | 'application/json') !== false) { 428 | return self::CONTENT_TYPE_JSON; 429 | } 430 | 431 | return self::CONTENT_TYPE_TEXT_HTML; 432 | } 433 | 434 | return self::CONTENT_TYPE_OTHER; 435 | } 436 | 437 | private function getCssBaseUrl() 438 | { 439 | $url_path_depth = count( 440 | explode('/', trim($this->request->getUrlComponent('path'), '/'))) - 1; 441 | if ($url_path_depth) { 442 | return str_repeat('../', $url_path_depth); 443 | } else { 444 | return './'; 445 | } 446 | } 447 | 448 | private function getDomFromHtml($html) 449 | { 450 | return str_get_html($html, false, false, '', false); 451 | } 452 | 453 | private function getFilteredSetCookie($set_cookie) 454 | { 455 | $all_chunks = explode(';', $set_cookie); 456 | $filtered_chunks = array(); 457 | foreach ($all_chunks as &$chunk) { 458 | $chunk = trim($chunk); 459 | list ($key) = explode('=', $chunk); 460 | switch ($key) { 461 | case 'path': 462 | case 'domain': 463 | continue 2; 464 | default: 465 | $filtered_chunks[] = $chunk; 466 | } 467 | } 468 | return implode('; ', $filtered_chunks); 469 | } 470 | 471 | private function resetDom(&$dom) 472 | { 473 | $html = $dom->__toString(); 474 | $this->destroyDom($dom); 475 | $dom = $this->getDomFromHtml($html); 476 | } 477 | 478 | private function shouldUseRedirectWhenBlocked() 479 | { 480 | 481 | // Don't use if response code isn't 200. Ie redirects shouldn't be 482 | // overridden, and error pages shouldn't be cached. 483 | if ($this->getResponseCode() != 200) { 484 | return false; 485 | } 486 | 487 | // Don't use for POST requests. 488 | if ($_SERVER['REQUEST_METHOD'] != 'GET') { 489 | return false; 490 | } 491 | 492 | return true; 493 | } 494 | } 495 | -------------------------------------------------------------------------------- /public/app-qr.php: -------------------------------------------------------------------------------- 1 | 16 | 17 | 18 | 19 | 20 | 22 | <?php print $apk_filename ?> 23 | 51 | 52 | 53 |
54 | 58 | 61 |
62 |
64 | 65 |
66 |
67 |
68 | 69 | 92 | 93 | -------------------------------------------------------------------------------- /public/conf-local-template.inc: -------------------------------------------------------------------------------- 1 | $elements) { 17 | self::apply($dom, $attribute, $elements, $request); 18 | } 19 | } 20 | 21 | private static function apply(simple_html_dom $dom, $attribute, $elements, 22 | ProxyHttpRequest $request) 23 | { 24 | foreach ($dom->find($elements . '[' . $attribute . ']') as $element) { 25 | $attr_val = $element->getAttribute($attribute); 26 | if ($attr_val) { 27 | 28 | // Ignore these links. 29 | if (startsWith($attr_val, array( 30 | 'data:', 31 | 'javascript:', 32 | 'mailto:', 33 | '.' 34 | ))) { 35 | continue; 36 | } 37 | 38 | // Turn protocol relative URLs into HTTPS. 39 | if (isset($attr_val[1]) && $attr_val[1] == '/' && 40 | $attr_val[0] == '/') { 41 | $attr_val = 'https:' . $attr_val; 42 | $element->setAttribute($attribute, $attr_val); 43 | } 44 | 45 | else { 46 | $attr_val_components = parse_url($attr_val); 47 | 48 | // Nothing to do without paths. 49 | if (isset($attr_val_components['path'])) { 50 | 51 | // Remove current host. 52 | if (isset($attr_val_components['host']) && $attr_val_components['host'] == 53 | $request->getUrlComponent('host')) { 54 | unset($attr_val_components['host']); 55 | } 56 | 57 | // If URL without host. 58 | if (! isset($attr_val_components['host'])) { 59 | 60 | // If path does not start with a slash, prepend current path directory. 61 | if ($attr_val_components['path'][0] != '/') { 62 | $attr_val_components['path'] = dirname( 63 | $request->getUrlComponent('path')) . '/' . 64 | $attr_val_components['path']; 65 | } 66 | 67 | $attr_val = '.' . http_build_path_query_fragment( 68 | $attr_val_components); 69 | $element->setAttribute($attribute, $attr_val); 70 | } 71 | } 72 | } 73 | 74 | /* 75 | * Special for existing base href values. They should always end with a slash, 76 | * but browsers are lenient if it's eg http://example.com. But since we may rewrite 77 | * the value later, it might have a path and without the slash it will fail. 78 | */ 79 | if ($element->tag == 'base') { 80 | $last_char = $attr_val[strlen($attr_val) - 1]; 81 | if ($last_char != '/') { 82 | $attr_val .= '/'; 83 | $element->setAttribute($attribute, $attr_val); 84 | } 85 | } 86 | } 87 | } 88 | } 89 | } -------------------------------------------------------------------------------- /public/filters/TextExternalUrlFilters.inc: -------------------------------------------------------------------------------- 1 | $replace) { 52 | $search = str_replace('/', '\/', $search); 53 | $replace = str_replace('/', '\/', $replace); 54 | $searches2[$search] = $replace; 55 | } 56 | 57 | // For pure JSON content, use these searches only. 58 | if ($content_type == ProxyHttpResponse::CONTENT_TYPE_JSON) { 59 | $searches = $searches2; 60 | } 61 | 62 | // Otherwise append. 63 | else { 64 | $searches += $searches2; 65 | } 66 | } 67 | 68 | // Special for javascript (and HTML since it could be in a script tag). 69 | if (in_array($content_type, 70 | array( 71 | ProxyHttpResponse::CONTENT_TYPE_JAVASCRIPT, 72 | ProxyHttpResponse::CONTENT_TYPE_TEXT_HTML 73 | ))) { 74 | foreach (array( 75 | "'", 76 | '"' 77 | ) as $quote) { 78 | if ($host != Conf::getDefaultUpstreamBaseUrlComponent( 79 | 'host')) { 80 | $prefix = 'http://' . $host; 81 | } else { 82 | $prefix = ''; 83 | } 84 | $searches[$quote . $host . $quote] = $quote . 85 | self::getBaseUrlHostAndPath() . $prefix . $quote; 86 | } 87 | } 88 | 89 | foreach ($searches as $search => $replace) { 90 | $body = str_ireplace($search, $replace, $body); 91 | } 92 | } 93 | } 94 | 95 | public static function applyReverse(&$body) 96 | { 97 | foreach (RedirectWhenBlockedFull::getAltBaseUrls() as $alt_base_url) { 98 | 99 | $searches = array( 100 | $alt_base_url . 'http://' => 'http://', 101 | $alt_base_url . 'https://' => 'https://', 102 | $alt_base_url => Conf::getDefaultUpstreamBaseUrlComponent( 103 | 'scheme') . '://' . 104 | Conf::getDefaultUpstreamBaseUrlComponent('host') . '/' 105 | ); 106 | 107 | // Add url-encoded versions. 108 | foreach ($searches as $search => $replace) { 109 | $search = urlencode($search); 110 | if (! isset($searches[$search])) { 111 | $searches[$search] = urlencode($replace); 112 | } 113 | } 114 | 115 | // Special case when only first colon is encoded. 116 | // Should be moved to site-specific config. 117 | foreach ($searches as $search => $replace) { 118 | $search = str_replace('://', urlencode(':') . '//', $search); 119 | if (! isset($searches[$search])) { 120 | $searches[$search] = str_replace('://', 121 | urlencode(':') . '//', $replace); 122 | } 123 | } 124 | 125 | foreach ($searches as $search => $replace) { 126 | $body = str_replace($search, $replace, $body); 127 | } 128 | } 129 | } 130 | 131 | public static function matchesUrl($url) 132 | { 133 | $host = parse_url($url, PHP_URL_HOST); 134 | if (in_array($host, self::$hosts)) { 135 | return true; 136 | } 137 | } 138 | 139 | private static function getBaseUrlHostAndPath() 140 | { 141 | static $host_and_path; 142 | if (! isset($host_and_path)) { 143 | $base_url_components = parse_url( 144 | RedirectWhenBlockedFull::getBaseUrl()); 145 | $host_and_path = $base_url_components['host']; 146 | if (isset($base_url_components['path'])) { 147 | $host_and_path .= $base_url_components['path']; 148 | } 149 | } 150 | return $host_and_path; 151 | } 152 | 153 | // Remove hosts which start with other hosts (eg remove google.com.hk if google.com is in the list). 154 | // Otherwise some hosts may be replaced twice. 155 | private static function getHostsFiltered() 156 | { 157 | static $filtered_hosts; 158 | if (! isset($filtered_hosts)) { 159 | $filtered_hosts = array(); 160 | sort(self::$hosts); 161 | foreach (self::$hosts as $host) { 162 | foreach ($filtered_hosts as $filtered_host) { 163 | if (startsWith($host, $filtered_host)) { 164 | continue 2; 165 | } 166 | } 167 | $filtered_hosts[] = $host; 168 | } 169 | } 170 | return $filtered_hosts; 171 | } 172 | } -------------------------------------------------------------------------------- /public/filters/TextInternalUrlFilters.inc: -------------------------------------------------------------------------------- 1 | $replace) { 20 | $body = str_ireplace($search, $replace, $body); 21 | } 22 | } 23 | } -------------------------------------------------------------------------------- /public/index.php: -------------------------------------------------------------------------------- 1 | $value) { 22 | header($key . ': ' . $value); 23 | } 24 | 25 | Log::add($_SERVER, '$_SERVER'); 26 | 27 | if (isset($_GET[RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME])) { 28 | 29 | // Key cannot be empty. 30 | if (Conf::$alt_base_urls_key) { 31 | 32 | // Verify key. Set this in conf-local.inc. 33 | if (isset($_GET['key']) && $_GET['key'] == Conf::$alt_base_urls_key) { 34 | 35 | if ($_GET[RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME] == 36 | Conf::OUTPUT_TYPE_ALT_BASE_URLS) { 37 | header('Content-Type: application/javascript'); 38 | print json_encode(RedirectWhenBlockedFull::getAltBaseUrls()); 39 | exit(); 40 | } 41 | 42 | if ($_GET[RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME] == 43 | Conf::OUTPUT_TYPE_APK_URLS) { 44 | header('Content-Type: application/javascript'); 45 | $urls = array(); 46 | foreach (RedirectWhenBlockedFull::getAltBaseUrls() as $url) { 47 | $url .= '?' . 48 | RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME . '=' . 49 | Conf::OUTPUT_TYPE_APK; 50 | $urls[] = $url; 51 | } 52 | print json_encode($urls); 53 | exit(); 54 | } 55 | 56 | if ($_GET[RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME] == 57 | Conf::OUTPUT_TYPE_APP_URLS) { 58 | header('Content-Type: application/javascript'); 59 | $urls = array(); 60 | foreach (RedirectWhenBlockedFull::getAltBaseUrls() as $url) { 61 | $url .= '?' . 62 | RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME . '=' . 63 | Conf::OUTPUT_TYPE_APP; 64 | $urls[] = $url; 65 | } 66 | print json_encode($urls); 67 | exit(); 68 | } 69 | 70 | if ($_GET[RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME] == 71 | Conf::OUTPUT_TYPE_STATUS) { 72 | header('Cache-Control: max-age=0'); 73 | header('Content-Type: text/plain'); 74 | require 'status_tests/StatusTest.inc'; 75 | 76 | foreach (scandir('status_tests/enabled') as $file) { 77 | if ($file[0] == '.') { 78 | continue; 79 | } 80 | require 'status_tests/enabled/' . $file; 81 | $class = basename($file, '.inc'); 82 | $test = new $class(); 83 | $tests[] = $test; 84 | } 85 | 86 | foreach ($tests as $test) { 87 | if (! $test->passed()) { 88 | http_response_code(503); 89 | break; 90 | } 91 | } 92 | 93 | foreach ($tests as $i => $test) { 94 | if ($i > 0) { 95 | print "\n---\n"; 96 | } 97 | print $test; 98 | } 99 | 100 | exit(); 101 | } 102 | } 103 | } 104 | 105 | if (Conf::$apk_url) { 106 | if ($_GET[RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME] == 107 | Conf::OUTPUT_TYPE_APP) { 108 | require 'app.php'; 109 | exit(); 110 | } 111 | 112 | if ($_GET[RedirectWhenBlockedFull::QUERY_STRING_PARAM_NAME] == 113 | Conf::OUTPUT_TYPE_APP_QR) { 114 | require 'app-qr.php'; 115 | exit(); 116 | } 117 | } 118 | } 119 | 120 | $request = new ProxyHttpRequest(); 121 | 122 | // Hijack crossdomain.xml. 123 | if ($request->getUrlComponent('path') == '/crossdomain.xml' && 124 | getDownstreamOrigin()) { 125 | header('Content-Type: application/xml'); 126 | $downstream_origin = getDownstreamOrigin(); 127 | print 128 | << 130 | 131 | 132 | 133 | 134 | 135 | EOF; 136 | exit(); 137 | } 138 | 139 | $client = new http\Client(); 140 | $client->setOptions( 141 | [ 142 | 'connecttimeout' => Conf::$proxy_http_request_connecttimeout, 143 | 'dns_cache_timeout' => Conf::$proxy_http_request_dns_cache_timeout, 144 | 'retrycount' => Conf::$proxy_http_request_retrycount, 145 | 'timeout' => Conf::$proxy_http_request_timeout 146 | ]); 147 | $client->enqueue($request)->send(); 148 | $response = new ProxyHttpResponse($client->getResponse(), $request); 149 | 150 | $body = $response->getBody(); 151 | $headers = $response->getHeaders(); 152 | 153 | // Default - can be overriden below. 154 | $headers['X-Frame-Options'] = 'SAMEORIGIN'; 155 | 156 | if (getDownstreamOrigin()) { 157 | $headers['Access-Control-Allow-Origin'] = getDownstreamOrigin(); 158 | 159 | // See http://stackoverflow.com/questions/12409600/error-request-header-field-content-type-is-not-allowed-by-access-control-allow. 160 | $headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept'; 161 | 162 | $headers['X-Frame-Options'] = 'ALLOW-FROM ' . getDownstreamOrigin(); 163 | } 164 | 165 | header($response->getResponseInfo()); 166 | foreach ($headers as $key => $values) { 167 | 168 | // Don't overwrite security headers. 169 | if (isset($required_security_headers[$key])) { 170 | continue; 171 | } 172 | 173 | if (! is_array(($values))) { 174 | $values = array( 175 | $values 176 | ); 177 | } 178 | 179 | foreach ($values as $i => $value) { 180 | header($key . ': ' . $value, ($i == 0)); 181 | } 182 | } 183 | 184 | print $body; -------------------------------------------------------------------------------- /public/main.inc: -------------------------------------------------------------------------------- 1 | 'Loading...', 26 | 'if_website_fails' => 'If the website fails to load, you may be able to find another 27 | mirror URL here:', 28 | 'if_website_fails_top' => 'If the website fails to load, you may be able to find another 29 | mirror URL on {{alt_url_collection_links}}.', 30 | 'or' => 'or' 31 | ); 32 | 33 | private static $alt_base_urls = array(), $alt_url_collections = array(); 34 | 35 | // Manually set charset. 36 | private static $charset; 37 | 38 | // If a part of the website uses a separate base URL. 39 | private static $base_url_suffix = ''; 40 | 41 | // Shown on the cached page while the content is loading. 42 | private static $html_body_appendix = ''; 43 | 44 | private static $website_title; 45 | 46 | public static function addAltBaseUrl($alt_base_url) 47 | { 48 | self::$alt_base_urls[] = $alt_base_url; 49 | } 50 | 51 | public static function addAltBaseUrls($alt_base_urls) 52 | { 53 | foreach ($alt_base_urls as $alt_base_url) { 54 | self::addAltBaseUrl($alt_base_url); 55 | } 56 | } 57 | 58 | public static function addAltUrlCollection($alt_url_collection) 59 | { 60 | self::$alt_url_collections[] = $alt_url_collection; 61 | } 62 | 63 | public static function addAltUrlCollections($alt_url_collections) 64 | { 65 | foreach ($alt_url_collections as $alt_url_collection) { 66 | self::addAltUrlCollection($alt_url_collection); 67 | } 68 | } 69 | 70 | public static function addUrlsFromConfDir() 71 | { 72 | $alt_base_urls = file(__DIR__ . '/conf/alt_base_urls.txt', 73 | FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 74 | self::addAltBaseUrls($alt_base_urls); 75 | $alt_url_collections = file(__DIR__ . '/conf/alt_url_collections.txt', 76 | FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES); 77 | self::addAltUrlCollections($alt_url_collections); 78 | } 79 | 80 | public static function appendToHtmlBody($str) 81 | { 82 | self::$html_body_appendix .= $str; 83 | } 84 | 85 | public static function getAltBaseUrls() 86 | { 87 | return self::$alt_base_urls; 88 | } 89 | 90 | public static function getBaseTag() 91 | { 92 | return ''; 94 | } 95 | 96 | // Guess the current base URL. 97 | public static function getBaseUrl($append_suffix = false) 98 | { 99 | $candidates = array(); 100 | 101 | if (isset($_GET[self::QUERY_STRING_PARAM_NAME])) { 102 | $url = substr($_GET[self::QUERY_STRING_PARAM_NAME], 1); 103 | $candidates[] = $url; 104 | } 105 | 106 | if (isset($_SERVER['HTTP_ORIGIN'])) { 107 | $candidates[] = $_SERVER['HTTP_ORIGIN']; 108 | } 109 | 110 | if (isset($_SERVER['HTTP_REFERER'])) { 111 | $candidates[] = $_SERVER['HTTP_REFERER']; 112 | } 113 | 114 | // Default fallback. 115 | $base_url = self::$alt_base_urls[0]; 116 | 117 | foreach ($candidates as $candidate) { 118 | foreach (self::$alt_base_urls as $alt_base_url) { 119 | if ($candidate && startsWith($candidate, $alt_base_url)) { 120 | $base_url = $alt_base_url; 121 | } 122 | } 123 | } 124 | 125 | if ($append_suffix) { 126 | $base_url .= self::$base_url_suffix; 127 | } 128 | 129 | return $base_url; 130 | } 131 | 132 | public static function getOutputType() 133 | { 134 | static $output_type; 135 | 136 | if (! isset($output_type)) { 137 | $output_type = isset($_GET[self::QUERY_STRING_PARAM_NAME]) ? $_GET[self::QUERY_STRING_PARAM_NAME][0] : NULL; 138 | } 139 | 140 | return $output_type; 141 | } 142 | 143 | // Because we append a custom query string parameter, the script may want to access 144 | // the "original" URI, with the custom query string parameter removed. 145 | public static function getRequestUriWithoutQueryStringParam() 146 | { 147 | $uri = $_SERVER['REQUEST_URI']; 148 | if (! isset($_GET[self::QUERY_STRING_PARAM_NAME])) { 149 | return $uri; 150 | } 151 | 152 | $get_copy = $_GET; 153 | unset($get_copy[self::QUERY_STRING_PARAM_NAME]); 154 | 155 | // If JSONP, remove other parameters added by jQuery. 156 | if (self::getOutputType() == self::OUTPUT_TYPE_JSONP) { 157 | if (isset($get_copy['callback'])) { 158 | unset($get_copy['callback']); 159 | } 160 | if (isset($get_copy['_'])) { 161 | unset($get_copy['_']); 162 | } 163 | } 164 | 165 | $uri_components = parse_url($uri); 166 | $uri = $uri_components['path']; 167 | 168 | if ($get_copy) { 169 | $uri .= '?' . http_build_query($get_copy); 170 | } 171 | 172 | if (isset($uri_components['fragment'])) { 173 | $uri .= '#' . $uri_components['fragment']; 174 | } 175 | 176 | return $uri; 177 | } 178 | 179 | public static function injectBaseTag(&$html) 180 | { 181 | // Insert base tag, unless there already is one. 182 | if (stripos($html, '', 189 | '', 190 | 191 | // If no head tag, insert after body tag instead. Yes, this means the HTML is invalid. But 192 | // adding a head tag to the body segment works too. 193 | '', 194 | '' 195 | ); 196 | 197 | $base_tag_injected = false; 198 | foreach ($head_tags as $head_tag) { 199 | $html = str_replace($head_tag, $head_tag . $base_tag, $html, 200 | $count); 201 | if ($count > 0) { 202 | $base_tag_injected = true; 203 | break; 204 | } 205 | } 206 | 207 | // For even more invalid HTML (no head tag, no body tag), just append base tag to start of doc. 208 | if (! $base_tag_injected) { 209 | $html = $base_tag . "\n" . $html; 210 | } 211 | } 212 | } 213 | 214 | // Main activity. 215 | public static function run() 216 | { 217 | /* 218 | * Normal request. Substitute the response with our own page. 219 | */ 220 | if (! isset($_GET[self::QUERY_STRING_PARAM_NAME])) { 221 | 222 | $iframe_src = $_SERVER['REQUEST_URI']; 223 | if ($_SERVER['QUERY_STRING']) { 224 | $iframe_src .= '&'; 225 | } else { 226 | $iframe_src .= '?'; 227 | } 228 | 229 | $iframe_src .= self::QUERY_STRING_PARAM_NAME . '=' . 230 | self::OUTPUT_TYPE_IFRAME; 231 | 232 | $request_path_depth = count( 233 | explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))); 234 | $script_path_depth = count(explode('/', $_SERVER['SCRIPT_NAME'])); 235 | $rwb_path_relative_to_request_path = str_repeat('../', 236 | $request_path_depth - $script_path_depth) . 'rwb'; 237 | 238 | require 'substitute-page.php'; 239 | exit(); 240 | } 241 | 242 | if (self::getOutputType() == self::OUTPUT_TYPE_JSONP) { 243 | 244 | // Output header now since other header output might block it later. 245 | header('Content-Type: application/javascript'); 246 | } 247 | 248 | // Turn on output buffer to capture all output. 249 | ob_start(); 250 | 251 | // Make this run after all output is completed. 252 | register_shutdown_function( 253 | function () 254 | { 255 | 256 | $html = ob_get_clean(); 257 | 258 | RedirectWhenBlockedFull::injectBaseTag($html); 259 | 260 | /* 261 | * This request comes from another base url (mirror or source host). 262 | * We take the normal output and turn it into a jsonp response. 263 | */ 264 | if (RedirectWhenBlockedFull::getOutputType() == 265 | RedirectWhenBlockedFull::OUTPUT_TYPE_JSONP) { 266 | 267 | print 268 | self::getJsonpCallbackName() . '(' . json_encode( 269 | array( 270 | 'html' => mb_convert_encoding_plus($html, 271 | 'UTF-8', 272 | RedirectWhenBlockedFull::getCharset($html)) 273 | )) . ')'; 274 | } 275 | 276 | else { 277 | print $html; 278 | } 279 | }); 280 | } 281 | 282 | public static function setBaseUrlSuffix($base_url_suffix) 283 | { 284 | self::$base_url_suffix = $base_url_suffix; 285 | } 286 | 287 | public static function setCharset($charset) 288 | { 289 | self::$charset = $charset; 290 | } 291 | 292 | public static function setWebsiteTitle($website_title) 293 | { 294 | self::$website_title = $website_title; 295 | } 296 | 297 | private static function getCharset($html) 298 | { 299 | if (isset(self::$charset) && self::$charset) { 300 | return self::$charset; 301 | } 302 | 303 | if (preg_match('/charset=([^\'"]+)/', $html, $match)) { 304 | return $match[1]; 305 | } 306 | } 307 | 308 | private static function getJsonpCallbackName() 309 | { 310 | if (isset($_GET['callback'])) { 311 | if (preg_match('/^' . self::JSONP_CALLBACK_BASENAME . '\d+$/', 312 | $_GET['callback'])) { 313 | return $_GET['callback']; 314 | } 315 | } 316 | 317 | // callback argument missing or not valid. fallback to default one. 318 | return self::JSONP_CALLBACK_BASENAME . '1'; 319 | } 320 | 321 | private static function getText($key) { 322 | if(!isset(self::$translatable_text[$key])) { 323 | return ''; 324 | } 325 | 326 | $text = self::$translatable_text[$key]; 327 | 328 | // Magic replacements. 329 | if(strpos($text, '{{alt_url_collection_links}}') !== false) { 330 | $alt_url_collection_links = array(); 331 | foreach(self::$alt_url_collections as $url) { 332 | $domain = parse_url($url, PHP_URL_HOST); 333 | list($domain_without_tld) = explode('.', $domain, 2); 334 | $alt_url_collection_links[] = '' . $domain_without_tld . ''; 335 | } 336 | $alt_url_collection_links_str = implode(' ' . self::$translatable_text['or'] . ' ', $alt_url_collection_links); 337 | $text = str_replace('{{alt_url_collection_links}}', $alt_url_collection_links_str, $text); 338 | } 339 | 340 | return $text; 341 | } 342 | } -------------------------------------------------------------------------------- /public/rwb/conf/alt_base_urls.txt: -------------------------------------------------------------------------------- 1 | http://localhost/website-mirror-by-proxy/public/ 2 | http://wmbp1.lo.cal/website-mirror-by-proxy/public/ 3 | http://wmbp2.lo.cal/website-mirror-by-proxy/public/ 4 | http://wmbp3.lo.cal/website-mirror-by-proxy/public/ -------------------------------------------------------------------------------- /public/rwb/conf/alt_url_collections.txt: -------------------------------------------------------------------------------- 1 | https://github.com/greatfire/wiki 2 | https://bitbucket.org/greatfire/wiki -------------------------------------------------------------------------------- /public/rwb/conf/code_update_timestamp.txt: -------------------------------------------------------------------------------- 1 | # Update this file when the outside of RWB changes to force 2 | # browsers to reload their cache. Changes to code inside RWB plus 3 | # changes to data in conf directory are automatically managed. 4 | 1420774435 -------------------------------------------------------------------------------- /public/rwb/multibyte.inc: -------------------------------------------------------------------------------- 1 | 3 | 4 | jquery-1.11.1.min.js 5 | 6 | NETWORK: 7 | * 8 | -------------------------------------------------------------------------------- /public/rwb/rwb.appcache.functions.inc: -------------------------------------------------------------------------------- 1 | strlen($str)) { 15 | return false; 16 | } 17 | 18 | return strcasecmp(substr($str, 0, strlen($needle)), $needle) === 0; 19 | } -------------------------------------------------------------------------------- /public/rwb/substitute-page.css: -------------------------------------------------------------------------------- 1 | html, body { 2 | margin: 0; 3 | padding: 0; 4 | } 5 | 6 | p { 7 | text-align: center; 8 | } 9 | 10 | ul { 11 | border: thin solid #ddd; 12 | margin: auto; 13 | padding: 5px; 14 | width: 300px; 15 | } 16 | 17 | li { 18 | margin-left: 50px; 19 | } 20 | 21 | h1 { 22 | color: #aaa; 23 | text-align: center; 24 | } 25 | 26 | div.top { 27 | color: #222; 28 | font-size: 90%; 29 | padding: 5px; 30 | text-align: center; 31 | } 32 | 33 | iframe { 34 | border: 0; 35 | margin: 0; 36 | overflow: hidden; 37 | padding: 0; 38 | width: 100%; 39 | padding: 0; 40 | } -------------------------------------------------------------------------------- /public/rwb/substitute-page.js: -------------------------------------------------------------------------------- 1 | var done = false; 2 | 3 | function iframeLoaded($iframe) { 4 | if($iframe.data('hasLoaded') === true) { 5 | console.log('iframe already loaded'); 6 | return; 7 | } 8 | 9 | done = true; 10 | 11 | console.log('iframe loaded'); 12 | $iframe.data('hasLoaded', true); 13 | $('div').html(if_website_fails_top); 14 | $('div').addClass('top'); 15 | 16 | manageIframe($iframe); 17 | setInterval(function() { 18 | try { 19 | manageIframe($iframe); 20 | } catch (err) { 21 | } 22 | }, 1000); 23 | } 24 | 25 | function manageIframe($iframe) { 26 | if($iframe.contents().find('title').text()) { 27 | document.title = $iframe.contents().find('title').text(); 28 | } 29 | 30 | if($iframe.contents().find('head').length > 0 && $iframe.contents().find('head base').length == 0) { 31 | $iframe.contents().find('head').prepend($('')); 32 | } 33 | 34 | if($iframe.contents().find('head base').attr('target') != window.name) { 35 | $iframe.contents().find('head base').attr('target', window.name); 36 | } 37 | 38 | // Set height. 39 | var targetHeight = $(window).height(); 40 | if($iframe[0].contentWindow.window != null && $iframe[0].contentWindow.window.document.body != null) { 41 | targetHeight = Math.max( 42 | targetHeight, 43 | $iframe[0].contentWindow.window.document.body.scrollHeight 44 | ); 45 | } 46 | 47 | var actualHeight = $iframe.height() 48 | + parseInt($iframe.contents().find('body').css('margin-top')) 49 | + parseInt($iframe.contents().find('body').css('padding-top')) 50 | + parseInt($iframe.contents().find('body').css('padding-bottom')) 51 | + parseInt($iframe.contents().find('body').css('margin-bottom')); 52 | 53 | if(targetHeight > actualHeight || targetHeight < (actualHeight - 100)) { 54 | $iframe.height(targetHeight + 10); 55 | } 56 | 57 | // Set width. 58 | var targetWidth = $(window).width(); 59 | if($iframe[0].contentWindow.window != null && $iframe[0].contentWindow.window.document.body != null) { 60 | targetWidth = Math.max( 61 | targetWidth, 62 | $iframe[0].contentWindow.window.document.body.scrollWidth 63 | ); 64 | } 65 | 66 | var actualWidth = $iframe.width() 67 | + parseInt($iframe.contents().find('body').css('margin-left')) 68 | + parseInt($iframe.contents().find('body').css('padding-left')) 69 | + parseInt($iframe.contents().find('body').css('padding-right')) 70 | + parseInt($iframe.contents().find('body').css('margin-right')); 71 | 72 | if(targetWidth > actualWidth || targetWidth < (actualWidth - 100)) { 73 | $iframe.width(targetWidth + 10); 74 | } 75 | } 76 | 77 | if (!window.console) { 78 | console = { log : function() {} }; 79 | } 80 | 81 | if (typeof String.prototype.startsWith != 'function') { 82 | String.prototype.startsWith = function (str){ 83 | return this.lastIndexOf(str, 0) === 0; 84 | }; 85 | } 86 | 87 | var base_url = ""; 88 | var relative_url = ""; 89 | for(var i in alt_base_urls) { 90 | if(window.location.href.startsWith(alt_base_urls[i])) { 91 | base_url = alt_base_urls[i]; 92 | relative_url = window.location.href.substring(alt_base_urls[i].length); 93 | break; 94 | } 95 | } 96 | 97 | $('iframe').height($(window).height()); 98 | 99 | var ifrInt = setInterval(function() { 100 | if($('iframe').contents().find('body *:first').length > 0) { 101 | iframeLoaded($('iframe')); 102 | clearInterval(ifrInt); 103 | } 104 | }, 300); 105 | 106 | setTimeout(function() { 107 | if(!done) { 108 | console.log('emergency!'); 109 | $('li a').each(function() { 110 | window.location = $(this).attr('href'); 111 | }); 112 | } 113 | }, 20000); 114 | 115 | $('iframe').load(function() { 116 | iframeLoaded($(this)); 117 | }); 118 | 119 | for(var i in alt_base_urls) { 120 | (function(alt_base_url) { 121 | if(window.location.href.startsWith(alt_base_url)) { 122 | return; 123 | } 124 | 125 | var alt_url = alt_base_url + relative_url; 126 | 127 | var alt_url_parser = document.createElement('a'); 128 | alt_url_parser.href = alt_url; 129 | if(alt_url_parser.search) { 130 | alt_url += '&'; 131 | } else { 132 | alt_url += '?'; 133 | } 134 | alt_url += get_param_name + '=' + output_type_jsonp + encodeURIComponent(alt_base_url); 135 | 136 | $.ajax({ 137 | dataType: 'jsonp', 138 | url: alt_url, 139 | cache: true, 140 | jsonpCallback: jsonp_callback_basename + i 141 | }).success(function(data) { 142 | if(!done && typeof data.html !== 'undefined') { 143 | done = true; 144 | console.log(alt_url + ' succeeded'); 145 | $iframe = $('iframe').clone(); 146 | $('iframe').remove(); 147 | $iframe.attr('src', ''); 148 | $('body').append($iframe); 149 | 150 | var iframeDoc = $iframe[0].contentDocument || $iframe[0].contentWindow.document; 151 | iframeDoc.open(); 152 | iframeDoc.write(data.html); 153 | iframeDoc.close(); 154 | 155 | iframeLoaded($iframe); 156 | } 157 | }); 158 | })(alt_base_urls[i]); 159 | } -------------------------------------------------------------------------------- /public/rwb/substitute-page.php: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 8 | <?php print self::$website_title ?> 9 | '; require 'substitute-page.css'; print ''; ?> 10 | 16 | 17 | 18 |
19 |

20 |

21 |

22 | 23 |
    24 | 25 |
  • 26 | 27 |
28 | 29 |
30 | 33 | 35 | 53 | 54 | 55 | -------------------------------------------------------------------------------- /public/simple_html_dom.php: -------------------------------------------------------------------------------- 1 | size is the "real" number of bytes the dom was created from. 18 | * but for most purposes, it's a really good estimation. 19 | * Paperg - Added the forceTagsClosed to the dom constructor. Forcing tags closed is great for malformed html, but it CAN lead to parsing errors. 20 | * Allow the user to tell us how much they trust the html. 21 | * Paperg add the text and plaintext to the selectors for the find syntax. plaintext implies text in the innertext of a node. text implies that the tag is a text node. 22 | * This allows for us to find tags based on the text they contain. 23 | * Create find_ancestor_tag to see if a tag is - at any level - inside of another specific tag. 24 | * Paperg: added parse_charset so that we know about the character set of the source document. 25 | * NOTE: If the user's system has a routine called get_last_retrieve_url_contents_content_type availalbe, we will assume it's returning the content-type header from the 26 | * last transfer or curl_exec, and we will parse that and use it in preference to any other method of charset detection. 27 | * 28 | * Found infinite loop in the case of broken html in restore_noise. Rewrote to protect from that. 29 | * PaperG (John Schlick) Added get_display_size for "IMG" tags. 30 | * 31 | * Licensed under The MIT License 32 | * Redistributions of files must retain the above copyright notice. 33 | * 34 | * @author S.C. Chen 35 | * @author John Schlick 36 | * @author Rus Carroll 37 | * @version 1.5 ($Rev: 210 $) 38 | * @package PlaceLocalInclude 39 | * @subpackage simple_html_dom 40 | */ 41 | 42 | /** 43 | * All of the Defines for the classes below. 44 | * @author S.C. Chen 45 | */ 46 | define('HDOM_TYPE_ELEMENT', 1); 47 | define('HDOM_TYPE_COMMENT', 2); 48 | define('HDOM_TYPE_TEXT', 3); 49 | define('HDOM_TYPE_ENDTAG', 4); 50 | define('HDOM_TYPE_ROOT', 5); 51 | define('HDOM_TYPE_UNKNOWN', 6); 52 | define('HDOM_QUOTE_DOUBLE', 0); 53 | define('HDOM_QUOTE_SINGLE', 1); 54 | define('HDOM_QUOTE_NO', 3); 55 | define('HDOM_INFO_BEGIN', 0); 56 | define('HDOM_INFO_END', 1); 57 | define('HDOM_INFO_QUOTE', 2); 58 | define('HDOM_INFO_SPACE', 3); 59 | define('HDOM_INFO_TEXT', 4); 60 | define('HDOM_INFO_INNER', 5); 61 | define('HDOM_INFO_OUTER', 6); 62 | define('HDOM_INFO_ENDSPACE',7); 63 | define('DEFAULT_TARGET_CHARSET', 'UTF-8'); 64 | define('DEFAULT_BR_TEXT', "\r\n"); 65 | define('DEFAULT_SPAN_TEXT', " "); 66 | define('MAX_FILE_SIZE', 600000); 67 | // helper functions 68 | // ----------------------------------------------------------------------------- 69 | // get html dom from file 70 | // $maxlen is defined in the code as PHP_STREAM_COPY_ALL which is defined as -1. 71 | function file_get_html($url, $use_include_path = false, $context=null, $offset = -1, $maxLen=-1, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT) 72 | { 73 | // We DO force the tags to be terminated. 74 | $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText); 75 | // For sourceforge users: uncomment the next line and comment the retreive_url_contents line 2 lines down if it is not already done. 76 | $contents = file_get_contents($url, $use_include_path, $context, $offset); 77 | // Paperg - use our own mechanism for getting the contents as we want to control the timeout. 78 | //$contents = retrieve_url_contents($url); 79 | if (empty($contents) || strlen($contents) > MAX_FILE_SIZE) 80 | { 81 | return false; 82 | } 83 | // The second parameter can force the selectors to all be lowercase. 84 | $dom->load($contents, $lowercase, $stripRN); 85 | return $dom; 86 | } 87 | 88 | // get html dom from string 89 | function str_get_html($str, $lowercase=true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT) 90 | { 91 | $dom = new simple_html_dom(null, $lowercase, $forceTagsClosed, $target_charset, $stripRN, $defaultBRText, $defaultSpanText); 92 | if (empty($str) || strlen($str) > MAX_FILE_SIZE) 93 | { 94 | $dom->clear(); 95 | return false; 96 | } 97 | $dom->load($str, $lowercase, $stripRN); 98 | return $dom; 99 | } 100 | 101 | // dump html dom tree 102 | function dump_html_tree($node, $show_attr=true, $deep=0) 103 | { 104 | $node->dump($node); 105 | } 106 | 107 | 108 | /** 109 | * simple html dom node 110 | * PaperG - added ability for "find" routine to lowercase the value of the selector. 111 | * PaperG - added $tag_start to track the start position of the tag in the total byte index 112 | * 113 | * @package PlaceLocalInclude 114 | */ 115 | class simple_html_dom_node 116 | { 117 | public $nodetype = HDOM_TYPE_TEXT; 118 | public $tag = 'text'; 119 | public $attr = array(); 120 | public $children = array(); 121 | public $nodes = array(); 122 | public $parent = null; 123 | // The "info" array - see HDOM_INFO_... for what each element contains. 124 | public $_ = array(); 125 | public $tag_start = 0; 126 | private $dom = null; 127 | 128 | function __construct($dom) 129 | { 130 | $this->dom = $dom; 131 | $dom->nodes[] = $this; 132 | } 133 | 134 | function __destruct() 135 | { 136 | $this->clear(); 137 | } 138 | 139 | function __toString() 140 | { 141 | return $this->outertext(); 142 | } 143 | 144 | // clean up memory due to php5 circular references memory leak... 145 | function clear() 146 | { 147 | $this->dom = null; 148 | $this->nodes = null; 149 | $this->parent = null; 150 | $this->children = null; 151 | } 152 | 153 | // dump node's tree 154 | function dump($show_attr=true, $deep=0) 155 | { 156 | $lead = str_repeat(' ', $deep); 157 | 158 | echo $lead.$this->tag; 159 | if ($show_attr && count($this->attr)>0) 160 | { 161 | echo '('; 162 | foreach ($this->attr as $k=>$v) 163 | echo "[$k]=>\"".$this->$k.'", '; 164 | echo ')'; 165 | } 166 | echo "\n"; 167 | 168 | if ($this->nodes) 169 | { 170 | foreach ($this->nodes as $c) 171 | { 172 | $c->dump($show_attr, $deep+1); 173 | } 174 | } 175 | } 176 | 177 | 178 | // Debugging function to dump a single dom node with a bunch of information about it. 179 | function dump_node($echo=true) 180 | { 181 | 182 | $string = $this->tag; 183 | if (count($this->attr)>0) 184 | { 185 | $string .= '('; 186 | foreach ($this->attr as $k=>$v) 187 | { 188 | $string .= "[$k]=>\"".$this->$k.'", '; 189 | } 190 | $string .= ')'; 191 | } 192 | if (count($this->_)>0) 193 | { 194 | $string .= ' $_ ('; 195 | foreach ($this->_ as $k=>$v) 196 | { 197 | if (is_array($v)) 198 | { 199 | $string .= "[$k]=>("; 200 | foreach ($v as $k2=>$v2) 201 | { 202 | $string .= "[$k2]=>\"".$v2.'", '; 203 | } 204 | $string .= ")"; 205 | } else { 206 | $string .= "[$k]=>\"".$v.'", '; 207 | } 208 | } 209 | $string .= ")"; 210 | } 211 | 212 | if (isset($this->text)) 213 | { 214 | $string .= " text: (" . $this->text . ")"; 215 | } 216 | 217 | $string .= " HDOM_INNER_INFO: '"; 218 | if (isset($node->_[HDOM_INFO_INNER])) 219 | { 220 | $string .= $node->_[HDOM_INFO_INNER] . "'"; 221 | } 222 | else 223 | { 224 | $string .= ' NULL '; 225 | } 226 | 227 | $string .= " children: " . count($this->children); 228 | $string .= " nodes: " . count($this->nodes); 229 | $string .= " tag_start: " . $this->tag_start; 230 | $string .= "\n"; 231 | 232 | if ($echo) 233 | { 234 | echo $string; 235 | return; 236 | } 237 | else 238 | { 239 | return $string; 240 | } 241 | } 242 | 243 | // returns the parent of node 244 | // If a node is passed in, it will reset the parent of the current node to that one. 245 | function parent($parent=null) 246 | { 247 | // I am SURE that this doesn't work properly. 248 | // It fails to unset the current node from it's current parents nodes or children list first. 249 | if ($parent !== null) 250 | { 251 | $this->parent = $parent; 252 | $this->parent->nodes[] = $this; 253 | $this->parent->children[] = $this; 254 | } 255 | 256 | return $this->parent; 257 | } 258 | 259 | // verify that node has children 260 | function has_child() 261 | { 262 | return !empty($this->children); 263 | } 264 | 265 | // returns children of node 266 | function children($idx=-1) 267 | { 268 | if ($idx===-1) 269 | { 270 | return $this->children; 271 | } 272 | if (isset($this->children[$idx])) 273 | { 274 | return $this->children[$idx]; 275 | } 276 | return null; 277 | } 278 | 279 | // returns the first child of node 280 | function first_child() 281 | { 282 | if (count($this->children)>0) 283 | { 284 | return $this->children[0]; 285 | } 286 | return null; 287 | } 288 | 289 | // returns the last child of node 290 | function last_child() 291 | { 292 | if (($count=count($this->children))>0) 293 | { 294 | return $this->children[$count-1]; 295 | } 296 | return null; 297 | } 298 | 299 | // returns the next sibling of node 300 | function next_sibling() 301 | { 302 | if ($this->parent===null) 303 | { 304 | return null; 305 | } 306 | 307 | $idx = 0; 308 | $count = count($this->parent->children); 309 | while ($idx<$count && $this!==$this->parent->children[$idx]) 310 | { 311 | ++$idx; 312 | } 313 | if (++$idx>=$count) 314 | { 315 | return null; 316 | } 317 | return $this->parent->children[$idx]; 318 | } 319 | 320 | // returns the previous sibling of node 321 | function prev_sibling() 322 | { 323 | if ($this->parent===null) return null; 324 | $idx = 0; 325 | $count = count($this->parent->children); 326 | while ($idx<$count && $this!==$this->parent->children[$idx]) 327 | ++$idx; 328 | if (--$idx<0) return null; 329 | return $this->parent->children[$idx]; 330 | } 331 | 332 | // function to locate a specific ancestor tag in the path to the root. 333 | function find_ancestor_tag($tag) 334 | { 335 | global $debug_object; 336 | if (is_object($debug_object)) { $debug_object->debug_log_entry(1); } 337 | 338 | // Start by including ourselves in the comparison. 339 | $returnDom = $this; 340 | 341 | while (!is_null($returnDom)) 342 | { 343 | if (is_object($debug_object)) { $debug_object->debug_log(2, "Current tag is: " . $returnDom->tag); } 344 | 345 | if ($returnDom->tag == $tag) 346 | { 347 | break; 348 | } 349 | $returnDom = $returnDom->parent; 350 | } 351 | return $returnDom; 352 | } 353 | 354 | // get dom node's inner html 355 | function innertext() 356 | { 357 | if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER]; 358 | if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); 359 | 360 | $ret = ''; 361 | foreach ($this->nodes as $n) 362 | $ret .= $n->outertext(); 363 | return $ret; 364 | } 365 | 366 | // get dom node's outer text (with tag) 367 | function outertext() 368 | { 369 | global $debug_object; 370 | if (is_object($debug_object)) 371 | { 372 | $text = ''; 373 | if ($this->tag == 'text') 374 | { 375 | if (!empty($this->text)) 376 | { 377 | $text = " with text: " . $this->text; 378 | } 379 | } 380 | $debug_object->debug_log(1, 'Innertext of tag: ' . $this->tag . $text); 381 | } 382 | 383 | if ($this->tag==='root') return $this->innertext(); 384 | 385 | // trigger callback 386 | if ($this->dom && $this->dom->callback!==null) 387 | { 388 | call_user_func_array($this->dom->callback, array($this)); 389 | } 390 | 391 | if (isset($this->_[HDOM_INFO_OUTER])) return $this->_[HDOM_INFO_OUTER]; 392 | if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); 393 | 394 | // render begin tag 395 | if ($this->dom && $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]) 396 | { 397 | $ret = $this->dom->nodes[$this->_[HDOM_INFO_BEGIN]]->makeup(); 398 | } else { 399 | $ret = ""; 400 | } 401 | 402 | // render inner text 403 | if (isset($this->_[HDOM_INFO_INNER])) 404 | { 405 | // If it's a br tag... don't return the HDOM_INNER_INFO that we may or may not have added. 406 | if ($this->tag != "br") 407 | { 408 | $ret .= $this->_[HDOM_INFO_INNER]; 409 | } 410 | } else { 411 | if ($this->nodes) 412 | { 413 | foreach ($this->nodes as $n) 414 | { 415 | $ret .= $this->convert_text($n->outertext()); 416 | } 417 | } 418 | } 419 | 420 | // render end tag 421 | if (isset($this->_[HDOM_INFO_END]) && $this->_[HDOM_INFO_END]!=0) 422 | $ret .= 'tag.'>'; 423 | return $ret; 424 | } 425 | 426 | // get dom node's plain text 427 | function text() 428 | { 429 | if (isset($this->_[HDOM_INFO_INNER])) return $this->_[HDOM_INFO_INNER]; 430 | switch ($this->nodetype) 431 | { 432 | case HDOM_TYPE_TEXT: return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); 433 | case HDOM_TYPE_COMMENT: return ''; 434 | case HDOM_TYPE_UNKNOWN: return ''; 435 | } 436 | if (strcasecmp($this->tag, 'script')===0) return ''; 437 | if (strcasecmp($this->tag, 'style')===0) return ''; 438 | 439 | $ret = ''; 440 | // In rare cases, (always node type 1 or HDOM_TYPE_ELEMENT - observed for some span tags, and some p tags) $this->nodes is set to NULL. 441 | // NOTE: This indicates that there is a problem where it's set to NULL without a clear happening. 442 | // WHY is this happening? 443 | if (!is_null($this->nodes)) 444 | { 445 | foreach ($this->nodes as $n) 446 | { 447 | $ret .= $this->convert_text($n->text()); 448 | } 449 | 450 | // If this node is a span... add a space at the end of it so multiple spans don't run into each other. This is plaintext after all. 451 | if ($this->tag == "span") 452 | { 453 | $ret .= $this->dom->default_span_text; 454 | } 455 | 456 | 457 | } 458 | return $ret; 459 | } 460 | 461 | function xmltext() 462 | { 463 | $ret = $this->innertext(); 464 | $ret = str_ireplace('', '', $ret); 466 | return $ret; 467 | } 468 | 469 | // build node's text with tag 470 | function makeup() 471 | { 472 | // text, comment, unknown 473 | if (isset($this->_[HDOM_INFO_TEXT])) return $this->dom->restore_noise($this->_[HDOM_INFO_TEXT]); 474 | 475 | $ret = '<'.$this->tag; 476 | $i = -1; 477 | 478 | foreach ($this->attr as $key=>$val) 479 | { 480 | ++$i; 481 | 482 | // skip removed attribute 483 | if ($val===null || $val===false) 484 | continue; 485 | 486 | $ret .= $this->_[HDOM_INFO_SPACE][$i][0]; 487 | //no value attr: nowrap, checked selected... 488 | if ($val===true) 489 | $ret .= $key; 490 | else { 491 | switch ($this->_[HDOM_INFO_QUOTE][$i]) 492 | { 493 | case HDOM_QUOTE_DOUBLE: $quote = '"'; break; 494 | case HDOM_QUOTE_SINGLE: $quote = '\''; break; 495 | default: $quote = ''; 496 | } 497 | $ret .= $key.$this->_[HDOM_INFO_SPACE][$i][1].'='.$this->_[HDOM_INFO_SPACE][$i][2].$quote.$val.$quote; 498 | } 499 | } 500 | $ret = $this->dom->restore_noise($ret); 501 | return $ret . $this->_[HDOM_INFO_ENDSPACE] . '>'; 502 | } 503 | 504 | // find elements by css selector 505 | //PaperG - added ability for find to lowercase the value of the selector. 506 | function find($selector, $idx=null, $lowercase=false) 507 | { 508 | $selectors = $this->parse_selector($selector); 509 | if (($count=count($selectors))===0) return array(); 510 | $found_keys = array(); 511 | 512 | // find each selector 513 | for ($c=0; $c<$count; ++$c) 514 | { 515 | // The change on the below line was documented on the sourceforge code tracker id 2788009 516 | // used to be: if (($levle=count($selectors[0]))===0) return array(); 517 | if (($levle=count($selectors[$c]))===0) return array(); 518 | if (!isset($this->_[HDOM_INFO_BEGIN])) return array(); 519 | 520 | $head = array($this->_[HDOM_INFO_BEGIN]=>1); 521 | 522 | // handle descendant selectors, no recursive! 523 | for ($l=0; $l<$levle; ++$l) 524 | { 525 | $ret = array(); 526 | foreach ($head as $k=>$v) 527 | { 528 | $n = ($k===-1) ? $this->dom->root : $this->dom->nodes[$k]; 529 | //PaperG - Pass this optional parameter on to the seek function. 530 | $n->seek($selectors[$c][$l], $ret, $lowercase); 531 | } 532 | $head = $ret; 533 | } 534 | 535 | foreach ($head as $k=>$v) 536 | { 537 | if (!isset($found_keys[$k])) 538 | { 539 | $found_keys[$k] = 1; 540 | } 541 | } 542 | } 543 | 544 | // sort keys 545 | ksort($found_keys); 546 | 547 | $found = array(); 548 | foreach ($found_keys as $k=>$v) 549 | $found[] = $this->dom->nodes[$k]; 550 | 551 | // return nth-element or array 552 | if (is_null($idx)) return $found; 553 | else if ($idx<0) $idx = count($found) + $idx; 554 | return (isset($found[$idx])) ? $found[$idx] : null; 555 | } 556 | 557 | // seek for given conditions 558 | // PaperG - added parameter to allow for case insensitive testing of the value of a selector. 559 | protected function seek($selector, &$ret, $lowercase=false) 560 | { 561 | global $debug_object; 562 | if (is_object($debug_object)) { $debug_object->debug_log_entry(1); } 563 | 564 | list($tag, $key, $val, $exp, $no_key) = $selector; 565 | 566 | // xpath index 567 | if ($tag && $key && is_numeric($key)) 568 | { 569 | $count = 0; 570 | foreach ($this->children as $c) 571 | { 572 | if ($tag==='*' || $tag===$c->tag) { 573 | if (++$count==$key) { 574 | $ret[$c->_[HDOM_INFO_BEGIN]] = 1; 575 | return; 576 | } 577 | } 578 | } 579 | return; 580 | } 581 | 582 | $end = (!empty($this->_[HDOM_INFO_END])) ? $this->_[HDOM_INFO_END] : 0; 583 | if ($end==0) { 584 | $parent = $this->parent; 585 | while (!isset($parent->_[HDOM_INFO_END]) && $parent!==null) { 586 | $end -= 1; 587 | $parent = $parent->parent; 588 | } 589 | $end += $parent->_[HDOM_INFO_END]; 590 | } 591 | 592 | for ($i=$this->_[HDOM_INFO_BEGIN]+1; $i<$end; ++$i) { 593 | $node = $this->dom->nodes[$i]; 594 | 595 | $pass = true; 596 | 597 | if ($tag==='*' && !$key) { 598 | if (in_array($node, $this->children, true)) 599 | $ret[$i] = 1; 600 | continue; 601 | } 602 | 603 | // compare tag 604 | if ($tag && $tag!=$node->tag && $tag!=='*') {$pass=false;} 605 | // compare key 606 | if ($pass && $key) { 607 | if ($no_key) { 608 | if (isset($node->attr[$key])) $pass=false; 609 | } else { 610 | if (($key != "plaintext") && !isset($node->attr[$key])) $pass=false; 611 | } 612 | } 613 | // compare value 614 | if ($pass && $key && $val && $val!=='*') { 615 | // If they have told us that this is a "plaintext" search then we want the plaintext of the node - right? 616 | if ($key == "plaintext") { 617 | // $node->plaintext actually returns $node->text(); 618 | $nodeKeyValue = $node->text(); 619 | } else { 620 | // this is a normal search, we want the value of that attribute of the tag. 621 | $nodeKeyValue = $node->attr[$key]; 622 | } 623 | if (is_object($debug_object)) {$debug_object->debug_log(2, "testing node: " . $node->tag . " for attribute: " . $key . $exp . $val . " where nodes value is: " . $nodeKeyValue);} 624 | 625 | //PaperG - If lowercase is set, do a case insensitive test of the value of the selector. 626 | if ($lowercase) { 627 | $check = $this->match($exp, strtolower($val), strtolower($nodeKeyValue)); 628 | } else { 629 | $check = $this->match($exp, $val, $nodeKeyValue); 630 | } 631 | if (is_object($debug_object)) {$debug_object->debug_log(2, "after match: " . ($check ? "true" : "false"));} 632 | 633 | // handle multiple class 634 | if (!$check && strcasecmp($key, 'class')===0) { 635 | foreach (explode(' ',$node->attr[$key]) as $k) { 636 | // Without this, there were cases where leading, trailing, or double spaces lead to our comparing blanks - bad form. 637 | if (!empty($k)) { 638 | if ($lowercase) { 639 | $check = $this->match($exp, strtolower($val), strtolower($k)); 640 | } else { 641 | $check = $this->match($exp, $val, $k); 642 | } 643 | if ($check) break; 644 | } 645 | } 646 | } 647 | if (!$check) $pass = false; 648 | } 649 | if ($pass) $ret[$i] = 1; 650 | unset($node); 651 | } 652 | // It's passed by reference so this is actually what this function returns. 653 | if (is_object($debug_object)) {$debug_object->debug_log(1, "EXIT - ret: ", $ret);} 654 | } 655 | 656 | protected function match($exp, $pattern, $value) { 657 | global $debug_object; 658 | if (is_object($debug_object)) {$debug_object->debug_log_entry(1);} 659 | 660 | switch ($exp) { 661 | case '=': 662 | return ($value===$pattern); 663 | case '!=': 664 | return ($value!==$pattern); 665 | case '^=': 666 | return preg_match("/^".preg_quote($pattern,'/')."/", $value); 667 | case '$=': 668 | return preg_match("/".preg_quote($pattern,'/')."$/", $value); 669 | case '*=': 670 | if ($pattern[0]=='/') { 671 | return preg_match($pattern, $value); 672 | } 673 | return preg_match("/".$pattern."/i", $value); 674 | } 675 | return false; 676 | } 677 | 678 | protected function parse_selector($selector_string) { 679 | global $debug_object; 680 | if (is_object($debug_object)) {$debug_object->debug_log_entry(1);} 681 | 682 | // pattern of CSS selectors, modified from mootools 683 | // Paperg: Add the colon to the attrbute, so that it properly finds like google does. 684 | // Note: if you try to look at this attribute, yo MUST use getAttribute since $dom->x:y will fail the php syntax check. 685 | // Notice the \[ starting the attbute? and the @? following? This implies that an attribute can begin with an @ sign that is not captured. 686 | // This implies that an html attribute specifier may start with an @ sign that is NOT captured by the expression. 687 | // farther study is required to determine of this should be documented or removed. 688 | // $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is"; 689 | $pattern = "/([\w-:\*]*)(?:\#([\w-]+)|\.([\w-]+))?(?:\[@?(!?[\w-:]+)(?:([!*^$]?=)[\"']?(.*?)[\"']?)?\])?([\/, ]+)/is"; 690 | preg_match_all($pattern, trim($selector_string).' ', $matches, PREG_SET_ORDER); 691 | if (is_object($debug_object)) {$debug_object->debug_log(2, "Matches Array: ", $matches);} 692 | 693 | $selectors = array(); 694 | $result = array(); 695 | //print_r($matches); 696 | 697 | foreach ($matches as $m) { 698 | $m[0] = trim($m[0]); 699 | if ($m[0]==='' || $m[0]==='/' || $m[0]==='//') continue; 700 | // for browser generated xpath 701 | if ($m[1]==='tbody') continue; 702 | 703 | list($tag, $key, $val, $exp, $no_key) = array($m[1], null, null, '=', false); 704 | if (!empty($m[2])) {$key='id'; $val=$m[2];} 705 | if (!empty($m[3])) {$key='class'; $val=$m[3];} 706 | if (!empty($m[4])) {$key=$m[4];} 707 | if (!empty($m[5])) {$exp=$m[5];} 708 | if (!empty($m[6])) {$val=$m[6];} 709 | 710 | // convert to lowercase 711 | if ($this->dom->lowercase) {$tag=strtolower($tag); $key=strtolower($key);} 712 | //elements that do NOT have the specified attribute 713 | if (isset($key[0]) && $key[0]==='!') {$key=substr($key, 1); $no_key=true;} 714 | 715 | $result[] = array($tag, $key, $val, $exp, $no_key); 716 | if (trim($m[7])===',') { 717 | $selectors[] = $result; 718 | $result = array(); 719 | } 720 | } 721 | if (count($result)>0) 722 | $selectors[] = $result; 723 | return $selectors; 724 | } 725 | 726 | function __get($name) 727 | { 728 | if (isset($this->attr[$name])) 729 | { 730 | return $this->convert_text($this->attr[$name]); 731 | } 732 | switch ($name) 733 | { 734 | case 'outertext': return $this->outertext(); 735 | case 'innertext': return $this->innertext(); 736 | case 'plaintext': return $this->text(); 737 | case 'xmltext': return $this->xmltext(); 738 | default: return array_key_exists($name, $this->attr); 739 | } 740 | } 741 | 742 | function __set($name, $value) 743 | { 744 | global $debug_object; 745 | if (is_object($debug_object)) {$debug_object->debug_log_entry(1);} 746 | 747 | switch ($name) 748 | { 749 | case 'outertext': return $this->_[HDOM_INFO_OUTER] = $value; 750 | case 'innertext': 751 | if (isset($this->_[HDOM_INFO_TEXT])) return $this->_[HDOM_INFO_TEXT] = $value; 752 | return $this->_[HDOM_INFO_INNER] = $value; 753 | } 754 | if (!isset($this->attr[$name])) 755 | { 756 | $this->_[HDOM_INFO_SPACE][] = array(' ', '', ''); 757 | $this->_[HDOM_INFO_QUOTE][] = HDOM_QUOTE_DOUBLE; 758 | } 759 | $this->attr[$name] = $value; 760 | } 761 | 762 | function __isset($name) 763 | { 764 | switch ($name) 765 | { 766 | case 'outertext': return true; 767 | case 'innertext': return true; 768 | case 'plaintext': return true; 769 | } 770 | //no value attr: nowrap, checked selected... 771 | return (array_key_exists($name, $this->attr)) ? true : isset($this->attr[$name]); 772 | } 773 | 774 | function __unset($name) { 775 | if (isset($this->attr[$name])) 776 | unset($this->attr[$name]); 777 | } 778 | 779 | // PaperG - Function to convert the text from one character set to another if the two sets are not the same. 780 | function convert_text($text) 781 | { 782 | global $debug_object; 783 | if (is_object($debug_object)) {$debug_object->debug_log_entry(1);} 784 | 785 | $converted_text = $text; 786 | 787 | $sourceCharset = ""; 788 | $targetCharset = ""; 789 | 790 | if ($this->dom) 791 | { 792 | $sourceCharset = strtoupper($this->dom->_charset); 793 | $targetCharset = strtoupper($this->dom->_target_charset); 794 | } 795 | if (is_object($debug_object)) {$debug_object->debug_log(3, "source charset: " . $sourceCharset . " target charaset: " . $targetCharset);} 796 | 797 | if (!empty($sourceCharset) && !empty($targetCharset) && (strcasecmp($sourceCharset, $targetCharset) != 0)) 798 | { 799 | // Check if the reported encoding could have been incorrect and the text is actually already UTF-8 800 | if ((strcasecmp($targetCharset, 'UTF-8') == 0) && ($this->is_utf8($text))) 801 | { 802 | $converted_text = $text; 803 | } 804 | else 805 | { 806 | $converted_text = iconv($sourceCharset, $targetCharset, $text); 807 | } 808 | } 809 | 810 | // Lets make sure that we don't have that silly BOM issue with any of the utf-8 text we output. 811 | if ($targetCharset == 'UTF-8') 812 | { 813 | if (substr($converted_text, 0, 3) == "\xef\xbb\xbf") 814 | { 815 | $converted_text = substr($converted_text, 3); 816 | } 817 | if (substr($converted_text, -3) == "\xef\xbb\xbf") 818 | { 819 | $converted_text = substr($converted_text, 0, -3); 820 | } 821 | } 822 | 823 | return $converted_text; 824 | } 825 | 826 | /** 827 | * Returns true if $string is valid UTF-8 and false otherwise. 828 | * 829 | * @param mixed $str String to be tested 830 | * @return boolean 831 | */ 832 | static function is_utf8($str) 833 | { 834 | $c=0; $b=0; 835 | $bits=0; 836 | $len=strlen($str); 837 | for($i=0; $i<$len; $i++) 838 | { 839 | $c=ord($str[$i]); 840 | if($c > 128) 841 | { 842 | if(($c >= 254)) return false; 843 | elseif($c >= 252) $bits=6; 844 | elseif($c >= 248) $bits=5; 845 | elseif($c >= 240) $bits=4; 846 | elseif($c >= 224) $bits=3; 847 | elseif($c >= 192) $bits=2; 848 | else return false; 849 | if(($i+$bits) > $len) return false; 850 | while($bits > 1) 851 | { 852 | $i++; 853 | $b=ord($str[$i]); 854 | if($b < 128 || $b > 191) return false; 855 | $bits--; 856 | } 857 | } 858 | } 859 | return true; 860 | } 861 | /* 862 | function is_utf8($string) 863 | { 864 | //this is buggy 865 | return (utf8_encode(utf8_decode($string)) == $string); 866 | } 867 | */ 868 | 869 | /** 870 | * Function to try a few tricks to determine the displayed size of an img on the page. 871 | * NOTE: This will ONLY work on an IMG tag. Returns FALSE on all other tag types. 872 | * 873 | * @author John Schlick 874 | * @version April 19 2012 875 | * @return array an array containing the 'height' and 'width' of the image on the page or -1 if we can't figure it out. 876 | */ 877 | function get_display_size() 878 | { 879 | global $debug_object; 880 | 881 | $width = -1; 882 | $height = -1; 883 | 884 | if ($this->tag !== 'img') 885 | { 886 | return false; 887 | } 888 | 889 | // See if there is aheight or width attribute in the tag itself. 890 | if (isset($this->attr['width'])) 891 | { 892 | $width = $this->attr['width']; 893 | } 894 | 895 | if (isset($this->attr['height'])) 896 | { 897 | $height = $this->attr['height']; 898 | } 899 | 900 | // Now look for an inline style. 901 | if (isset($this->attr['style'])) 902 | { 903 | // Thanks to user gnarf from stackoverflow for this regular expression. 904 | $attributes = array(); 905 | preg_match_all("/([\w-]+)\s*:\s*([^;]+)\s*;?/", $this->attr['style'], $matches, PREG_SET_ORDER); 906 | foreach ($matches as $match) { 907 | $attributes[$match[1]] = $match[2]; 908 | } 909 | 910 | // If there is a width in the style attributes: 911 | if (isset($attributes['width']) && $width == -1) 912 | { 913 | // check that the last two characters are px (pixels) 914 | if (strtolower(substr($attributes['width'], -2)) == 'px') 915 | { 916 | $proposed_width = substr($attributes['width'], 0, -2); 917 | // Now make sure that it's an integer and not something stupid. 918 | if (filter_var($proposed_width, FILTER_VALIDATE_INT)) 919 | { 920 | $width = $proposed_width; 921 | } 922 | } 923 | } 924 | 925 | // If there is a width in the style attributes: 926 | if (isset($attributes['height']) && $height == -1) 927 | { 928 | // check that the last two characters are px (pixels) 929 | if (strtolower(substr($attributes['height'], -2)) == 'px') 930 | { 931 | $proposed_height = substr($attributes['height'], 0, -2); 932 | // Now make sure that it's an integer and not something stupid. 933 | if (filter_var($proposed_height, FILTER_VALIDATE_INT)) 934 | { 935 | $height = $proposed_height; 936 | } 937 | } 938 | } 939 | 940 | } 941 | 942 | // Future enhancement: 943 | // Look in the tag to see if there is a class or id specified that has a height or width attribute to it. 944 | 945 | // Far future enhancement 946 | // Look at all the parent tags of this image to see if they specify a class or id that has an img selector that specifies a height or width 947 | // Note that in this case, the class or id will have the img subselector for it to apply to the image. 948 | 949 | // ridiculously far future development 950 | // If the class or id is specified in a SEPARATE css file thats not on the page, go get it and do what we were just doing for the ones on the page. 951 | 952 | $result = array('height' => $height, 953 | 'width' => $width); 954 | return $result; 955 | } 956 | 957 | // camel naming conventions 958 | function getAllAttributes() {return $this->attr;} 959 | function getAttribute($name) {return $this->__get($name);} 960 | function setAttribute($name, $value) {$this->__set($name, $value);} 961 | function hasAttribute($name) {return $this->__isset($name);} 962 | function removeAttribute($name) {$this->__set($name, null);} 963 | function getElementById($id) {return $this->find("#$id", 0);} 964 | function getElementsById($id, $idx=null) {return $this->find("#$id", $idx);} 965 | function getElementByTagName($name) {return $this->find($name, 0);} 966 | function getElementsByTagName($name, $idx=null) {return $this->find($name, $idx);} 967 | function parentNode() {return $this->parent();} 968 | function childNodes($idx=-1) {return $this->children($idx);} 969 | function firstChild() {return $this->first_child();} 970 | function lastChild() {return $this->last_child();} 971 | function nextSibling() {return $this->next_sibling();} 972 | function previousSibling() {return $this->prev_sibling();} 973 | function hasChildNodes() {return $this->has_child();} 974 | function nodeName() {return $this->tag;} 975 | function appendChild($node) {$node->parent($this); return $node;} 976 | 977 | } 978 | 979 | /** 980 | * simple html dom parser 981 | * Paperg - in the find routine: allow us to specify that we want case insensitive testing of the value of the selector. 982 | * Paperg - change $size from protected to public so we can easily access it 983 | * Paperg - added ForceTagsClosed in the constructor which tells us whether we trust the html or not. Default is to NOT trust it. 984 | * 985 | * @package PlaceLocalInclude 986 | */ 987 | class simple_html_dom 988 | { 989 | public $root = null; 990 | public $nodes = array(); 991 | public $callback = null; 992 | public $lowercase = false; 993 | // Used to keep track of how large the text was when we started. 994 | public $original_size; 995 | public $size; 996 | protected $pos; 997 | protected $doc; 998 | protected $char; 999 | protected $cursor; 1000 | protected $parent; 1001 | protected $noise = array(); 1002 | protected $token_blank = " \t\r\n"; 1003 | protected $token_equal = ' =/>'; 1004 | protected $token_slash = " />\r\n\t"; 1005 | protected $token_attr = ' >'; 1006 | // Note that this is referenced by a child node, and so it needs to be public for that node to see this information. 1007 | public $_charset = ''; 1008 | public $_target_charset = ''; 1009 | protected $default_br_text = ""; 1010 | public $default_span_text = ""; 1011 | 1012 | // use isset instead of in_array, performance boost about 30%... 1013 | protected $self_closing_tags = array('img'=>1, 'br'=>1, 'input'=>1, 'meta'=>1, 'link'=>1, 'hr'=>1, 'base'=>1, 'embed'=>1, 'spacer'=>1); 1014 | protected $block_tags = array('root'=>1, 'body'=>1, 'form'=>1, 'div'=>1, 'span'=>1, 'table'=>1); 1015 | // Known sourceforge issue #2977341 1016 | // B tags that are not closed cause us to return everything to the end of the document. 1017 | protected $optional_closing_tags = array( 1018 | 'tr'=>array('tr'=>1, 'td'=>1, 'th'=>1), 1019 | 'th'=>array('th'=>1), 1020 | 'td'=>array('td'=>1), 1021 | 'li'=>array('li'=>1), 1022 | 'dt'=>array('dt'=>1, 'dd'=>1), 1023 | 'dd'=>array('dd'=>1, 'dt'=>1), 1024 | 'dl'=>array('dd'=>1, 'dt'=>1), 1025 | 'p'=>array('p'=>1), 1026 | 'nobr'=>array('nobr'=>1), 1027 | 'b'=>array('b'=>1), 1028 | 'option'=>array('option'=>1), 1029 | ); 1030 | 1031 | function __construct($str=null, $lowercase=true, $forceTagsClosed=true, $target_charset=DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT) 1032 | { 1033 | if ($str) 1034 | { 1035 | if (preg_match("/^http:\/\//i",$str) || is_file($str)) 1036 | { 1037 | $this->load_file($str); 1038 | } 1039 | else 1040 | { 1041 | $this->load($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText); 1042 | } 1043 | } 1044 | // Forcing tags to be closed implies that we don't trust the html, but it can lead to parsing errors if we SHOULD trust the html. 1045 | if (!$forceTagsClosed) { 1046 | $this->optional_closing_array=array(); 1047 | } 1048 | $this->_target_charset = $target_charset; 1049 | } 1050 | 1051 | function __destruct() 1052 | { 1053 | $this->clear(); 1054 | } 1055 | 1056 | // load html from string 1057 | function load($str, $lowercase=true, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT) 1058 | { 1059 | global $debug_object; 1060 | 1061 | // prepare 1062 | $this->prepare($str, $lowercase, $stripRN, $defaultBRText, $defaultSpanText); 1063 | // strip out cdata 1064 | $this->remove_noise("''is", true); 1065 | // strip out comments 1066 | $this->remove_noise("''is"); 1067 | // Per sourceforge http://sourceforge.net/tracker/?func=detail&aid=2949097&group_id=218559&atid=1044037 1068 | // Script tags removal now preceeds style tag removal. 1069 | // strip out