3 * poche, a read it later open source system
6 * @author Nicolas Lœuillet <support@inthepoche.com>
8 * @license http://www.wtfpl.net/ see COPYING file
12 * Permet de générer l'URL de poche pour le bookmarklet
14 function get_poche_url()
17 if(isset($_SERVER['HTTPS'])) {
18 if($_SERVER['HTTPS'] != "off" && $_SERVER['HTTPS'] != "") {
23 return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
26 // function define to retrieve url content
27 function get_external_file($url)
30 // spoofing FireFox 18.0
31 $useragent="Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0";
33 if (in_array ('curl', get_loaded_extensions())) {
34 // Fetch feed from URL
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);
42 // FOR SSL do not verified certificate
43 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER
, FALSE);
44 curl_setopt($curl, CURLOPT_AUTOREFERER
, TRUE );
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);
51 $data = curl_exec($curl);
53 $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE
);
55 $httpcodeOK = isset($httpcode) and ($httpcode == 200 or $httpcode == 301);
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)
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.
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));
79 // if response is not empty and response is OK
80 if (isset($data) and isset($httpcodeOK) and $httpcodeOK ) {
82 // take charset of page and get it
83 preg_match('#<meta .*charset=.*>#Usi', $data, $meta);
85 // if meta tag is found
86 if (!empty($meta[0])) {
87 // retrieve encoding in $enc
88 preg_match('#charset="?(.*)"#si', $meta[0], $enc);
90 // if charset is found set it otherwise, set it to utf-8
91 $html_charset = (!empty($enc[1])) ? strtolower($enc[1]) : 'utf-8';
94 $html_charset = 'utf-8';
98 // replace charset of url to charset of page
99 $data = str_replace('charset='.$enc[1], 'charset='.$html_charset, $data);
109 * Préparation de l'URL avec récupération du contenu avant insertion en base
111 function prepare_url($url)
115 $parametres = array();
116 $url = html_entity_decode(trim($url));
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);
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));
132 if (isset($html) and strlen($html) > 0)
134 $r = new Readability($html, $url);
136 $r->convertLinksToFootnotes
= CONVERT_LINKS_FOOTNOTES
;
137 $r->revertForcedParagraphElements
= REVERT_FORCED_PARAGRAPH_ELEMENTS
;
141 $content = $r->articleContent
->innerHTML
;
142 $parametres['title'] = $r->articleTitle
->innerHTML
;
143 $parametres['content'] = $content;
152 * On modifie les URLS des images dans le corps de l'article
154 function filtre_picture($content, $url, $id)
157 preg_match_all('#<\s*(img)[^>]+src="([^"]*)"[^>]*>#Si', $content, $matches, PREG_SET_ORDER
);
158 foreach($matches as $i => $link)
160 $link[1] = trim($link[1]);
161 if (!preg_match('#^(([a-z]+://)|(\#))#', $link[1]) )
163 $absolute_path = get_absolute_link($link[2],$url);
164 $filename = basename(parse_url($absolute_path, PHP_URL_PATH
));
165 $directory = create_assets_directory($id);
166 $fullpath = $directory . '/' . $filename;
167 download_pictures($absolute_path, $fullpath);
168 $content = str_replace($matches[$i][2], $fullpath, $content);
177 * Retourne le lien absolu
179 function get_absolute_link($relative_link, $url)
181 /* return if already absolute URL */
182 if (parse_url($relative_link, PHP_URL_SCHEME
) != '') return $relative_link;
184 /* queries and anchors */
185 if ($relative_link[0]=='#' || $relative_link[0]=='?') return $url . $relative_link;
187 /* parse base URL and convert to local variables:
188 $scheme, $host, $path */
189 extract(parse_url($url));
191 /* remove non-directory element from path */
192 $path = preg_replace('#/[^/]*$#', '', $path);
194 /* destroy path if relative url points to root */
195 if ($relative_link[0] == '/') $path = '';
197 /* dirty absolute URL */
198 $abs = $host . $path . '/' . $relative_link;
200 /* replace '//' or '/./' or '/foo/../' with '/' */
201 $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
202 for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
204 /* absolute URL is ready! */
205 return $scheme.'://'.$abs;
209 * Téléchargement des images
212 function download_pictures($absolute_path, $fullpath)
214 $rawdata = get_external_file($absolute_path);
216 if(file_exists($fullpath)) {
219 $fp = fopen($fullpath, 'x');
220 fwrite($fp, $rawdata);
225 * Crée un répertoire de médias pour l'article
227 function create_assets_directory($id)
229 $assets_path = ABS_PATH
;
230 if(!is_dir($assets_path)) {
231 mkdir($assets_path, 0705);
234 $article_directory = $assets_path . $id;
235 if(!is_dir($article_directory)) {
236 mkdir($article_directory, 0705);
239 return $article_directory;
243 * Suppression du répertoire d'images
245 function remove_directory($directory)
247 if(is_dir($directory)) {
248 $files = array_diff(scandir($directory), array('.','..'));
249 foreach ($files as $file) {
250 (is_dir("$directory/$file")) ? remove_directory("$directory/$file") : unlink("$directory/$file");
252 return rmdir($directory);
256 function display_view($view, $id = 0, $full_head = 'yes')
258 global $tpl, $store, $msg;
263 $entries = $store->retrieveAll();
264 $tpl->assign('export', myTool::renderJson($entries));
265 $tpl->draw('export');
269 $tpl->assign('load_all_js', 0);
272 $tpl->draw('config');
274 $tpl->draw('footer');
278 $entry = $store->retrieveOneById($id);
280 if ($entry != NULL) {
281 $tpl->assign('id', $entry['id']);
282 $tpl->assign('url', $entry['url']);
283 $tpl->assign('title', $entry['title']);
284 $tpl->assign('content', $entry['content']);
285 $tpl->assign('is_fav', $entry['is_fav']);
286 $tpl->assign('is_read', $entry['is_read']);
287 $tpl->assign('load_all_js', 0);
291 logm('error in view call : entry is NULL');
294 logm('view link #' . $id);
297 $entries = $store->getEntriesByView($view);
299 $tpl->assign('entries', $entries);
301 if ($full_head == 'yes') {
302 $tpl->assign('load_all_js', 1);
307 $tpl->draw('entries');
309 if ($full_head == 'yes') {
311 $tpl->draw('footer');
318 * Appel d'une action (mark as fav, archive, delete)
320 function action_to_do($action, $url, $id = 0)
330 if (MyTool::isUrl($url)) {
331 if($parametres_url = prepare_url($url)) {
332 if ($store->add($url, $parametres_url['title'], $parametres_url['content'])) {
333 $last_id = $store->getLastId();
334 if (DOWNLOAD_PICTURES) {
335 $content = filtre_picture($parametres_url['content'], $url, $last_id);
337 $msg->add('s', 'the link has been added successfully');
340 $msg->add('e', 'error during insertion : the link wasn\'t added');
344 $msg->add('e', 'error during url preparation : the link wasn\'t added');
345 logm('error during url preparation');
349 $msg->add('e', 'error during url preparation : the link is not valid');
350 logm($url . ' is not a valid url');
353 logm('add link ' . $url);
356 if ($store->deleteById($id)) {
357 remove_directory(ABS_PATH . $id);
358 $msg->add('s', 'the link has been deleted successfully');
359 logm('delete link #' . $id);
362 $msg->add('e', 'the link wasn\'t deleted');
363 logm('error : can\'t delete link #' . $id);
367 $store->favoriteById($id);
368 $msg->add('s', 'the favorite toggle has been done successfully');
369 logm('mark as favorite link #' . $id);
371 case 'toggle_archive' :
372 $store->archiveById($id);
373 $msg->add('s', 'the archive toggle has been done successfully');
374 logm('archive link #' . $id);
381 function logm($message)
383 $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR
"].' - '.strval($message)."\n
";
384 file_put_contents('./log.txt',$t,FILE_APPEND);