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