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