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 $scriptname = str_replace('/index.php', '/', $_SERVER["SCRIPT_NAME"]);
60 if (!isset($_SERVER["HTTP_HOST"])) {
64 $host = (isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_X_FORWARDED_HOST'] : (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['SERVER_NAME']));
66 if (strpos($host, ':') !== false) {
70 return 'http' . ($https ? 's' : '') . '://'
71 . $host . $serverport . $scriptname;
79 public static function redirect($url = '')
82 $url = (empty($_SERVER['HTTP_REFERER'])?'?':$_SERVER['HTTP_REFERER']);
83 if (isset($_POST['returnurl'])) {
84 $url = $_POST['returnurl'];
89 if (empty($url) || parse_url($url, PHP_URL_QUERY
) === $_SERVER['QUERY_STRING']) {
90 $url = Tools
::getPocheUrl();
93 if (substr($url, 0, 1) !== '?') {
94 $ref = Tools
::getPocheUrl();
95 if (substr($url, 0, strlen($ref)) !== $ref) {
100 self
::logm('redirect to ' . $url);
101 header('Location: '.$url);
106 * Returns name of the template file to display
111 public static function getTplFile($view)
114 'install', 'import', 'export', 'config', 'tags',
115 'edit-tags', 'view', 'login', 'error'
118 return (in_array($view, $views) ? $view . '.twig' : 'home.twig');
122 * Download a file (typically, for downloading pictures on web server)
125 * @return bool|mixed|string
127 public static function getFile($url)
130 $useragent = "Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0";
132 if (in_array ('curl', get_loaded_extensions())) {
133 # Fetch feed from URL
135 curl_setopt($curl, CURLOPT_URL
, $url);
136 curl_setopt($curl, CURLOPT_TIMEOUT
, $timeout);
137 if (!ini_get('open_basedir') && !ini_get('safe_mode')) {
138 curl_setopt($curl, CURLOPT_FOLLOWLOCATION
, true);
140 curl_setopt($curl, CURLOPT_RETURNTRANSFER
, true);
141 curl_setopt($curl, CURLOPT_HEADER
, false);
143 # for ssl, do not verified certificate
144 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, FALSE);
145 curl_setopt($curl, CURLOPT_AUTOREFERER
, TRUE );
147 # FeedBurner requires a proper USER-AGENT...
148 curl_setopt($curl, CURL_HTTP_VERSION_1_1
, true);
149 curl_setopt($curl, CURLOPT_ENCODING
, "gzip, deflate");
150 curl_setopt($curl, CURLOPT_USERAGENT
, $useragent);
152 $data = curl_exec($curl);
153 $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE
);
154 $httpcodeOK = isset($httpcode) and ($httpcode == 200 or $httpcode == 301);
157 # create http context and add timeout and user-agent
158 $context = stream_context_create(
161 'timeout' => $timeout,
162 'header' => "User-Agent: " . $useragent,
163 'follow_location' => true
166 'verify_peer' => false,
167 'allow_self_signed' => true
172 # only download page lesser than 4MB
173 $data = @file_get_contents($url, false, $context, -1, 4000000);
175 if (isset($http_response_header) and isset($http_response_header[0])) {
176 $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));
180 # if response is not empty and response is OK
181 if (isset($data) and isset($httpcodeOK) and $httpcodeOK) {
183 # take charset of page and get it
184 preg_match('#<meta .*charset=.*>#Usi', $data, $meta);
186 # if meta tag is found
187 if (!empty($meta[0])) {
188 preg_match('#charset="?(.*)"#si', $meta[0], $encoding);
189 # if charset is found set it otherwise, set it to utf-8
190 $html_charset = (!empty($encoding[1])) ? strtolower($encoding[1]) : 'utf-8';
191 if (empty($encoding[1])) $encoding[1] = 'utf-8';
193 $html_charset = 'utf-8';
197 # replace charset of url to charset of page
198 $data = str_replace('charset=' . $encoding[1], 'charset=' . $html_charset, $data);
208 * Headers for JSON export
212 public static function renderJson($data)
214 header('Cache-Control: no-cache, must-revalidate');
215 header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
216 header('Content-type: application/json; charset=UTF-8');
217 echo json_encode($data);
222 * Create new line in log file
226 public static function logm($message)
228 if (DEBUG_POCHE
&& php_sapi_name() != 'cli') {
229 $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n";
230 file_put_contents(CACHE
. '/log.txt', $t, FILE_APPEND
);
231 error_log('DEBUG POCHE : ' . $message);
236 * Encode a URL by using a salt
241 public static function encodeString($string)
243 return sha1($string . SALT
);
250 * @param string $default
253 public static function checkVar($var, $default = '')
255 return ((isset($_REQUEST["$var"])) ? htmlentities($_REQUEST["$var"]) : $default);
259 * Returns the domain name for a URL
264 public static function getDomain($url)
266 return parse_url($url, PHP_URL_HOST
);
270 * For a given text, we calculate reading time for an article
275 public static function getReadingTime($text)
277 return floor(str_word_count(strip_tags($text)) / 200);
281 * Returns the correct header for a status code
283 * @param $status_code
285 private static function _status($status_code)
287 if (strpos(php_sapi_name(), 'apache') !== false) {
289 header('HTTP/1.0 '.$status_code);
293 header('Status: '.$status_code);
298 * Download the sqlite database
300 public static function downloadDb()
302 header('Content-Disposition: attachment; filename="poche.sqlite.gz"');
305 header('Content-Transfer-Encoding: binary');
306 header('Content-Type: application/octet-stream');
307 echo gzencode(file_get_contents(STORAGE_SQLITE
));
313 * Get the content for a given URL (by a call to FullTextFeed)
318 public static function getPageContent(Url
$url)
320 // Saving and clearing context
322 foreach( $GLOBALS as $key => $value ) {
323 if( $key != 'GLOBALS' && $key != '_SESSION' && $key != 'HTTP_SESSION_VARS' ) {
324 $GLOBALS[$key] = array();
325 $REAL[$key] = $value;
328 // Saving and clearing session
329 if (isset($_SESSION)) {
330 $REAL_SESSION = array();
331 foreach( $_SESSION as $key => $value ) {
332 $REAL_SESSION[$key] = $value;
333 unset($_SESSION[$key]);
337 // Running code in different context
338 $scope = function() {
339 extract( func_get_arg(1) );
340 $_GET = $_REQUEST = array(
341 "url" => $url->getUrl(),
343 "links" => "preserve",
346 "submit" => "Create Feed"
349 require func_get_arg(0);
350 $json = ob_get_contents();
355 $json = $scope("inc/3rdparty/makefulltextfeed.php", array("url" => $url));
357 // Clearing and restoring context
358 foreach ($GLOBALS as $key => $value) {
359 if($key != "GLOBALS" && $key != "_SESSION" ) {
360 unset($GLOBALS[$key]);
363 foreach ($REAL as $key => $value) {
364 $GLOBALS[$key] = $value;
367 // Clearing and restoring session
368 if (isset($REAL_SESSION)) {
369 foreach($_SESSION as $key => $value) {
370 unset($_SESSION[$key]);
373 foreach($REAL_SESSION as $key => $value) {
374 $_SESSION[$key] = $value;
378 return json_decode($json, true);
382 * Returns whether we handle an AJAX (XMLHttpRequest) request.
384 * @return boolean whether we handle an AJAX (XMLHttpRequest) request.
386 public static function isAjaxRequest()
388 return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
394 public static function emptyCache()
396 $files = new RecursiveIteratorIterator(
397 new RecursiveDirectoryIterator(CACHE
, RecursiveDirectoryIterator
::SKIP_DOTS
),
398 RecursiveIteratorIterator
::CHILD_FIRST
401 foreach ($files as $fileInfo) {
402 $todo = ($fileInfo->isDir() ? 'rmdir' : 'unlink');
403 $todo($fileInfo->getRealPath());
406 Tools
::logm('empty cache');
410 public static function generateToken()
412 if (ini_get('open_basedir') === '') {
413 if (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN') {
414 // alternative to /dev/urandom for Windows
415 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
417 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
421 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
424 return str_replace('+', '', $token);