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
14 * Initialize PHP environment
16 public static function initPhp()
18 define('START_TIME', microtime(true));
20 function stripslashesDeep($value) {
21 return is_array($value)
22 ? array_map('stripslashesDeep', $value)
23 : stripslashes($value);
26 if (get_magic_quotes_gpc()) {
27 $_POST = array_map('stripslashesDeep', $_POST);
28 $_GET = array_map('stripslashesDeep', $_GET);
29 $_COOKIE = array_map('stripslashesDeep', $_COOKIE);
33 register_shutdown_function('ob_end_flush');
37 * Get wallabag instance URL
41 public static function getPocheUrl()
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');
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"]);
58 if (isset($_SERVER["HTTP_X_FORWARDED_PORT"])) {
59 $serverport = ':' . $_SERVER["HTTP_X_FORWARDED_PORT"];
62 $scriptname = str_replace('/index.php', '/', $_SERVER["SCRIPT_NAME"]);
64 if (!isset($_SERVER["HTTP_HOST"])) {
68 $host = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']));
70 if (strpos($host, ':') !== false) {
74 return 'http' . ($https ? 's' : '') . '://'
75 . $host . $serverport . $scriptname;
83 public static function redirect($url = '')
86 $url = (empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']);
87 if (isset($_POST['returnurl'])) {
88 $url = $_POST['returnurl'];
93 if (empty($url) || parse_url($url, PHP_URL_QUERY
) === $_SERVER['QUERY_STRING']) {
94 $url = Tools
::getPocheUrl();
97 if (substr($url, 0, 1) !== '?') {
98 $ref = Tools
::getPocheUrl();
99 if (substr($url, 0, strlen($ref)) !== $ref) {
104 self
::logm('redirect to ' . $url);
105 header('Location: '.$url);
110 * Returns name of the template file to display
115 public static function getTplFile($view)
118 'install', 'import', 'export', 'config', 'tags',
119 'edit-tags', 'view', 'login', 'error'
122 return (in_array($view, $views) ? $view . '.twig' : 'home.twig');
126 * Download a file (typically, for downloading pictures on web server)
129 * @return bool|mixed|string
131 public static function getFile($url)
134 $useragent = "Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0";
136 if (in_array ('curl', get_loaded_extensions())) {
137 # Fetch feed from URL
139 curl_setopt($curl, CURLOPT_URL
, $url);
140 curl_setopt($curl, CURLOPT_TIMEOUT
, $timeout);
141 if (!ini_get('open_basedir') && !ini_get('safe_mode')) {
142 curl_setopt($curl, CURLOPT_FOLLOWLOCATION
, true);
144 curl_setopt($curl, CURLOPT_RETURNTRANSFER
, true);
145 curl_setopt($curl, CURLOPT_HEADER
, false);
147 # for ssl, do not verified certificate
148 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, FALSE);
149 curl_setopt($curl, CURLOPT_AUTOREFERER
, TRUE );
151 # FeedBurner requires a proper USER-AGENT...
152 curl_setopt($curl, CURL_HTTP_VERSION_1_1
, true);
153 curl_setopt($curl, CURLOPT_ENCODING
, "gzip, deflate");
154 curl_setopt($curl, CURLOPT_USERAGENT
, $useragent);
156 $data = curl_exec($curl);
157 $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE
);
158 $httpcodeOK = isset($httpcode) and ($httpcode == 200 or $httpcode == 301);
161 # create http context and add timeout and user-agent
162 $context = stream_context_create(
165 'timeout' => $timeout,
166 'header' => "User-Agent: " . $useragent,
167 'follow_location' => true
170 'verify_peer' => false,
171 'allow_self_signed' => true
176 # only download page lesser than 4MB
177 $data = @file_get_contents($url, false, $context, -1, 4000000);
179 if (isset($http_response_header) and isset($http_response_header[0])) {
180 $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));
184 # if response is not empty and response is OK
185 if (isset($data) and isset($httpcodeOK) and $httpcodeOK) {
187 # take charset of page and get it
188 preg_match('#<meta .*charset=.*>#Usi', $data, $meta);
190 # if meta tag is found
191 if (!empty($meta[0])) {
192 preg_match('#charset="?(.*)"#si', $meta[0], $encoding);
193 # if charset is found set it otherwise, set it to utf-8
194 $html_charset = (!empty($encoding[1])) ? strtolower($encoding[1]) : 'utf-8';
195 if (empty($encoding[1])) $encoding[1] = 'utf-8';
197 $html_charset = 'utf-8';
201 # replace charset of url to charset of page
202 $data = str_replace('charset=' . $encoding[1], 'charset=' . $html_charset, $data);
212 * Headers for JSON export
216 public static function renderJson($data)
218 header('Cache-Control: no-cache, must-revalidate');
219 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
220 header('Content-type: application/json; charset=UTF-8');
221 echo json_encode($data);
226 * Create new line in log file
230 public static function logm($message)
232 if (DEBUG_POCHE
&& php_sapi_name() != 'cli') {
233 $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n";
234 file_put_contents(CACHE
. '/log.txt', $t, FILE_APPEND
);
235 error_log('DEBUG POCHE : ' . $message);
240 * Encode a URL by using a salt
245 public static function encodeString($string)
247 return sha1($string . SALT
);
254 * @param string $default
257 public static function checkVar($var, $default = '')
259 return ((isset($_REQUEST["$var"])) ? htmlentities($_REQUEST["$var"]) : $default);
263 * Returns the domain name for a URL
268 public static function getDomain($url)
270 return parse_url($url, PHP_URL_HOST
);
274 * For a given text, we calculate reading time for an article
279 public static function getReadingTime($text)
281 return floor(str_word_count(strip_tags($text)) / 200);
285 * Returns the correct header for a status code
287 * @param $status_code
289 private static function _status($status_code)
291 if (strpos(php_sapi_name(), 'apache') !== false) {
293 header('HTTP/1.0 '.$status_code);
297 header('Status: '.$status_code);
302 * Get the content for a given URL (by a call to FullTextFeed)
307 public static function getPageContent(Url
$url)
309 // Saving and clearing context
311 foreach( $GLOBALS as $key => $value ) {
312 if( $key != 'GLOBALS' && $key != '_SESSION' && $key != 'HTTP_SESSION_VARS' ) {
313 $GLOBALS[$key] = array();
314 $REAL[$key] = $value;
317 // Saving and clearing session
318 if (isset($_SESSION)) {
319 $REAL_SESSION = array();
320 foreach( $_SESSION as $key => $value ) {
321 $REAL_SESSION[$key] = $value;
322 unset($_SESSION[$key]);
326 // Running code in different context
327 $scope = function() {
328 extract( func_get_arg(1) );
329 $_GET = $_REQUEST = array(
330 "url" => $url->getUrl(),
332 "links" => "preserve",
335 "submit" => "Create Feed"
338 require func_get_arg(0);
339 $json = ob_get_contents();
344 $json = $scope("inc/3rdparty/makefulltextfeed.php", array("url" => $url));
346 // Clearing and restoring context
347 foreach ($GLOBALS as $key => $value) {
348 if($key != "GLOBALS" && $key != "_SESSION" ) {
349 unset($GLOBALS[$key]);
352 foreach ($REAL as $key => $value) {
353 $GLOBALS[$key] = $value;
356 // Clearing and restoring session
357 if (isset($REAL_SESSION)) {
358 foreach($_SESSION as $key => $value) {
359 unset($_SESSION[$key]);
362 foreach($REAL_SESSION as $key => $value) {
363 $_SESSION[$key] = $value;
367 return json_decode($json, true);
371 * Returns whether we handle an AJAX (XMLHttpRequest) request.
373 * @return boolean whether we handle an AJAX (XMLHttpRequest) request.
375 public static function isAjaxRequest()
377 return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
383 public static function emptyCache()
385 $files = new RecursiveIteratorIterator(
386 new RecursiveDirectoryIterator(CACHE
, RecursiveDirectoryIterator
::SKIP_DOTS
),
387 RecursiveIteratorIterator
::CHILD_FIRST
390 foreach ($files as $fileInfo) {
391 $todo = ($fileInfo->isDir() ? 'rmdir' : 'unlink');
392 $todo($fileInfo->getRealPath());
395 Tools
::logm('empty cache');
399 public static function generateToken()
401 if (ini_get('open_basedir') === '') {
402 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
403 // alternative to /dev/urandom for Windows
404 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
406 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
410 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
413 return str_replace('+', '', $token);