]> git.immae.eu Git - github/wallabag/wallabag.git/blame - inc/functions.php
Merge branch 'dev'
[github/wallabag/wallabag.git] / inc / functions.php
CommitLineData
24619534 1<?php
6f87a197 2/**
3 * poche, a read it later open source system
4 *
5 * @category poche
6 * @author Nicolas Lœuillet <support@inthepoche.com>
7 * @copyright 2013
8 * @license http://www.wtfpl.net/ see COPYING file
9 */
24619534 10
c8bbe19b 11/**
12 * Permet de générer l'URL de poche pour le bookmarklet
13 */
8046748b 14function get_poche_url()
c8bbe19b 15{
16 $protocol = "http";
17 if(isset($_SERVER['HTTPS'])) {
f0fc5011 18 if($_SERVER['HTTPS'] != "off" && $_SERVER['HTTPS'] != "") {
c8bbe19b 19 $protocol = "https";
20 }
21 }
24619534 22
c8bbe19b 23 return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
24619534 24}
25
aa8c9f2a
NL
26function encode_string($string)
27{
28 return sha1($string . SALT);
29}
30
24619534 31// function define to retrieve url content
1c182b6c 32function get_external_file($url)
c8bbe19b 33{
1c182b6c 34 $timeout = 15;
24619534 35 // spoofing FireFox 18.0
36 $useragent="Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0";
37
38 if (in_array ('curl', get_loaded_extensions())) {
39 // Fetch feed from URL
40 $curl = curl_init();
41 curl_setopt($curl, CURLOPT_URL, $url);
42 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
43 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
44 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
45 curl_setopt($curl, CURLOPT_HEADER, false);
46
2987031b 47 // FOR SSL do not verified certificate
4ddbd267 48 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
2987031b 49 curl_setopt($curl, CURLOPT_AUTOREFERER, TRUE );
4ddbd267 50
24619534 51 // FeedBurner requires a proper USER-AGENT...
52 curl_setopt($curl, CURL_HTTP_VERSION_1_1, true);
53 curl_setopt($curl, CURLOPT_ENCODING, "gzip, deflate");
54 curl_setopt($curl, CURLOPT_USERAGENT, $useragent);
55
56 $data = curl_exec($curl);
57
58 $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
59
60 $httpcodeOK = isset($httpcode) and ($httpcode == 200 or $httpcode == 301);
61
62 curl_close($curl);
63 } else {
64
65 // create http context and add timeout and user-agent
4ddbd267 66 $context = stream_context_create(array(
2987031b 67 'http'=>array('timeout' => $timeout,
68 'header'=> "User-Agent: ".$useragent, /*spoot Mozilla Firefox*/
69 'follow_location' => true),
70 // FOR SSL do not verified certificate
71 'ssl' => array('verify_peer' => false,
72 'allow_self_signed' => true)
73 )
74 );
24619534 75
76 // only download page lesser than 4MB
77 $data = @file_get_contents($url, false, $context, -1, 4000000); // We download at most 4 MB from source.
24619534 78
79 if(isset($http_response_header) and isset($http_response_header[0])) {
80 $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));
81 }
82 }
83
84 // if response is not empty and response is OK
85 if (isset($data) and isset($httpcodeOK) and $httpcodeOK ) {
86
87 // take charset of page and get it
88 preg_match('#<meta .*charset=.*>#Usi', $data, $meta);
89
90 // if meta tag is found
91 if (!empty($meta[0])) {
92 // retrieve encoding in $enc
93 preg_match('#charset="?(.*)"#si', $meta[0], $enc);
94
95 // if charset is found set it otherwise, set it to utf-8
96 $html_charset = (!empty($enc[1])) ? strtolower($enc[1]) : 'utf-8';
97
98 } else {
99 $html_charset = 'utf-8';
100 $enc[1] = '';
101 }
102
103 // replace charset of url to charset of page
104 $data = str_replace('charset='.$enc[1], 'charset='.$html_charset, $data);
105
106 return $data;
107 }
108 else {
109 return FALSE;
110 }
3c8d80ae 111}
112
8046748b 113/**
114 * Préparation de l'URL avec récupération du contenu avant insertion en base
115 */
d06f30ef 116function prepare_url($url)
3c8d80ae 117{
118 $parametres = array();
e4d2565e 119 $url = html_entity_decode(trim($url));
3c8d80ae 120
121 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
122 // from shaarli, by sebsauvage
123 $i=strpos($url,'&utm_source='); if ($i!==false) $url=substr($url,0,$i);
124 $i=strpos($url,'?utm_source='); if ($i!==false) $url=substr($url,0,$i);
125 $i=strpos($url,'#xtor=RSS-'); if ($i!==false) $url=substr($url,0,$i);
126
e4d2565e 127 $title = $url;
2987031b 128 $html = Encoding::toUTF8(get_external_file($url,15));
129 // If get_external_file if not able to retrieve HTTPS content try the same URL with HTTP protocol
130 if (!preg_match('!^https?://!i', $url) && (!isset($html) || strlen($html) <= 0)) {
131 $url = 'http://' . $url;
132 $html = Encoding::toUTF8(get_external_file($url,15));
133 }
3c8d80ae 134
494e21b4 135 if (function_exists('tidy_parse_string')) {
136 $tidy = tidy_parse_string($html, array(), 'UTF8');
137 $tidy->cleanRepair();
138 $html = $tidy->value;
139 }
140
3c8d80ae 141 if (isset($html) and strlen($html) > 0)
142 {
143 $r = new Readability($html, $url);
2987031b 144
d06f30ef 145 $r->convertLinksToFootnotes = CONVERT_LINKS_FOOTNOTES;
2987031b 146 $r->revertForcedParagraphElements = REVERT_FORCED_PARAGRAPH_ELEMENTS;
4ddbd267 147
3c8d80ae 148 if($r->init())
149 {
1c182b6c 150 $content = $r->articleContent->innerHTML;
151 $parametres['title'] = $r->articleTitle->innerHTML;
64458521 152 $parametres['content'] = $content;
1c182b6c 153 return $parametres;
3c8d80ae 154 }
155 }
156
1c182b6c 157 return FALSE;
158}
159
160/**
161 * On modifie les URLS des images dans le corps de l'article
162 */
163function filtre_picture($content, $url, $id)
164{
165 $matches = array();
166 preg_match_all('#<\s*(img)[^>]+src="([^"]*)"[^>]*>#Si', $content, $matches, PREG_SET_ORDER);
167 foreach($matches as $i => $link)
168 {
169 $link[1] = trim($link[1]);
170 if (!preg_match('#^(([a-z]+://)|(\#))#', $link[1]) )
171 {
172 $absolute_path = get_absolute_link($link[2],$url);
173 $filename = basename(parse_url($absolute_path, PHP_URL_PATH));
174 $directory = create_assets_directory($id);
175 $fullpath = $directory . '/' . $filename;
176 download_pictures($absolute_path, $fullpath);
177 $content = str_replace($matches[$i][2], $fullpath, $content);
178 }
179
180 }
181
182 return $content;
183}
184
185/**
186 * Retourne le lien absolu
187 */
188function get_absolute_link($relative_link, $url)
189{
190 /* return if already absolute URL */
191 if (parse_url($relative_link, PHP_URL_SCHEME) != '') return $relative_link;
192
193 /* queries and anchors */
194 if ($relative_link[0]=='#' || $relative_link[0]=='?') return $url . $relative_link;
195
196 /* parse base URL and convert to local variables:
197 $scheme, $host, $path */
198 extract(parse_url($url));
199
200 /* remove non-directory element from path */
201 $path = preg_replace('#/[^/]*$#', '', $path);
202
203 /* destroy path if relative url points to root */
204 if ($relative_link[0] == '/') $path = '';
205
206 /* dirty absolute URL */
207 $abs = $host . $path . '/' . $relative_link;
208
209 /* replace '//' or '/./' or '/foo/../' with '/' */
210 $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
211 for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
212
213 /* absolute URL is ready! */
214 return $scheme.'://'.$abs;
215}
216
217/**
218 * Téléchargement des images
219 */
220
221function download_pictures($absolute_path, $fullpath)
222{
223 $rawdata = get_external_file($absolute_path);
3c8d80ae 224
1c182b6c 225 if(file_exists($fullpath)) {
226 unlink($fullpath);
227 }
228 $fp = fopen($fullpath, 'x');
229 fwrite($fp, $rawdata);
230 fclose($fp);
231}
232
233/**
234 * Crée un répertoire de médias pour l'article
235 */
236function create_assets_directory($id)
237{
238 $assets_path = ABS_PATH;
239 if(!is_dir($assets_path)) {
240 mkdir($assets_path, 0705);
241 }
242
243 $article_directory = $assets_path . $id;
244 if(!is_dir($article_directory)) {
245 mkdir($article_directory, 0705);
246 }
247
248 return $article_directory;
249}
250
251/**
252 * Suppression du répertoire d'images
253 */
254function remove_directory($directory)
255{
256 if(is_dir($directory)) {
257 $files = array_diff(scandir($directory), array('.','..'));
258 foreach ($files as $file) {
07a19252 259 (is_dir("$directory/$file")) ? remove_directory("$directory/$file") : unlink("$directory/$file");
1c182b6c 260 }
261 return rmdir($directory);
262 }
263d6c67 263}
264
a1953dff 265function display_view($view, $id = 0, $full_head = 'yes')
266{
f0070a15 267 global $tpl, $store, $msg;
a1953dff 268
269 switch ($view)
270 {
44e77bfa 271 case 'export':
272 $entries = $store->retrieveAll();
6f87a197 273 $tpl->assign('export', myTool::renderJson($entries));
44e77bfa 274 $tpl->draw('export');
275 logm('export view');
276 break;
016989b7 277 case 'config':
278 $tpl->assign('load_all_js', 0);
279 $tpl->draw('head');
280 $tpl->draw('home');
281 $tpl->draw('config');
282 $tpl->draw('js');
283 $tpl->draw('footer');
284 logm('config view');
44e77bfa 285 break;
a1953dff 286 case 'view':
14890de3 287 $entry = $store->retrieveOneById($id);
a1953dff 288
289 if ($entry != NULL) {
14890de3 290 $tpl->assign('id', $entry['id']);
291 $tpl->assign('url', $entry['url']);
292 $tpl->assign('title', $entry['title']);
494e21b4 293 $content = $entry['content'];
294 if (function_exists('tidy_parse_string')) {
295 $tidy = tidy_parse_string($content, array('indent'=>true, 'show-body-only' => true), 'UTF8');
296 $tidy->cleanRepair();
297 $content = $tidy->value;
298 }
299 $tpl->assign('content', $content);
14890de3 300 $tpl->assign('is_fav', $entry['is_fav']);
301 $tpl->assign('is_read', $entry['is_read']);
a1953dff 302 $tpl->assign('load_all_js', 0);
303 $tpl->draw('view');
304 }
305 else {
306 logm('error in view call : entry is NULL');
307 }
308
309 logm('view link #' . $id);
310 break;
311 default: # home view
14890de3 312 $entries = $store->getEntriesByView($view);
a1953dff 313
314 $tpl->assign('entries', $entries);
315
316 if ($full_head == 'yes') {
317 $tpl->assign('load_all_js', 1);
318 $tpl->draw('head');
319 $tpl->draw('home');
320 }
321
322 $tpl->draw('entries');
323
324 if ($full_head == 'yes') {
325 $tpl->draw('js');
326 $tpl->draw('footer');
327 }
328 break;
329 }
330}
331
263d6c67 332/**
333 * Appel d'une action (mark as fav, archive, delete)
334 */
e4d2565e 335function action_to_do($action, $url, $id = 0)
263d6c67 336{
f0070a15 337 global $store, $msg;
263d6c67 338
339 switch ($action)
340 {
341 case 'add':
342 if ($url == '')
343 continue;
344
6f87a197 345 if (MyTool::isUrl($url)) {
346 if($parametres_url = prepare_url($url)) {
29c6fd46 347 if ($store->add($url, $parametres_url['title'], $parametres_url['content'])) {
348 $last_id = $store->getLastId();
349 if (DOWNLOAD_PICTURES) {
350 $content = filtre_picture($parametres_url['content'], $url, $last_id);
351 }
352 $msg->add('s', 'the link has been added successfully');
6f87a197 353 }
29c6fd46 354 else {
355 $msg->add('e', 'error during insertion : the link wasn\'t added');
356 }
357 }
358 else {
359 $msg->add('e', 'error during url preparation : the link wasn\'t added');
360 logm('error during url preparation');
14890de3 361 }
1c182b6c 362 }
6f87a197 363 else {
29c6fd46 364 $msg->add('e', 'error during url preparation : the link is not valid');
6f87a197 365 logm($url . ' is not a valid url');
366 }
1c182b6c 367
a81cd067 368 logm('add link ' . $url);
263d6c67 369 break;
370 case 'delete':
29c6fd46 371 if ($store->deleteById($id)) {
372 remove_directory(ABS_PATH . $id);
373 $msg->add('s', 'the link has been deleted successfully');
374 logm('delete link #' . $id);
375 }
376 else {
377 $msg->add('e', 'the link wasn\'t deleted');
378 logm('error : can\'t delete link #' . $id);
379 }
263d6c67 380 break;
139769aa 381 case 'toggle_fav' :
14890de3 382 $store->favoriteById($id);
e4d2565e 383 logm('mark as favorite link #' . $id);
139769aa 384 break;
385 case 'toggle_archive' :
14890de3 386 $store->archiveById($id);
e4d2565e 387 logm('archive link #' . $id);
139769aa 388 break;
263d6c67 389 default:
390 break;
391 }
cf3180f6 392}
393
713b2d69 394function logm($message)
395{
396 $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."\n";
a81cd067 397 file_put_contents('./log.txt',$t,FILE_APPEND);
cdcc8d25 398}