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