]> git.immae.eu Git - github/wallabag/wallabag.git/blame - inc/functions.php
possibilité de désactiver la récupération des images d'un article
[github/wallabag/wallabag.git] / inc / functions.php
CommitLineData
24619534 1<?php
2
c8bbe19b 3/**
4 * Permet de générer l'URL de poche pour le bookmarklet
5 */
8046748b 6function get_poche_url()
c8bbe19b 7{
8 $protocol = "http";
9 if(isset($_SERVER['HTTPS'])) {
f0fc5011 10 if($_SERVER['HTTPS'] != "off" && $_SERVER['HTTPS'] != "") {
c8bbe19b 11 $protocol = "https";
12 }
13 }
24619534 14
c8bbe19b 15 return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
24619534 16}
17
24619534 18// function define to retrieve url content
1c182b6c 19function get_external_file($url)
c8bbe19b 20{
1c182b6c 21 $timeout = 15;
24619534 22 // spoofing FireFox 18.0
23 $useragent="Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0";
24
25 if (in_array ('curl', get_loaded_extensions())) {
26 // Fetch feed from URL
27 $curl = curl_init();
28 curl_setopt($curl, CURLOPT_URL, $url);
29 curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
30 curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
31 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
32 curl_setopt($curl, CURLOPT_HEADER, false);
33
34 // FeedBurner requires a proper USER-AGENT...
35 curl_setopt($curl, CURL_HTTP_VERSION_1_1, true);
36 curl_setopt($curl, CURLOPT_ENCODING, "gzip, deflate");
37 curl_setopt($curl, CURLOPT_USERAGENT, $useragent);
38
39 $data = curl_exec($curl);
40
41 $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
42
43 $httpcodeOK = isset($httpcode) and ($httpcode == 200 or $httpcode == 301);
44
45 curl_close($curl);
46 } else {
47
48 // create http context and add timeout and user-agent
1c182b6c 49 $context = stream_context_create(array('http'=>array('timeout' => $timeout,'header'=> "User-Agent: ".$useragent,/*spoot Mozilla Firefox*/'follow_location' => true)));
24619534 50
51 // only download page lesser than 4MB
52 $data = @file_get_contents($url, false, $context, -1, 4000000); // We download at most 4 MB from source.
24619534 53
54 if(isset($http_response_header) and isset($http_response_header[0])) {
55 $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));
56 }
57 }
58
59 // if response is not empty and response is OK
60 if (isset($data) and isset($httpcodeOK) and $httpcodeOK ) {
61
62 // take charset of page and get it
63 preg_match('#<meta .*charset=.*>#Usi', $data, $meta);
64
65 // if meta tag is found
66 if (!empty($meta[0])) {
67 // retrieve encoding in $enc
68 preg_match('#charset="?(.*)"#si', $meta[0], $enc);
69
70 // if charset is found set it otherwise, set it to utf-8
71 $html_charset = (!empty($enc[1])) ? strtolower($enc[1]) : 'utf-8';
72
73 } else {
74 $html_charset = 'utf-8';
75 $enc[1] = '';
76 }
77
78 // replace charset of url to charset of page
79 $data = str_replace('charset='.$enc[1], 'charset='.$html_charset, $data);
80
81 return $data;
82 }
83 else {
84 return FALSE;
85 }
3c8d80ae 86}
87
8046748b 88/**
89 * Préparation de l'URL avec récupération du contenu avant insertion en base
90 */
1c182b6c 91function prepare_url($url, $id)
3c8d80ae 92{
93 $parametres = array();
94 $url = html_entity_decode(trim($url));
95
96 // We remove the annoying parameters added by FeedBurner and GoogleFeedProxy (?utm_source=...)
97 // from shaarli, by sebsauvage
98 $i=strpos($url,'&utm_source='); if ($i!==false) $url=substr($url,0,$i);
99 $i=strpos($url,'?utm_source='); if ($i!==false) $url=substr($url,0,$i);
100 $i=strpos($url,'#xtor=RSS-'); if ($i!==false) $url=substr($url,0,$i);
101
102 $title = $url;
103 if (!preg_match('!^https?://!i', $url))
104 $url = 'http://' . $url;
105
106 $html = Encoding::toUTF8(get_external_file($url,15));
107 if (isset($html) and strlen($html) > 0)
108 {
109 $r = new Readability($html, $url);
4456315b 110 $r->convertLinksToFootnotes = TRUE;
3c8d80ae 111 if($r->init())
112 {
1c182b6c 113 $content = $r->articleContent->innerHTML;
114 $parametres['title'] = $r->articleTitle->innerHTML;
64458521 115 if (DOWNLOAD_PICTURES) {
116 $content = filtre_picture($content, $url, $id);
117 }
118 $parametres['content'] = $content;
1c182b6c 119 return $parametres;
3c8d80ae 120 }
121 }
122
1c182b6c 123 logm('error during url preparation');
124 return FALSE;
125}
126
127/**
128 * On modifie les URLS des images dans le corps de l'article
129 */
130function filtre_picture($content, $url, $id)
131{
132 $matches = array();
133 preg_match_all('#<\s*(img)[^>]+src="([^"]*)"[^>]*>#Si', $content, $matches, PREG_SET_ORDER);
134 foreach($matches as $i => $link)
135 {
136 $link[1] = trim($link[1]);
137 if (!preg_match('#^(([a-z]+://)|(\#))#', $link[1]) )
138 {
139 $absolute_path = get_absolute_link($link[2],$url);
140 $filename = basename(parse_url($absolute_path, PHP_URL_PATH));
141 $directory = create_assets_directory($id);
142 $fullpath = $directory . '/' . $filename;
143 download_pictures($absolute_path, $fullpath);
144 $content = str_replace($matches[$i][2], $fullpath, $content);
145 }
146
147 }
148
149 return $content;
150}
151
152/**
153 * Retourne le lien absolu
154 */
155function get_absolute_link($relative_link, $url)
156{
157 /* return if already absolute URL */
158 if (parse_url($relative_link, PHP_URL_SCHEME) != '') return $relative_link;
159
160 /* queries and anchors */
161 if ($relative_link[0]=='#' || $relative_link[0]=='?') return $url . $relative_link;
162
163 /* parse base URL and convert to local variables:
164 $scheme, $host, $path */
165 extract(parse_url($url));
166
167 /* remove non-directory element from path */
168 $path = preg_replace('#/[^/]*$#', '', $path);
169
170 /* destroy path if relative url points to root */
171 if ($relative_link[0] == '/') $path = '';
172
173 /* dirty absolute URL */
174 $abs = $host . $path . '/' . $relative_link;
175
176 /* replace '//' or '/./' or '/foo/../' with '/' */
177 $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
178 for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
179
180 /* absolute URL is ready! */
181 return $scheme.'://'.$abs;
182}
183
184/**
185 * Téléchargement des images
186 */
187
188function download_pictures($absolute_path, $fullpath)
189{
190 $rawdata = get_external_file($absolute_path);
3c8d80ae 191
1c182b6c 192 if(file_exists($fullpath)) {
193 unlink($fullpath);
194 }
195 $fp = fopen($fullpath, 'x');
196 fwrite($fp, $rawdata);
197 fclose($fp);
198}
199
200/**
201 * Crée un répertoire de médias pour l'article
202 */
203function create_assets_directory($id)
204{
205 $assets_path = ABS_PATH;
206 if(!is_dir($assets_path)) {
207 mkdir($assets_path, 0705);
208 }
209
210 $article_directory = $assets_path . $id;
211 if(!is_dir($article_directory)) {
212 mkdir($article_directory, 0705);
213 }
214
215 return $article_directory;
216}
217
218/**
219 * Suppression du répertoire d'images
220 */
221function remove_directory($directory)
222{
223 if(is_dir($directory)) {
224 $files = array_diff(scandir($directory), array('.','..'));
225 foreach ($files as $file) {
07a19252 226 (is_dir("$directory/$file")) ? remove_directory("$directory/$file") : unlink("$directory/$file");
1c182b6c 227 }
228 return rmdir($directory);
229 }
263d6c67 230}
231
232/**
233 * Appel d'une action (mark as fav, archive, delete)
234 */
1c182b6c 235
cf3180f6 236function action_to_do($action, $id, $url, $token)
263d6c67 237{
238 global $db;
239
240 switch ($action)
241 {
242 case 'add':
243 if ($url == '')
244 continue;
245
cb1348bc 246 # FIXME corriger cette génération d'ID
1c182b6c 247 $req = $db->getHandle()->query("SELECT id FROM entries ORDER BY id DESC");
248 $id = $req->fetchColumn()+1;
249
250 if($parametres_url = prepare_url($url, $id)) {
251 $sql_action = 'INSERT INTO entries ( id, url, title, content ) VALUES (?,?, ?, ?)';
252 $params_action = array($id,$url, $parametres_url['title'], $parametres_url['content']);
253 }
254
a81cd067 255 logm('add link ' . $url);
263d6c67 256 break;
257 case 'delete':
cf3180f6 258 if (verif_token($token)) {
1c182b6c 259 remove_directory(ABS_PATH . $id);
cf3180f6 260 $sql_action = "DELETE FROM entries WHERE id=?";
261 $params_action = array($id);
a81cd067 262 logm('delete link #' . $id);
cf3180f6 263 }
713b2d69 264 else logm('csrf problem while deleting entry');
263d6c67 265 break;
139769aa 266 case 'toggle_fav' :
267 if (verif_token($token)) {
268 $sql_action = "UPDATE entries SET is_fav=~is_fav WHERE id=?";
269 $params_action = array($id);
a81cd067 270 logm('mark as favorite link #' . $id);
139769aa 271 }
713b2d69 272 else logm('csrf problem while fav entry');
139769aa 273 break;
274 case 'toggle_archive' :
275 if (verif_token($token)) {
276 $sql_action = "UPDATE entries SET is_read=~is_read WHERE id=?";
277 $params_action = array($id);
a81cd067 278 logm('archive link #' . $id);
139769aa 279 }
713b2d69 280 else logm('csrf problem while archive entry');
139769aa 281 break;
263d6c67 282 default:
283 break;
284 }
285
286 try
287 {
288 # action query
289 if (isset($sql_action))
290 {
291 $query = $db->getHandle()->prepare($sql_action);
292 $query->execute($params_action);
293 }
294 }
295 catch (Exception $e)
296 {
713b2d69 297 logm('action query error : '.$e->getMessage());
263d6c67 298 }
299}
300
301/**
302 * Détermine quels liens afficher : home, fav ou archives
303 */
9fee2e72 304function display_view($view)
263d6c67 305{
306 global $db;
307
139769aa 308 switch ($_SESSION['sort'])
309 {
310 case 'ia':
311 $order = 'ORDER BY id';
312 break;
313 case 'id':
314 $order = 'ORDER BY id DESC';
315 break;
316 case 'ta':
317 $order = 'ORDER BY lower(title)';
318 break;
319 case 'td':
320 $order = 'ORDER BY lower(title) DESC';
321 break;
322 default:
323 $order = 'ORDER BY id';
324 break;
325 }
326
9fee2e72 327 switch ($view)
263d6c67 328 {
329 case 'archive':
139769aa 330 $sql = "SELECT * FROM entries WHERE is_read=? " . $order;
263d6c67 331 $params = array(-1);
332 break;
333 case 'fav' :
139769aa 334 $sql = "SELECT * FROM entries WHERE is_fav=? " . $order;
263d6c67 335 $params = array(-1);
336 break;
337 default:
139769aa 338 $sql = "SELECT * FROM entries WHERE is_read=? " . $order;
263d6c67 339 $params = array(0);
340 break;
341 }
342
343 # view query
344 try
345 {
346 $query = $db->getHandle()->prepare($sql);
347 $query->execute($params);
348 $entries = $query->fetchAll();
349 }
350 catch (Exception $e)
351 {
713b2d69 352 logm('view query error : '.$e->getMessage());
263d6c67 353 }
354
355 return $entries;
356}
357
358/**
359 * Récupère un article en fonction d'un ID
360 */
361function get_article($id)
362{
363 global $db;
364
365 $entry = NULL;
366 $sql = "SELECT * FROM entries WHERE id=?";
367 $params = array(intval($id));
368
369 # view article query
370 try
371 {
372 $query = $db->getHandle()->prepare($sql);
373 $query->execute($params);
374 $entry = $query->fetchAll();
375 }
376 catch (Exception $e)
377 {
713b2d69 378 logm('get article query error : '.$e->getMessage());
263d6c67 379 }
380
381 return $entry;
cf3180f6 382}
383
384/**
385 * Vérifie si le jeton passé en $_POST correspond à celui en session
386 */
387function verif_token($token)
388{
389 if(isset($_SESSION['token_poche']) && isset($_SESSION['token_time_poche']) && isset($token))
390 {
391 if($_SESSION['token_poche'] == $token)
392 {
393 $old_timestamp = time() - (15*60);
394 if($_SESSION['token_time_poche'] >= $old_timestamp)
395 {
396 return TRUE;
397 }
643e3037 398 else {
399 session_destroy();
713b2d69 400 logm('session expired');
643e3037 401 }
cf3180f6 402 }
713b2d69 403 else {
404 logm('token error : the token is different');
405 return FALSE;
406 }
407 }
408 else {
409 logm('token error : the token is not here');
410 return FALSE;
cf3180f6 411 }
713b2d69 412}
413
414function logm($message)
415{
416 $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."\n";
a81cd067 417 file_put_contents('./log.txt',$t,FILE_APPEND);
c8bbe19b 418}