]>
git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/poche/Tools.class.php
3 * wallabag, self hostable application allowing you to not miss any content anymore
6 * @author Nicolas LÅ“uillet <nicolas@loeuillet.org>
8 * @license http://opensource.org/licenses/MIT see COPYING file
13 private function __construct()
19 * Initialize PHP environment
21 public static function initPhp()
23 define('START_TIME', microtime(true));
25 function stripslashesDeep($value) {
26 return is_array($value)
27 ? array_map('stripslashesDeep', $value)
28 : stripslashes($value);
31 if (get_magic_quotes_gpc()) {
32 $_POST = array_map('stripslashesDeep', $_POST);
33 $_GET = array_map('stripslashesDeep', $_GET);
34 $_COOKIE = array_map('stripslashesDeep', $_COOKIE);
38 register_shutdown_function('ob_end_flush');
42 * Get wallabag instance URL
46 public static function getPocheUrl()
48 $https = (!empty($_SERVER['HTTPS'])
49 && (strtolower($_SERVER['HTTPS']) == 'on'))
50 || (isset($_SERVER["SERVER_PORT"])
51 && $_SERVER["SERVER_PORT"] == '443') // HTTPS detection.
52 || (isset($_SERVER["SERVER_PORT"]) //Custom HTTPS port detection
53 && $_SERVER["SERVER_PORT"] == SSL_PORT
)
54 || (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
55 && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
57 $serverport = (!isset($_SERVER["SERVER_PORT"])
58 || $_SERVER["SERVER_PORT"] == '80'
59 || ($https && $_SERVER["SERVER_PORT"] == '443')
60 || ($https && $_SERVER["SERVER_PORT"]==SSL_PORT
) //Custom HTTPS port detection
61 ? '' : ':' . $_SERVER["SERVER_PORT"]);
63 $scriptname = str_replace('/index.php', '/', $_SERVER["SCRIPT_NAME"]);
65 if (!isset($_SERVER["HTTP_HOST"])) {
69 $host = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']));
71 if (strpos($host, ':') !== false) {
75 return 'http' . ($https ? 's' : '') . '://'
76 . $host . $serverport . $scriptname;
84 public static function redirect($url = '')
87 $url = (empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']);
88 if (isset($_POST['returnurl'])) {
89 $url = $_POST['returnurl'];
94 if (empty($url) || parse_url($url, PHP_URL_QUERY
) === $_SERVER['QUERY_STRING']) {
95 $url = Tools
::getPocheUrl();
98 if (substr($url, 0, 1) !== '?') {
99 $ref = Tools
::getPocheUrl();
100 if (substr($url, 0, strlen($ref)) !== $ref) {
105 self
::logm('redirect to ' . $url);
106 header('Location: '.$url);
111 * Returns name of the template file to display
116 public static function getTplFile($view)
119 'install', 'import', 'export', 'config', 'tags',
120 'edit-tags', 'view', 'login', 'error'
123 return (in_array($view, $views) ? $view . '.twig' : 'home.twig');
127 * Download a file (typically, for downloading pictures on web server)
130 * @return bool|mixed|string
132 public static function getFile($url)
135 $useragent = "Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0";
137 if (in_array ('curl', get_loaded_extensions())) {
138 # Fetch feed from URL
140 curl_setopt($curl, CURLOPT_URL
, $url);
141 curl_setopt($curl, CURLOPT_TIMEOUT
, $timeout);
142 if (!ini_get('open_basedir') && !ini_get('safe_mode')) {
143 curl_setopt($curl, CURLOPT_FOLLOWLOCATION
, true);
145 curl_setopt($curl, CURLOPT_RETURNTRANSFER
, true);
146 curl_setopt($curl, CURLOPT_HEADER
, false);
148 # for ssl, do not verified certificate
149 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, FALSE);
150 curl_setopt($curl, CURLOPT_AUTOREFERER
, TRUE );
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);
157 $data = curl_exec($curl);
158 $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE
);
159 $httpcodeOK = isset($httpcode) and ($httpcode == 200 or $httpcode == 301);
162 # create http context and add timeout and user-agent
163 $context = stream_context_create(
166 'timeout' => $timeout,
167 'header' => "User-Agent: " . $useragent,
168 'follow_location' => true
171 'verify_peer' => false,
172 'allow_self_signed' => true
177 # only download page lesser than 4MB
178 $data = @file_get_contents($url, false, $context, -1, 4000000);
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));
185 # if response is not empty and response is OK
186 if (isset($data) and isset($httpcodeOK) and $httpcodeOK) {
188 # take charset of page and get it
189 preg_match('#<meta .*charset=.*>#Usi', $data, $meta);
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';
196 if (empty($encoding[1])) $encoding[1] = 'utf-8';
198 $html_charset = 'utf-8';
202 # replace charset of url to charset of page
203 $data = str_replace('charset=' . $encoding[1], 'charset=' . $html_charset, $data);
213 * Headers for JSON export
217 public static function renderJson($data)
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);
227 * Create new line in log file
231 public static function logm($message)
233 if (DEBUG_POCHE
&& php_sapi_name() != 'cli') {
234 $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n";
235 file_put_contents(CACHE
. '/log.txt', $t, FILE_APPEND
);
236 error_log('DEBUG POCHE : ' . $message);
241 * Encode a URL by using a salt
246 public static function encodeString($string)
248 return sha1($string . SALT
);
255 * @param string $default
258 public static function checkVar($var, $default = '')
260 return ((isset($_REQUEST["$var"])) ? htmlentities($_REQUEST["$var"]) : $default);
264 * Returns the domain name for a URL
269 public static function getDomain($url)
271 return parse_url($url, PHP_URL_HOST
);
275 * For a given text, we calculate reading time for an article
280 public static function getReadingTime($text)
282 return floor(str_word_count(strip_tags($text)) / 200);
286 * Returns the correct header for a status code
288 * @param $status_code
290 private static function _status($status_code)
292 if (strpos(php_sapi_name(), 'apache') !== false) {
294 header('HTTP/1.0 '.$status_code);
298 header('Status: '.$status_code);
303 * Download the sqlite database
305 public static function downloadDb()
307 header('Content-Disposition: attachment; filename="poche.sqlite.gz"');
310 header('Content-Transfer-Encoding: binary');
311 header('Content-Type: application/octet-stream');
312 echo gzencode(file_get_contents(STORAGE_SQLITE
));
318 * Get the content for a given URL (by a call to FullTextFeed)
323 public static function getPageContent(Url
$url)
325 // Saving and clearing context
327 foreach( $GLOBALS as $key => $value ) {
328 if( $key != 'GLOBALS' && $key != '_SESSION' && $key != 'HTTP_SESSION_VARS' ) {
329 $GLOBALS[$key] = array();
330 $REAL[$key] = $value;
333 // Saving and clearing session
334 if (isset($_SESSION)) {
335 $REAL_SESSION = array();
336 foreach( $_SESSION as $key => $value ) {
337 $REAL_SESSION[$key] = $value;
338 unset($_SESSION[$key]);
342 // Running code in different context
343 $scope = function() {
344 extract( func_get_arg(1) );
345 $_GET = $_REQUEST = array(
346 "url" => $url->getUrl(),
348 "links" => "preserve",
351 "submit" => "Create Feed"
354 require func_get_arg(0);
355 $json = ob_get_contents();
360 $json = $scope("inc/3rdparty/makefulltextfeed.php", array("url" => $url));
362 // Clearing and restoring context
363 foreach ($GLOBALS as $key => $value) {
364 if($key != "GLOBALS" && $key != "_SESSION" ) {
365 unset($GLOBALS[$key]);
368 foreach ($REAL as $key => $value) {
369 $GLOBALS[$key] = $value;
372 // Clearing and restoring session
373 if (isset($REAL_SESSION)) {
374 foreach($_SESSION as $key => $value) {
375 unset($_SESSION[$key]);
378 foreach($REAL_SESSION as $key => $value) {
379 $_SESSION[$key] = $value;
383 return json_decode($json, true);
387 * Returns whether we handle an AJAX (XMLHttpRequest) request.
389 * @return boolean whether we handle an AJAX (XMLHttpRequest) request.
391 public static function isAjaxRequest()
393 return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';