]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Tools.class.php
2ee86c74e7ccb5823bfd4663454ba3ca90f8eab0
[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://opensource.org/licenses/MIT see COPYING file
9 */
10
11 final class Tools
12 {
13 /**
14 * Initialize PHP environment
15 */
16 public static function initPhp()
17 {
18 define('START_TIME', microtime(true));
19
20 function stripslashesDeep($value) {
21 return is_array($value)
22 ? array_map('stripslashesDeep', $value)
23 : stripslashes($value);
24 }
25
26 if (get_magic_quotes_gpc()) {
27 $_POST = array_map('stripslashesDeep', $_POST);
28 $_GET = array_map('stripslashesDeep', $_GET);
29 $_COOKIE = array_map('stripslashesDeep', $_COOKIE);
30 }
31
32 ob_start();
33 register_shutdown_function('ob_end_flush');
34 }
35
36 /**
37 * Get wallabag instance URL
38 *
39 * @return string
40 */
41 public static function getPocheUrl()
42 {
43 $baseUrl = "";
44
45 $https = (!empty($_SERVER['HTTPS'])
46 && (strtolower($_SERVER['HTTPS']) == 'on'))
47 || (isset($_SERVER["SERVER_PORT"])
48 && $_SERVER["SERVER_PORT"] == '443') // HTTPS detection.
49 || (isset($_SERVER["SERVER_PORT"]) //Custom HTTPS port detection
50 && $_SERVER["SERVER_PORT"] == SSL_PORT)
51 || (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
52 && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
53
54 $serverport = (!isset($_SERVER["SERVER_PORT"])
55 || $_SERVER["SERVER_PORT"] == '80'
56 || $_SERVER["SERVER_PORT"] == HTTP_PORT
57 || ($https && $_SERVER["SERVER_PORT"] == '443')
58 || ($https && $_SERVER["SERVER_PORT"]==SSL_PORT) //Custom HTTPS port detection
59 ? '' : ':' . $_SERVER["SERVER_PORT"]);
60
61 if (isset($_SERVER["HTTP_X_FORWARDED_PORT"])) {
62 $serverport = ':' . $_SERVER["HTTP_X_FORWARDED_PORT"];
63 }
64
65 $scriptname = str_replace('/index.php', '/', $_SERVER["SCRIPT_NAME"]);
66
67 if (!isset($_SERVER["HTTP_HOST"])) {
68 return $scriptname;
69 }
70
71 $host = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']));
72
73 if (strpos($host, ':') !== false) {
74 $serverport = '';
75 }
76
77 // check if BASE_URL is configured
78 if(BASE_URL) {
79 $baseUrl = BASE_URL;
80 } else {
81 $baseUrl = 'http' . ($https ? 's' : '') . '://' . $host . $serverport;
82 }
83
84 return $baseUrl . $scriptname;
85
86 }
87
88 /**
89 * Redirects to a URL
90 *
91 * @param string $url
92 */
93 public static function redirect($url = '')
94 {
95 if ($url === '') {
96 $url = (empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']);
97 if (isset($_POST['returnurl'])) {
98 $url = $_POST['returnurl'];
99 }
100 }
101
102 # prevent loop
103 if (empty($url) || parse_url($url, PHP_URL_QUERY) === $_SERVER['QUERY_STRING']) {
104 $url = Tools::getPocheUrl();
105 }
106
107 if (substr($url, 0, 1) !== '?') {
108 $ref = Tools::getPocheUrl();
109 if (substr($url, 0, strlen($ref)) !== $ref) {
110 $url = $ref;
111 }
112 }
113
114 self::logm('redirect to ' . $url);
115 header('Location: '.$url);
116 exit();
117 }
118
119 /**
120 * Returns name of the template file to display
121 *
122 * @param $view
123 * @return string
124 */
125 public static function getTplFile($view)
126 {
127 $views = array(
128 'install', 'import', 'export', 'config', 'tags',
129 'edit-tags', 'view', 'login', 'error', 'about', 'register'
130 );
131
132 return (in_array($view, $views) ? $view . '.twig' : 'home.twig');
133 }
134
135 /**
136 * Download a file (typically, for downloading pictures on web server)
137 *
138 * @param $url
139 * @return bool|mixed|string
140 */
141 public static function getFile($url)
142 {
143 $timeout = 15;
144 $useragent = "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0";
145
146 if (in_array ('curl', get_loaded_extensions())) {
147 # Fetch feed from URL
148 $curl = curl_init();
149 curl_setopt($curl, CURLOPT_URL, $url);
150 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
151 if (!ini_get('open_basedir') && !ini_get('safe_mode')) {
152 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
153 }
154 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
155 curl_setopt($curl, CURLOPT_HEADER, false);
156
157 # for ssl, do not verified certificate
158 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
159 curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE );
160
161 # FeedBurner requires a proper USER-AGENT...
162 curl_setopt($curl, CURL_HTTP_VERSION_1_1, true);
163 curl_setopt($curl, CURLOPT_ENCODING, "gzip, deflate");
164 curl_setopt($curl, CURLOPT_USERAGENT, $useragent);
165
166 $data = curl_exec($curl);
167 $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
168 $httpcodeOK = isset($httpcode) and ($httpcode == 200 or $httpcode == 301);
169 curl_close($curl);
170 } else {
171 # create http context and add timeout and user-agent
172 $context = stream_context_create(
173 array(
174 'http' => array(
175 'timeout' => $timeout,
176 'header' => "User-Agent: " . $useragent,
177 'follow_location' => true
178 ),
179 'ssl' => array(
180 'verify_peer' => false,
181 'allow_self_signed' => true
182 )
183 )
184 );
185
186 # only download page lesser than 4MB
187 $data = @file_get_contents($url, false, $context, -1, 4000000);
188
189 if (isset($http_response_header) and isset($http_response_header[0])) {
190 $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));
191 }
192 }
193
194 # if response is not empty and response is OK
195 if (isset($data) and isset($httpcodeOK) and $httpcodeOK) {
196
197 # take charset of page and get it
198 preg_match('#<meta .*charset=.*>#Usi', $data, $meta);
199
200 # if meta tag is found
201 if (!empty($meta[0])) {
202 preg_match('#charset="?(.*)"#si', $meta[0], $encoding);
203 # if charset is found set it otherwise, set it to utf-8
204 $html_charset = (!empty($encoding[1])) ? strtolower($encoding[1]) : 'utf-8';
205 if (empty($encoding[1])) $encoding[1] = 'utf-8';
206 } else {
207 $html_charset = 'utf-8';
208 $encoding[1] = '';
209 }
210
211 # replace charset of url to charset of page
212 $data = str_replace('charset=' . $encoding[1], 'charset=' . $html_charset, $data);
213
214 return $data;
215 }
216 else {
217 return FALSE;
218 }
219 }
220
221 /**
222 * Headers for JSON export
223 *
224 * @param $data
225 */
226 public static function renderJson($data)
227 {
228 header('Cache-Control: no-cache, must-revalidate');
229 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
230 header('Content-type: application/json; charset=UTF-8');
231 echo json_encode($data);
232 exit();
233 }
234
235 /**
236 * UTF-8 encode array of string
237 *
238 * @param $data
239 */
240 public static function utf8ize($data)
241 {
242 if (is_array($data))
243 {
244 foreach ($data as $k => $v)
245 {
246 $data[$k] = self::utf8ize($v);
247 }
248 }
249 else if (is_string ($data))
250 {
251 if ('' == mb_detect_encoding($data))
252 {
253 return utf8_encode($data);
254 }
255 else
256 {
257 return $data;
258 }
259 }
260 return $data;
261 }
262
263 /**
264 * Create new line in log file
265 *
266 * @param $message
267 */
268 public static function logm($message)
269 {
270 if (DEBUG_POCHE && php_sapi_name() != 'cli') {
271 $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n";
272 file_put_contents(CACHE . '/log.txt', $t, FILE_APPEND);
273 error_log('DEBUG POCHE : ' . $message);
274 }
275 }
276
277 /**
278 * Encode a URL by using a salt
279 *
280 * @param $string
281 * @return string
282 */
283 public static function encodeString($string)
284 {
285 return sha1($string . SALT);
286 }
287
288 /**
289 * Cleans a variable
290 *
291 * @param $var
292 * @param string $default
293 * @return string
294 */
295 public static function checkVar($var, $default = '')
296 {
297 return ((isset($_REQUEST["$var"])) ? htmlentities($_REQUEST["$var"]) : $default);
298 }
299
300 /**
301 * Returns the domain name for a URL
302 *
303 * @param $url
304 * @return string
305 */
306 public static function getDomain($url)
307 {
308 return parse_url($url, PHP_URL_HOST);
309 }
310
311 /**
312 * For a given text, we calculate reading time for an article
313 *
314 * @param $text
315 * @return float
316 */
317 public static function getReadingTime($text)
318 {
319 return floor(str_word_count(strip_tags($text)) / 200);
320 }
321
322 /**
323 * Returns the correct header for a status code
324 *
325 * @param $status_code
326 */
327 private static function _status($status_code)
328 {
329 if (strpos(php_sapi_name(), 'apache') !== false) {
330
331 header('HTTP/1.0 '.$status_code);
332 }
333 else {
334
335 header('Status: '.$status_code);
336 }
337 }
338
339 /**
340 * Get the content for a given URL (by a call to FullTextFeed)
341 *
342 * @param Url $url
343 * @return mixed
344 */
345 public static function getPageContent(Url $url)
346 {
347 // Saving and clearing context
348 $REAL = array();
349 foreach( $GLOBALS as $key => $value ) {
350 if( $key != 'GLOBALS' && $key != '_SESSION' && $key != 'HTTP_SESSION_VARS' ) {
351 $GLOBALS[$key] = array();
352 $REAL[$key] = $value;
353 }
354 }
355 // Saving and clearing session
356 if (isset($_SESSION)) {
357 $REAL_SESSION = array();
358 foreach( $_SESSION as $key => $value ) {
359 $REAL_SESSION[$key] = $value;
360 unset($_SESSION[$key]);
361 }
362 }
363
364 // Running code in different context
365 $scope = function() {
366 extract( func_get_arg(1) );
367 $_GET = $_REQUEST = array(
368 "url" => $url->getUrl(),
369 "max" => 5,
370 "links" => "preserve",
371 "exc" => "",
372 "format" => "json",
373 "submit" => "Create Feed"
374 );
375 ob_start();
376 require func_get_arg(0);
377 $json = ob_get_contents();
378 ob_end_clean();
379 return $json;
380 };
381
382 // Silence $scope function to avoid
383 // issues with FTRSS when error_reporting is to high
384 // FTRSS generates PHP warnings which break output
385 $json = @$scope("inc/3rdparty/makefulltextfeed.php", array("url" => $url));
386
387 // Clearing and restoring context
388 foreach ($GLOBALS as $key => $value) {
389 if($key != "GLOBALS" && $key != "_SESSION" ) {
390 unset($GLOBALS[$key]);
391 }
392 }
393 foreach ($REAL as $key => $value) {
394 $GLOBALS[$key] = $value;
395 }
396
397 // Clearing and restoring session
398 if (isset($REAL_SESSION)) {
399 foreach($_SESSION as $key => $value) {
400 unset($_SESSION[$key]);
401 }
402
403 foreach($REAL_SESSION as $key => $value) {
404 $_SESSION[$key] = $value;
405 }
406 }
407
408 return json_decode($json, true);
409 }
410
411 /**
412 * Returns whether we handle an AJAX (XMLHttpRequest) request.
413 *
414 * @return boolean whether we handle an AJAX (XMLHttpRequest) request.
415 */
416 public static function isAjaxRequest()
417 {
418 return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
419 }
420
421 /*
422 * Empty cache folder
423 */
424 public static function emptyCache()
425 {
426 $files = new RecursiveIteratorIterator(
427 new RecursiveDirectoryIterator(CACHE, RecursiveDirectoryIterator::SKIP_DOTS),
428 RecursiveIteratorIterator::CHILD_FIRST
429 );
430
431 foreach ($files as $fileInfo) {
432 $filename = $fileInfo->getFilename();
433 if (!$filename[0] == '.') {
434 $todo = ($fileInfo->isDir() ? 'rmdir' : 'unlink');
435 $todo($fileInfo->getRealPath());
436 }
437 }
438
439 Tools::logm('empty cache');
440 Tools::redirect();
441 }
442
443 public static function generateToken()
444 {
445 if (ini_get('open_basedir') === '') {
446 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
447 // alternative to /dev/urandom for Windows
448 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
449 } else {
450 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
451 }
452 }
453 else {
454 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
455 }
456
457 return str_replace('+', '', $token);
458 }
459
460 /**
461 *
462 * Returns the doctype for an HTML document (used for Mozilla Bookmarks)
463 * @param simple_html_dom $doc
464 * @return doctype $el
465 *
466 */
467
468 public static function get_doctype($doc)
469 {
470 $els = $doc->find('unknown');
471
472 foreach ($els as $e => $el)
473 if ($el->parent()->tag == 'root')
474 return $el;
475
476 return NULL;
477 }
478
479 }