4 * Permet de générer l'URL de poche pour le bookmarklet
6 function get_poche_url()
9 if(isset($_SERVER['HTTPS'])) {
10 if($_SERVER['HTTPS'] != "off" && $_SERVER['HTTPS'] != "") {
15 return $protocol . "://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
18 // function define to retrieve url content
19 function get_external_file($url)
22 // spoofing FireFox 18.0
23 $useragent="Mozilla/5.0 (Windows NT 5.1; rv:18.0) Gecko/20100101 Firefox/18.0";
25 if (in_array ('curl', get_loaded_extensions())) {
26 // Fetch feed from URL
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);
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);
39 $data = curl_exec($curl);
41 $httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE
);
43 $httpcodeOK = isset($httpcode) and ($httpcode == 200 or $httpcode == 301);
48 // create http context and add timeout and user-agent
49 $context = stream_context_create(array('http'=>array('timeout' => $timeout,'header'=> "User-Agent: ".$useragent,/*spoot Mozilla Firefox*/'follow_location' => true)));
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.
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));
59 // if response is not empty and response is OK
60 if (isset($data) and isset($httpcodeOK) and $httpcodeOK ) {
62 // take charset of page and get it
63 preg_match('#<meta .*charset=.*>#Usi', $data, $meta);
65 // if meta tag is found
66 if (!empty($meta[0])) {
67 // retrieve encoding in $enc
68 preg_match('#charset="?(.*)"#si', $meta[0], $enc);
70 // if charset is found set it otherwise, set it to utf-8
71 $html_charset = (!empty($enc[1])) ? strtolower($enc[1]) : 'utf-8';
74 $html_charset = 'utf-8';
78 // replace charset of url to charset of page
79 $data = str_replace('charset='.$enc[1], 'charset='.$html_charset, $data);
89 * Préparation de l'URL avec récupération du contenu avant insertion en base
91 function prepare_url($url, $id)
93 $parametres = array();
94 $url = html_entity_decode(trim($url));
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);
103 if (!preg_match('!^https?://!i', $url))
104 $url = 'http://' . $url;
106 $html = Encoding
::toUTF8(get_external_file($url,15));
107 if (isset($html) and strlen($html) > 0)
109 $r = new Readability($html, $url);
110 $r->convertLinksToFootnotes
= TRUE;
113 $content = $r->articleContent
->innerHTML
;
114 $parametres['title'] = $r->articleTitle
->innerHTML
;
115 $parametres['content'] = filtre_picture($content, $url, $id);
120 logm('error during url preparation');
125 * On modifie les URLS des images dans le corps de l'article
127 function filtre_picture($content, $url, $id)
130 preg_match_all('#<\s*(img)[^>]+src="([^"]*)"[^>]*>#Si', $content, $matches, PREG_SET_ORDER
);
131 foreach($matches as $i => $link)
133 $link[1] = trim($link[1]);
134 if (!preg_match('#^(([a-z]+://)|(\#))#', $link[1]) )
136 $absolute_path = get_absolute_link($link[2],$url);
137 $filename = basename(parse_url($absolute_path, PHP_URL_PATH
));
138 $directory = create_assets_directory($id);
139 $fullpath = $directory . '/' . $filename;
140 download_pictures($absolute_path, $fullpath);
141 $content = str_replace($matches[$i][2], $fullpath, $content);
150 * Retourne le lien absolu
152 function get_absolute_link($relative_link, $url)
154 /* return if already absolute URL */
155 if (parse_url($relative_link, PHP_URL_SCHEME
) != '') return $relative_link;
157 /* queries and anchors */
158 if ($relative_link[0]=='#' || $relative_link[0]=='?') return $url . $relative_link;
160 /* parse base URL and convert to local variables:
161 $scheme, $host, $path */
162 extract(parse_url($url));
164 /* remove non-directory element from path */
165 $path = preg_replace('#/[^/]*$#', '', $path);
167 /* destroy path if relative url points to root */
168 if ($relative_link[0] == '/') $path = '';
170 /* dirty absolute URL */
171 $abs = $host . $path . '/' . $relative_link;
173 /* replace '//' or '/./' or '/foo/../' with '/' */
174 $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
175 for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}
177 /* absolute URL is ready! */
178 return $scheme.'://'.$abs;
182 * Téléchargement des images
185 function download_pictures($absolute_path, $fullpath)
187 $rawdata = get_external_file($absolute_path);
189 if(file_exists($fullpath)) {
192 $fp = fopen($fullpath, 'x');
193 fwrite($fp, $rawdata);
198 * Crée un répertoire de médias pour l'article
200 function create_assets_directory($id)
202 $assets_path = ABS_PATH
;
203 if(!is_dir($assets_path)) {
204 mkdir($assets_path, 0705);
207 $article_directory = $assets_path . $id;
208 if(!is_dir($article_directory)) {
209 mkdir($article_directory, 0705);
212 return $article_directory;
216 * Suppression du répertoire d'images
218 function remove_directory($directory)
220 if(is_dir($directory)) {
221 $files = array_diff(scandir($directory), array('.','..'));
222 foreach ($files as $file) {
223 (is_dir("$directory/$file")) ? remove_directory("$directory/$file") : unlink("$directory/$file");
225 return rmdir($directory);
230 * Appel d'une action (mark as fav, archive, delete)
233 function action_to_do($action, $id, $url, $token)
243 $req = $db->getHandle()->query("SELECT id FROM entries ORDER BY id DESC
");
244 $id = $req->fetchColumn()+1;
246 if($parametres_url = prepare_url($url, $id)) {
247 $sql_action = 'INSERT INTO entries ( id, url, title, content ) VALUES (?,?, ?, ?)';
248 $params_action = array($id,$url, $parametres_url['title'], $parametres_url['content']);
251 logm('add link ' . $url);
254 if (verif_token($token)) {
255 remove_directory(ABS_PATH . $id);
256 $sql_action = "DELETE FROM entries WHERE id
=?";
257 $params_action = array($id);
258 logm('delete link #' . $id);
260 else logm('csrf problem while deleting entry');
263 if (verif_token($token)) {
264 $sql_action = "UPDATE entries SET is_fav
=~is_fav WHERE id
=?";
265 $params_action = array($id);
266 logm('mark as favorite link #' . $id);
268 else logm('csrf problem while fav entry');
270 case 'toggle_archive' :
271 if (verif_token($token)) {
272 $sql_action = "UPDATE entries SET is_read
=~is_read WHERE id
=?";
273 $params_action = array($id);
274 logm('archive link #' . $id);
276 else logm('csrf problem while archive entry');
285 if (isset($sql_action))
287 $query = $db->getHandle()->prepare($sql_action);
288 $query->execute($params_action);
293 logm('action query error : '.$e->getMessage());
298 * Détermine quels liens afficher : home, fav ou archives
300 function display_view($view)
304 switch ($_SESSION['sort'])
307 $order = 'ORDER BY id';
310 $order = 'ORDER BY id DESC';
313 $order = 'ORDER BY lower(title)';
316 $order = 'ORDER BY lower(title) DESC';
319 $order = 'ORDER BY id';
326 $sql = "SELECT
* FROM entries WHERE is_read
=? " . $order;
330 $sql = "SELECT
* FROM entries WHERE is_fav
=? " . $order;
334 $sql = "SELECT
* FROM entries WHERE is_read
=? " . $order;
342 $query = $db->getHandle()->prepare($sql);
343 $query->execute($params);
344 $entries = $query->fetchAll();
348 logm('view query error : '.$e->getMessage());
355 * Récupère un article en fonction d'un ID
357 function get_article($id)
362 $sql = "SELECT
* FROM entries WHERE id
=?";
363 $params = array(intval($id));
368 $query = $db->getHandle()->prepare($sql);
369 $query->execute($params);
370 $entry = $query->fetchAll();
374 logm('get article query error : '.$e->getMessage());
381 * Vérifie si le jeton passé en $_POST correspond à celui en session
383 function verif_token($token)
385 if(isset($_SESSION['token_poche']) && isset($_SESSION['token_time_poche']) && isset($token))
387 if($_SESSION['token_poche'] == $token)
389 $old_timestamp = time() - (15*60);
390 if($_SESSION['token_time_poche'] >= $old_timestamp)
396 logm('session expired');
400 logm('token error : the token is different');
405 logm('token error : the token is not here');
410 function logm($message)
412 $t = strval(date('Y/m/d_H:i:s')).' - '.$_SERVER["REMOTE_ADDR
"].' - '.strval($message)."\n
";
413 file_put_contents('./log.txt',$t,FILE_APPEND);