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