]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Tools.class.php
Merge pull request #634 from wallabag/dev
[github/wallabag/wallabag.git] / inc / poche / Tools.class.php
1 <?php
2 /**
3 * wallabag, self hostable application allowing you to not miss any content anymore
4 *
5 * @category wallabag
6 * @author Nicolas LÅ“uillet <nicolas@loeuillet.org>
7 * @copyright 2013
8 * @license http://www.wtfpl.net/ see COPYING file
9 */
10
11 class Tools
12 {
13 public static function initPhp()
14 {
15 define('START_TIME', microtime(true));
16
17 if (phpversion() < 5) {
18 die(_('Oops, it seems you don\'t have PHP 5.'));
19 }
20
21 error_reporting(E_ALL);
22
23 function stripslashesDeep($value) {
24 return is_array($value)
25 ? array_map('stripslashesDeep', $value)
26 : stripslashes($value);
27 }
28
29 if (get_magic_quotes_gpc()) {
30 $_POST = array_map('stripslashesDeep', $_POST);
31 $_GET = array_map('stripslashesDeep', $_GET);
32 $_COOKIE = array_map('stripslashesDeep', $_COOKIE);
33 }
34
35 ob_start();
36 register_shutdown_function('ob_end_flush');
37 }
38
39 public static function getPocheUrl()
40 {
41 $https = (!empty($_SERVER['HTTPS'])
42 && (strtolower($_SERVER['HTTPS']) == 'on'))
43 || (isset($_SERVER["SERVER_PORT"])
44 && $_SERVER["SERVER_PORT"] == '443') // HTTPS detection.
45 || (isset($_SERVER["SERVER_PORT"]) //Custom HTTPS port detection
46 && $_SERVER["SERVER_PORT"] == SSL_PORT)
47 || (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
48 && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
49
50 $serverport = (!isset($_SERVER["SERVER_PORT"])
51 || $_SERVER["SERVER_PORT"] == '80'
52 || ($https && $_SERVER["SERVER_PORT"] == '443')
53 || ($https && $_SERVER["SERVER_PORT"]==SSL_PORT) //Custom HTTPS port detection
54 ? '' : ':' . $_SERVER["SERVER_PORT"]);
55
56 $scriptname = str_replace('/index.php', '/', $_SERVER["SCRIPT_NAME"]);
57
58 if (!isset($_SERVER["HTTP_HOST"])) {
59 return $scriptname;
60 }
61
62 $host = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']));
63
64 return 'http' . ($https ? 's' : '') . '://'
65 . $host . $serverport . $scriptname;
66 }
67
68 public static function redirect($url = '')
69 {
70 if ($url === '') {
71 $url = (empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']);
72 if (isset($_POST['returnurl'])) {
73 $url = $_POST['returnurl'];
74 }
75 }
76
77 # prevent loop
78 if (empty($url) || parse_url($url, PHP_URL_QUERY) === $_SERVER['QUERY_STRING']) {
79 $url = Tools::getPocheUrl();
80 }
81
82 if (substr($url, 0, 1) !== '?') {
83 $ref = Tools::getPocheUrl();
84 if (substr($url, 0, strlen($ref)) !== $ref) {
85 $url = $ref;
86 }
87 }
88 self::logm('redirect to ' . $url);
89 header('Location: '.$url);
90 exit();
91 }
92
93 public static function getTplFile($view)
94 {
95 $views = array(
96 'install', 'import', 'export', 'config', 'tags',
97 'edit-tags', 'view', 'login', 'error'
98 );
99
100 if (in_array($view, $views)) {
101 return $view . '.twig';
102 }
103
104 return 'home.twig';
105 }
106
107 public static function getFile($url)
108 {
109 $timeout = 15;
110 $useragent = "Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0";
111
112 if (in_array ('curl', get_loaded_extensions())) {
113 # Fetch feed from URL
114 $curl = curl_init();
115 curl_setopt($curl, CURLOPT_URL, $url);
116 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
117 if (!ini_get('open_basedir') && !ini_get('safe_mode')) {
118 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
119 }
120 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
121 curl_setopt($curl, CURLOPT_HEADER, false);
122
123 # for ssl, do not verified certificate
124 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
125 curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE );
126
127 # FeedBurner requires a proper USER-AGENT...
128 curl_setopt($curl, CURL_HTTP_VERSION_1_1, true);
129 curl_setopt($curl, CURLOPT_ENCODING, "gzip, deflate");
130 curl_setopt($curl, CURLOPT_USERAGENT, $useragent);
131
132 $data = curl_exec($curl);
133 $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
134 $httpcodeOK = isset($httpcode) and ($httpcode == 200 or $httpcode == 301);
135 curl_close($curl);
136 } else {
137 # create http context and add timeout and user-agent
138 $context = stream_context_create(
139 array(
140 'http' => array(
141 'timeout' => $timeout,
142 'header' => "User-Agent: " . $useragent,
143 'follow_location' => true
144 ),
145 'ssl' => array(
146 'verify_peer' => false,
147 'allow_self_signed' => true
148 )
149 )
150 );
151
152 # only download page lesser than 4MB
153 $data = @file_get_contents($url, false, $context, -1, 4000000);
154
155 if (isset($http_response_header) and isset($http_response_header[0])) {
156 $httpcodeOK = isset($http_response_header) and isset($http_response_header[0]) and ((strpos($http_response_header[0], '200 OK') !== FALSE) or (strpos($http_response_header[0], '301 Moved Permanently') !== FALSE));
157 }
158 }
159
160 # if response is not empty and response is OK
161 if (isset($data) and isset($httpcodeOK) and $httpcodeOK) {
162
163 # take charset of page and get it
164 preg_match('#<meta .*charset=.*>#Usi', $data, $meta);
165
166 # if meta tag is found
167 if (!empty($meta[0])) {
168 preg_match('#charset="?(.*)"#si', $meta[0], $encoding);
169 # if charset is found set it otherwise, set it to utf-8
170 $html_charset = (!empty($encoding[1])) ? strtolower($encoding[1]) : 'utf-8';
171 if (empty($encoding[1])) $encoding[1] = 'utf-8';
172 } else {
173 $html_charset = 'utf-8';
174 $encoding[1] = '';
175 }
176
177 # replace charset of url to charset of page
178 $data = str_replace('charset=' . $encoding[1], 'charset=' . $html_charset, $data);
179
180 return $data;
181 }
182 else {
183 return FALSE;
184 }
185 }
186
187 public static function renderJson($data)
188 {
189 header('Cache-Control: no-cache, must-revalidate');
190 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
191 header('Content-type: application/json; charset=UTF-8');
192 echo json_encode($data);
193 exit();
194 }
195
196 public static function logm($message)
197 {
198 if (DEBUG_POCHE && php_sapi_name() != 'cli') {
199 $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n";
200 file_put_contents(CACHE . '/log.txt', $t, FILE_APPEND);
201 error_log('DEBUG POCHE : ' . $message);
202 }
203 }
204
205 public static function encodeString($string)
206 {
207 return sha1($string . SALT);
208 }
209
210 public static function checkVar($var, $default = '')
211 {
212 return ((isset ($_REQUEST["$var"])) ? htmlentities($_REQUEST["$var"]) : $default);
213 }
214
215 public static function getDomain($url)
216 {
217 return parse_url($url, PHP_URL_HOST);
218 }
219
220 public static function getReadingTime($text) {
221 $word = str_word_count(strip_tags($text));
222 $minutes = floor($word / 200);
223 $seconds = floor($word % 200 / (200 / 60));
224 $time = array('minutes' => $minutes, 'seconds' => $seconds);
225
226 return $minutes;
227 }
228
229 public static function getDocLanguage($userlanguage) {
230 $lang = explode('.', $userlanguage);
231 return str_replace('_', '-', $lang[0]);
232 }
233
234 public static function status($status_code)
235 {
236 if (strpos(php_sapi_name(), 'apache') !== false) {
237
238 header('HTTP/1.0 '.$status_code);
239 }
240 else {
241
242 header('Status: '.$status_code);
243 }
244 }
245
246 public static function download_db() {
247 header('Content-Disposition: attachment; filename="poche.sqlite.gz"');
248 self::status(200);
249
250 header('Content-Transfer-Encoding: binary');
251 header('Content-Type: application/octet-stream');
252 echo gzencode(file_get_contents(STORAGE_SQLITE));
253
254 exit;
255 }
256
257 public static function getPageContent(Url $url)
258 {
259 // Saving and clearing context
260 $REAL = array();
261 foreach( $GLOBALS as $key => $value ) {
262 if( $key != 'GLOBALS' && $key != '_SESSION' && $key != 'HTTP_SESSION_VARS' ) {
263 $GLOBALS[$key] = array();
264 $REAL[$key] = $value;
265 }
266 }
267 // Saving and clearing session
268 if ( isset($_SESSION) ) {
269 $REAL_SESSION = array();
270 foreach( $_SESSION as $key => $value ) {
271 $REAL_SESSION[$key] = $value;
272 unset($_SESSION[$key]);
273 }
274 }
275
276 // Running code in different context
277 $scope = function() {
278 extract( func_get_arg(1) );
279 $_GET = $_REQUEST = array(
280 "url" => $url->getUrl(),
281 "max" => 5,
282 "links" => "preserve",
283 "exc" => "",
284 "format" => "json",
285 "submit" => "Create Feed"
286 );
287 ob_start();
288 require func_get_arg(0);
289 $json = ob_get_contents();
290 ob_end_clean();
291 return $json;
292 };
293 $json = $scope( "inc/3rdparty/makefulltextfeed.php", array("url" => $url) );
294
295 // Clearing and restoring context
296 foreach( $GLOBALS as $key => $value ) {
297 if( $key != "GLOBALS" && $key != "_SESSION" ) {
298 unset($GLOBALS[$key]);
299 }
300 }
301 foreach( $REAL as $key => $value ) {
302 $GLOBALS[$key] = $value;
303 }
304 // Clearing and restoring session
305 if ( isset($REAL_SESSION) ) {
306 foreach( $_SESSION as $key => $value ) {
307 unset($_SESSION[$key]);
308 }
309 foreach( $REAL_SESSION as $key => $value ) {
310 $_SESSION[$key] = $value;
311 }
312 }
313
314 return json_decode($json, true);
315 }
316
317 /**
318 * Returns whether we handle an AJAX (XMLHttpRequest) request.
319 * @return boolean whether we handle an AJAX (XMLHttpRequest) request.
320 */
321 public static function isAjaxRequest()
322 {
323 return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
324 }
325
326 }