]> git.immae.eu Git - github/wallabag/wallabag.git/blob - inc/functions.php
ec5b3d6a300678518554382c83302a0ce24d5359
[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 // 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
57 $context = stream_context_create(array('http'=>array('timeout' => $timeout,'header'=> "User-Agent: ".$useragent,/*spoot Mozilla Firefox*/'follow_location' => true)));
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.
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 }
94 }
95
96 /**
97 * Préparation de l'URL avec récupération du contenu avant insertion en base
98 */
99 function prepare_url($url)
100 {
101 $parametres = array();
102 $url = html_entity_decode(trim($url));
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
110 $title = $url;
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);
118 $r->convertLinksToFootnotes = CONVERT_LINKS_FOOTNOTES;
119 if($r->init())
120 {
121 $content = $r->articleContent->innerHTML;
122 $parametres['title'] = $r->articleTitle->innerHTML;
123 $parametres['content'] = $content;
124 return $parametres;
125 }
126 }
127
128 logm('error during url preparation');
129 return FALSE;
130 }
131
132 /**
133 * On modifie les URLS des images dans le corps de l'article
134 */
135 function filtre_picture($content, $url, $id)
136 {
137 $matches = array();
138 preg_match_all('#<\s*(img)[^>]+src="([^"]*)"[^>]*>#Si', $content, $matches, PREG_SET_ORDER);
139 foreach($matches as $i => $link)
140 {
141 $link[1] = trim($link[1]);
142 if (!preg_match('#^(([a-z]+://)|(\#))#', $link[1]) )
143 {
144 $absolute_path = get_absolute_link($link[2],$url);
145 $filename = basename(parse_url($absolute_path, PHP_URL_PATH));
146 $directory = create_assets_directory($id);
147 $fullpath = $directory . '/' . $filename;
148 download_pictures($absolute_path, $fullpath);
149 $content = str_replace($matches[$i][2], $fullpath, $content);
150 }
151
152 }
153
154 return $content;
155 }
156
157 /**
158 * Retourne le lien absolu
159 */
160 function get_absolute_link($relative_link, $url)
161 {
162 /* return if already absolute URL */
163 if (parse_url($relative_link, PHP_URL_SCHEME) != '') return $relative_link;
164
165 /* queries and anchors */
166 if ($relative_link[0]=='#' || $relative_link[0]=='?') return $url . $relative_link;
167
168 /* parse base URL and convert to local variables:
169 $scheme, $host, $path */
170 extract(parse_url($url));
171
172 /* remove non-directory element from path */
173 $path = preg_replace('#/[^/]*$#', '', $path);
174
175 /* destroy path if relative url points to root */
176 if ($relative_link[0] == '/') $path = '';
177
178 /* dirty absolute URL */
179 $abs = $host . $path . '/' . $relative_link;
180
181 /* replace '//' or '/./' or '/foo/../' with '/' */
182 $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
183 for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
184
185 /* absolute URL is ready! */
186 return $scheme.'://'.$abs;
187 }
188
189 /**
190 * Téléchargement des images
191 */
192
193 function download_pictures($absolute_path, $fullpath)
194 {
195 $rawdata = get_external_file($absolute_path);
196
197 if(file_exists($fullpath)) {
198 unlink($fullpath);
199 }
200 $fp = fopen($fullpath, 'x');
201 fwrite($fp, $rawdata);
202 fclose($fp);
203 }
204
205 /**
206 * Crée un répertoire de médias pour l'article
207 */
208 function create_assets_directory($id)
209 {
210 $assets_path = ABS_PATH;
211 if(!is_dir($assets_path)) {
212 mkdir($assets_path, 0705);
213 }
214
215 $article_directory = $assets_path . $id;
216 if(!is_dir($article_directory)) {
217 mkdir($article_directory, 0705);
218 }
219
220 return $article_directory;
221 }
222
223 /**
224 * Suppression du répertoire d'images
225 */
226 function remove_directory($directory)
227 {
228 if(is_dir($directory)) {
229 $files = array_diff(scandir($directory), array('.','..'));
230 foreach ($files as $file) {
231 (is_dir("$directory/$file")) ? remove_directory("$directory/$file") : unlink("$directory/$file");
232 }
233 return rmdir($directory);
234 }
235 }
236
237 function display_view($view, $id = 0, $full_head = 'yes')
238 {
239 global $tpl, $store;
240
241 switch ($view)
242 {
243 case 'export':
244 $entries = $store->retrieveAll();
245 $tpl->assign('export', myTool::renderJson($entries));
246 $tpl->draw('export');
247 logm('export view');
248 break;
249 case 'config':
250 $tpl->assign('load_all_js', 0);
251 $tpl->draw('head');
252 $tpl->draw('home');
253 $tpl->draw('config');
254 $tpl->draw('js');
255 $tpl->draw('footer');
256 logm('config view');
257 break;
258 case 'view':
259 $entry = $store->retrieveOneById($id);
260
261 if ($entry != NULL) {
262 $tpl->assign('id', $entry['id']);
263 $tpl->assign('url', $entry['url']);
264 $tpl->assign('title', $entry['title']);
265 $tpl->assign('content', $entry['content']);
266 $tpl->assign('is_fav', $entry['is_fav']);
267 $tpl->assign('is_read', $entry['is_read']);
268 $tpl->assign('load_all_js', 0);
269 $tpl->draw('view');
270 }
271 else {
272 logm('error in view call : entry is NULL');
273 }
274
275 logm('view link #' . $id);
276 break;
277 default: # home view
278 $entries = $store->getEntriesByView($view);
279
280 $tpl->assign('entries', $entries);
281
282 if ($full_head == 'yes') {
283 $tpl->assign('load_all_js', 1);
284 $tpl->draw('head');
285 $tpl->draw('home');
286 }
287
288 $tpl->draw('entries');
289
290 if ($full_head == 'yes') {
291 $tpl->draw('js');
292 $tpl->draw('footer');
293 }
294 break;
295 }
296 }
297
298 /**
299 * Appel d'une action (mark as fav, archive, delete)
300 */
301 function action_to_do($action, $url, $id = 0)
302 {
303 global $store;
304
305 switch ($action)
306 {
307 case 'add':
308 if ($url == '')
309 continue;
310
311 if (MyTool::isUrl($url)) {
312 if($parametres_url = prepare_url($url)) {
313 $store->add($url, $parametres_url['title'], $parametres_url['content']);
314 $last_id = $store->getLastId();
315 if (DOWNLOAD_PICTURES) {
316 $content = filtre_picture($parametres_url['content'], $url, $last_id);
317 }
318 }
319 }
320 else {
321 logm($url . ' is not a valid url');
322 }
323
324 logm('add link ' . $url);
325 break;
326 case 'delete':
327 remove_directory(ABS_PATH . $id);
328 $store->deleteById($id);
329 logm('delete link #' . $id);
330 break;
331 case 'toggle_fav' :
332 $store->favoriteById($id);
333 logm('mark as favorite link #' . $id);
334 break;
335 case 'toggle_archive' :
336 $store->archiveById($id);
337 logm('archive link #' . $id);
338 break;
339 default:
340 break;
341 }
342 }
343
344 function logm($message)
345 {
346 $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR"].' - '.strval($message)."\n";
347 file_put_contents('./log.txt',$t,FILE_APPEND);
348 }