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