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 || $_SERVER["SERVER_PORT"] == HTTP_PORT
55 || ($https && $_SERVER["SERVER_PORT"] == '443')
56 || ($https && $_SERVER["SERVER_PORT"]==SSL_PORT
) //Custom HTTPS port detection
57 ? '' : ':' . $_SERVER["SERVER_PORT"]);
59 if (isset($_SERVER["HTTP_X_FORWARDED_PORT"])) {
60 $serverport = ':' . $_SERVER["HTTP_X_FORWARDED_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', 'about'
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 * Get the content for a given URL (by a call to FullTextFeed)
308 public static function getPageContent(Url
$url)
310 // Saving and clearing context
312 foreach( $GLOBALS as $key => $value ) {
313 if( $key != 'GLOBALS' && $key != '_SESSION' && $key != 'HTTP_SESSION_VARS' ) {
314 $GLOBALS[$key] = array();
315 $REAL[$key] = $value;
318 // Saving and clearing session
319 if (isset($_SESSION)) {
320 $REAL_SESSION = array();
321 foreach( $_SESSION as $key => $value ) {
322 $REAL_SESSION[$key] = $value;
323 unset($_SESSION[$key]);
327 // Running code in different context
328 $scope = function() {
329 extract( func_get_arg(1) );
330 $_GET = $_REQUEST = array(
331 "url" => $url->getUrl(),
333 "links" => "preserve",
336 "submit" => "Create Feed"
339 require func_get_arg(0);
340 $json = ob_get_contents();
345 $json = $scope("inc/3rdparty/makefulltextfeed.php", array("url" => $url));
347 // Clearing and restoring context
348 foreach ($GLOBALS as $key => $value) {
349 if($key != "GLOBALS" && $key != "_SESSION" ) {
350 unset($GLOBALS[$key]);
353 foreach ($REAL as $key => $value) {
354 $GLOBALS[$key] = $value;
357 // Clearing and restoring session
358 if (isset($REAL_SESSION)) {
359 foreach($_SESSION as $key => $value) {
360 unset($_SESSION[$key]);
363 foreach($REAL_SESSION as $key => $value) {
364 $_SESSION[$key] = $value;
368 return json_decode($json, true);
372 * Returns whether we handle an AJAX (XMLHttpRequest) request.
374 * @return boolean whether we handle an AJAX (XMLHttpRequest) request.
376 public static function isAjaxRequest()
378 return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
384 public static function emptyCache()
386 $files = new RecursiveIteratorIterator(
387 new RecursiveDirectoryIterator(CACHE
, RecursiveDirectoryIterator
::SKIP_DOTS
),
388 RecursiveIteratorIterator
::CHILD_FIRST
391 foreach ($files as $fileInfo) {
392 $todo = ($fileInfo->isDir() ? 'rmdir' : 'unlink');
393 $todo($fileInfo->getRealPath());
396 Tools
::logm('empty cache');
400 public static function generateToken()
402 if (ini_get('open_basedir') === '') {
403 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
404 // alternative to /dev/urandom for Windows
405 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
407 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
411 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
414 return str_replace('+', '', $token);