]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Tools.class.php
deleting send to kindle function
[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 $https = (!empty($_SERVER['HTTPS'])
44 && (strtolower($_SERVER['HTTPS']) == 'on'))
45 || (isset($_SERVER["SERVER_PORT"])
46 && $_SERVER["SERVER_PORT"] == '443') // HTTPS detection.
47 || (isset($_SERVER["SERVER_PORT"]) //Custom HTTPS port detection
48 && $_SERVER["SERVER_PORT"] == SSL_PORT)
49 || (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
50 && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
51
52 $serverport = (!isset($_SERVER["SERVER_PORT"])
53 || $_SERVER["SERVER_PORT"] == '80'
54 || ($https && $_SERVER["SERVER_PORT"] == '443')
55 || ($https && $_SERVER["SERVER_PORT"]==SSL_PORT) //Custom HTTPS port detection
56 ? '' : ':' . $_SERVER["SERVER_PORT"]);
57
58 $scriptname = str_replace('/index.php', '/', $_SERVER["SCRIPT_NAME"]);
59
60 if (!isset($_SERVER["HTTP_HOST"])) {
61 return $scriptname;
62 }
63
64 $host = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']));
65
66 if (strpos($host, ':') !== false) {
67 $serverport = '';
68 }
69
70 return 'http' . ($https ? 's' : '') . '://'
71 . $host . $serverport . $scriptname;
72 }
73
74 /**
75 * Redirects to a URL
76 *
77 * @param string $url
78 */
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 }
99
100 self::logm('redirect to ' . $url);
101 header('Location: '.$url);
102 exit();
103 }
104
105 /**
106 * Returns name of the template file to display
107 *
108 * @param $view
109 * @return string
110 */
111 public static function getTplFile($view)
112 {
113 $views = array(
114 'install', 'import', 'export', 'config', 'tags',
115 'edit-tags', 'view', 'login', 'error'
116 );
117
118 return (in_array($view, $views) ? $view . '.twig' : 'home.twig');
119 }
120
121 /**
122 * Download a file (typically, for downloading pictures on web server)
123 *
124 * @param $url
125 * @return bool|mixed|string
126 */
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);
137 if (!ini_get('open_basedir') && !ini_get('safe_mode')) {
138 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
139 }
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
173 $data = @file_get_contents($url, false, $context, -1, 4000000);
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';
191 if (empty($encoding[1])) $encoding[1] = 'utf-8';
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
207 /**
208 * Headers for JSON export
209 *
210 * @param $data
211 */
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
221 /**
222 * Create new line in log file
223 *
224 * @param $message
225 */
226 public static function logm($message)
227 {
228 if (DEBUG_POCHE && php_sapi_name() != 'cli') {
229 $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n";
230 file_put_contents(CACHE . '/log.txt', $t, FILE_APPEND);
231 error_log('DEBUG POCHE : ' . $message);
232 }
233 }
234
235 /**
236 * Encode a URL by using a salt
237 *
238 * @param $string
239 * @return string
240 */
241 public static function encodeString($string)
242 {
243 return sha1($string . SALT);
244 }
245
246 /**
247 * Cleans a variable
248 *
249 * @param $var
250 * @param string $default
251 * @return string
252 */
253 public static function checkVar($var, $default = '')
254 {
255 return ((isset($_REQUEST["$var"])) ? htmlentities($_REQUEST["$var"]) : $default);
256 }
257
258 /**
259 * Returns the domain name for a URL
260 *
261 * @param $url
262 * @return string
263 */
264 public static function getDomain($url)
265 {
266 return parse_url($url, PHP_URL_HOST);
267 }
268
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);
278 }
279
280 /**
281 * Returns the correct header for a status code
282 *
283 * @param $status_code
284 */
285 private static function _status($status_code)
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
297 /**
298 * Download the sqlite database
299 */
300 public static function downloadDb()
301 {
302 header('Content-Disposition: attachment; filename="poche.sqlite.gz"');
303 self::_status(200);
304
305 header('Content-Transfer-Encoding: binary');
306 header('Content-Type: application/octet-stream');
307 echo gzencode(file_get_contents(STORAGE_SQLITE));
308
309 exit;
310 }
311
312 /**
313 * Get the content for a given URL (by a call to FullTextFeed)
314 *
315 * @param Url $url
316 * @return mixed
317 */
318 public static function getPageContent(Url $url)
319 {
320 // Saving and clearing context
321 $REAL = array();
322 foreach( $GLOBALS as $key => $value ) {
323 if( $key != 'GLOBALS' && $key != '_SESSION' && $key != 'HTTP_SESSION_VARS' ) {
324 $GLOBALS[$key] = array();
325 $REAL[$key] = $value;
326 }
327 }
328 // Saving and clearing session
329 if (isset($_SESSION)) {
330 $REAL_SESSION = array();
331 foreach( $_SESSION as $key => $value ) {
332 $REAL_SESSION[$key] = $value;
333 unset($_SESSION[$key]);
334 }
335 }
336
337 // Running code in different context
338 $scope = function() {
339 extract( func_get_arg(1) );
340 $_GET = $_REQUEST = array(
341 "url" => $url->getUrl(),
342 "max" => 5,
343 "links" => "preserve",
344 "exc" => "",
345 "format" => "json",
346 "submit" => "Create Feed"
347 );
348 ob_start();
349 require func_get_arg(0);
350 $json = ob_get_contents();
351 ob_end_clean();
352 return $json;
353 };
354
355 $json = $scope("inc/3rdparty/makefulltextfeed.php", array("url" => $url));
356
357 // Clearing and restoring context
358 foreach ($GLOBALS as $key => $value) {
359 if($key != "GLOBALS" && $key != "_SESSION" ) {
360 unset($GLOBALS[$key]);
361 }
362 }
363 foreach ($REAL as $key => $value) {
364 $GLOBALS[$key] = $value;
365 }
366
367 // Clearing and restoring session
368 if (isset($REAL_SESSION)) {
369 foreach($_SESSION as $key => $value) {
370 unset($_SESSION[$key]);
371 }
372
373 foreach($REAL_SESSION as $key => $value) {
374 $_SESSION[$key] = $value;
375 }
376 }
377
378 return json_decode($json, true);
379 }
380
381 /**
382 * Returns whether we handle an AJAX (XMLHttpRequest) request.
383 *
384 * @return boolean whether we handle an AJAX (XMLHttpRequest) request.
385 */
386 public static function isAjaxRequest()
387 {
388 return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
389 }
390
391 /*
392 * Empty cache folder
393 */
394 public static function emptyCache()
395 {
396 $files = new RecursiveIteratorIterator(
397 new RecursiveDirectoryIterator(CACHE, RecursiveDirectoryIterator::SKIP_DOTS),
398 RecursiveIteratorIterator::CHILD_FIRST
399 );
400
401 foreach ($files as $fileInfo) {
402 $todo = ($fileInfo->isDir() ? 'rmdir' : 'unlink');
403 $todo($fileInfo->getRealPath());
404 }
405
406 Tools::logm('empty cache');
407 Tools::redirect();
408 }
409
410 public static function generateToken()
411 {
412 if (ini_get('open_basedir') === '') {
413 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
414 // alternative to /dev/urandom for Windows
415 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
416 } else {
417 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
418 }
419 }
420 else {
421 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
422 }
423
424 return str_replace('+', '', $token);
425 }
426
427 }