aboutsummaryrefslogtreecommitdiffhomepage
path: root/inc/poche
diff options
context:
space:
mode:
Diffstat (limited to 'inc/poche')
-rwxr-xr-xinc/poche/Database.class.php117
-rwxr-xr-xinc/poche/Poche.class.php663
-rwxr-xr-x[-rw-r--r--]inc/poche/Tools.class.php81
-rwxr-xr-xinc/poche/config.inc.php.new14
-rw-r--r--inc/poche/global.inc.php2
5 files changed, 437 insertions, 440 deletions
diff --git a/inc/poche/Database.class.php b/inc/poche/Database.class.php
index c998fe14..6244df88 100755
--- a/inc/poche/Database.class.php
+++ b/inc/poche/Database.class.php
@@ -18,7 +18,7 @@ class Database {
18 'default' => 'ORDER BY entries.id' 18 'default' => 'ORDER BY entries.id'
19 ); 19 );
20 20
21 function __construct() 21 function __construct()
22 { 22 {
23 switch (STORAGE) { 23 switch (STORAGE) {
24 case 'sqlite': 24 case 'sqlite':
@@ -27,11 +27,11 @@ class Database {
27 break; 27 break;
28 case 'mysql': 28 case 'mysql':
29 $db_path = 'mysql:host=' . STORAGE_SERVER . ';dbname=' . STORAGE_DB; 29 $db_path = 'mysql:host=' . STORAGE_SERVER . ';dbname=' . STORAGE_DB;
30 $this->handle = new PDO($db_path, STORAGE_USER, STORAGE_PASSWORD); 30 $this->handle = new PDO($db_path, STORAGE_USER, STORAGE_PASSWORD);
31 break; 31 break;
32 case 'postgres': 32 case 'postgres':
33 $db_path = 'pgsql:host=' . STORAGE_SERVER . ';dbname=' . STORAGE_DB; 33 $db_path = 'pgsql:host=' . STORAGE_SERVER . ';dbname=' . STORAGE_DB;
34 $this->handle = new PDO($db_path, STORAGE_USER, STORAGE_PASSWORD); 34 $this->handle = new PDO($db_path, STORAGE_USER, STORAGE_PASSWORD);
35 break; 35 break;
36 } 36 }
37 37
@@ -51,7 +51,7 @@ class Database {
51 } 51 }
52 $hasAdmin = count($query->fetchAll()); 52 $hasAdmin = count($query->fetchAll());
53 53
54 if ($hasAdmin == 0) 54 if ($hasAdmin == 0)
55 return false; 55 return false;
56 56
57 return true; 57 return true;
@@ -140,7 +140,7 @@ class Database {
140 $sql = 'INSERT INTO users_config ( user_id, name, value ) VALUES (?, ?, ?)'; 140 $sql = 'INSERT INTO users_config ( user_id, name, value ) VALUES (?, ?, ?)';
141 $params = array($id_user, 'language', LANG); 141 $params = array($id_user, 'language', LANG);
142 $query = $this->executeQuery($sql, $params); 142 $query = $this->executeQuery($sql, $params);
143 143
144 $sql = 'INSERT INTO users_config ( user_id, name, value ) VALUES (?, ?, ?)'; 144 $sql = 'INSERT INTO users_config ( user_id, name, value ) VALUES (?, ?, ?)';
145 $params = array($id_user, 'theme', DEFAULT_THEME); 145 $params = array($id_user, 'theme', DEFAULT_THEME);
146 $query = $this->executeQuery($sql, $params); 146 $query = $this->executeQuery($sql, $params);
@@ -153,7 +153,7 @@ class Database {
153 $query = $this->executeQuery($sql, array($id)); 153 $query = $this->executeQuery($sql, array($id));
154 $result = $query->fetchAll(); 154 $result = $query->fetchAll();
155 $user_config = array(); 155 $user_config = array();
156 156
157 foreach ($result as $key => $value) { 157 foreach ($result as $key => $value) {
158 $user_config[$value['name']] = $value['value']; 158 $user_config[$value['name']] = $value['value'];
159 } 159 }
@@ -201,10 +201,10 @@ class Database {
201 $params_update = array($password, $userId); 201 $params_update = array($password, $userId);
202 $query = $this->executeQuery($sql_update, $params_update); 202 $query = $this->executeQuery($sql_update, $params_update);
203 } 203 }
204 204
205 public function updateUserConfig($userId, $key, $value) { 205 public function updateUserConfig($userId, $key, $value) {
206 $config = $this->getConfigUser($userId); 206 $config = $this->getConfigUser($userId);
207 207
208 if (! isset($config[$key])) { 208 if (! isset($config[$key])) {
209 $sql = "INSERT INTO users_config (value, user_id, name) VALUES (?, ?, ?)"; 209 $sql = "INSERT INTO users_config (value, user_id, name) VALUES (?, ?, ?)";
210 } 210 }
@@ -230,6 +230,36 @@ class Database {
230 } 230 }
231 } 231 }
232 232
233 public function updateContentAndTitle($id, $title, $body, $user_id) {
234 $sql_action = 'UPDATE entries SET content = ?, title = ? WHERE id=? AND user_id=?';
235 $params_action = array($body, $title, $id, $user_id);
236 $query = $this->executeQuery($sql_action, $params_action);
237
238 return $query;
239 }
240
241 public function retrieveUnfetchedEntries($user_id, $limit) {
242
243 $sql_limit = "LIMIT 0,".$limit;
244 if (STORAGE == 'postgres') {
245 $sql_limit = "LIMIT ".$limit." OFFSET 0";
246 }
247
248 $sql = "SELECT * FROM entries WHERE (content = '' OR content IS NULL) AND user_id=? ORDER BY id " . $sql_limit;
249 $query = $this->executeQuery($sql, array($user_id));
250 $entries = $query->fetchAll();
251
252 return $entries;
253 }
254
255 public function retrieveUnfetchedEntriesCount($user_id) {
256 $sql = "SELECT count(*) FROM entries WHERE (content = '' OR content IS NULL) AND user_id=?";
257 $query = $this->executeQuery($sql, array($user_id));
258 list($count) = $query->fetch();
259
260 return $count;
261 }
262
233 public function retrieveAll($user_id) { 263 public function retrieveAll($user_id) {
234 $sql = "SELECT * FROM entries WHERE user_id=? ORDER BY id"; 264 $sql = "SELECT * FROM entries WHERE user_id=? ORDER BY id";
235 $query = $this->executeQuery($sql, array($user_id)); 265 $query = $this->executeQuery($sql, array($user_id));
@@ -294,24 +324,24 @@ class Database {
294 return $entries; 324 return $entries;
295 } 325 }
296 326
297 public function getEntriesByViewCount($view, $user_id, $tag_id = 0) { 327 public function getEntriesByViewCount($view, $user_id, $tag_id = 0) {
298 switch ($view) { 328 switch ($view) {
299 case 'archive': 329 case 'archive':
300 $sql = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? "; 330 $sql = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? ";
301 $params = array($user_id, 1); 331 $params = array($user_id, 1);
302 break; 332 break;
303 case 'fav' : 333 case 'fav' :
304 $sql = "SELECT count(*) FROM entries WHERE user_id=? AND is_fav=? "; 334 $sql = "SELECT count(*) FROM entries WHERE user_id=? AND is_fav=? ";
305 $params = array($user_id, 1); 335 $params = array($user_id, 1);
306 break; 336 break;
307 case 'tag' : 337 case 'tag' :
308 $sql = "SELECT count(*) FROM entries 338 $sql = "SELECT count(*) FROM entries
309 LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id 339 LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id
310 WHERE entries.user_id=? AND tags_entries.tag_id = ? "; 340 WHERE entries.user_id=? AND tags_entries.tag_id = ? ";
311 $params = array($user_id, $tag_id); 341 $params = array($user_id, $tag_id);
312 break; 342 break;
313 default: 343 default:
314 $sql = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? "; 344 $sql = "SELECT count(*) FROM entries WHERE user_id=? AND is_read=? ";
315 $params = array($user_id, 0); 345 $params = array($user_id, 0);
316 break; 346 break;
317 } 347 }
@@ -319,7 +349,7 @@ class Database {
319 $query = $this->executeQuery($sql, $params); 349 $query = $this->executeQuery($sql, $params);
320 list($count) = $query->fetch(); 350 list($count) = $query->fetch();
321 351
322 return $count; 352 return $count;
323 } 353 }
324 354
325 public function updateContent($id, $content, $user_id) { 355 public function updateContent($id, $content, $user_id) {
@@ -329,11 +359,24 @@ class Database {
329 return $query; 359 return $query;
330 } 360 }
331 361
332 public function add($url, $title, $content, $user_id) { 362 /**
333 $sql_action = 'INSERT INTO entries ( url, title, content, user_id ) VALUES (?, ?, ?, ?)'; 363 *
334 $params_action = array($url, $title, $content, $user_id); 364 * @param string $url
335 $query = $this->executeQuery($sql_action, $params_action); 365 * @param string $title
336 return $query; 366 * @param string $content
367 * @param integer $user_id
368 * @return integer $id of inserted record
369 */
370 public function add($url, $title, $content, $user_id, $isFavorite=0, $isRead=0) {
371 $sql_action = 'INSERT INTO entries ( url, title, content, user_id, is_fav, is_read ) VALUES (?, ?, ?, ?, ?, ?)';
372 $params_action = array($url, $title, $content, $user_id, $isFavorite, $isRead);
373 if ( !$this->executeQuery($sql_action, $params_action) ) {
374 $id = null;
375 }
376 else {
377 $id = intval($this->getLastId( (STORAGE == 'postgres') ? 'users_id_seq' : '' ));
378 }
379 return $id;
337 } 380 }
338 381
339 public function deleteById($id, $user_id) { 382 public function deleteById($id, $user_id) {
@@ -364,13 +407,25 @@ class Database {
364 public function getLastId($column = '') { 407 public function getLastId($column = '') {
365 return $this->getHandle()->lastInsertId($column); 408 return $this->getHandle()->lastInsertId($column);
366 } 409 }
410
411 public function search($term, $user_id, $limit = '') {
412 $search = '%'.$term.'%';
413 $sql_action = "SELECT * FROM entries WHERE user_id=? AND (content LIKE ? OR title LIKE ? OR url LIKE ?) "; //searches in content, title and URL
414 $sql_action .= $this->getEntriesOrder().' ' . $limit;
415 $params_action = array($user_id, $search, $search, $search);
416 $query = $this->executeQuery($sql_action, $params_action);
417 return $query->fetchAll();
418 }
367 419
368 public function retrieveAllTags($user_id) { 420 public function retrieveAllTags($user_id, $term = null) {
369 $sql = "SELECT DISTINCT tags.* FROM tags 421 $sql = "SELECT DISTINCT tags.*, count(entries.id) AS entriescount FROM tags
370 LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id 422 LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id
371 LEFT JOIN entries ON tags_entries.entry_id=entries.id 423 LEFT JOIN entries ON tags_entries.entry_id=entries.id
372 WHERE entries.user_id=?"; 424 WHERE entries.user_id=?
373 $query = $this->executeQuery($sql, array($user_id)); 425 ". (($term) ? "AND lower(tags.value) LIKE ?" : '') ."
426 GROUP BY tags.id, tags.value
427 ORDER BY tags.value";
428 $query = $this->executeQuery($sql, (($term)? array($user_id, strtolower('%'.$term.'%')) : array($user_id) ));
374 $tags = $query->fetchAll(); 429 $tags = $query->fetchAll();
375 430
376 return $tags; 431 return $tags;
@@ -390,7 +445,7 @@ class Database {
390 } 445 }
391 446
392 public function retrieveEntriesByTag($tag_id, $user_id) { 447 public function retrieveEntriesByTag($tag_id, $user_id) {
393 $sql = 448 $sql =
394 "SELECT entries.* FROM entries 449 "SELECT entries.* FROM entries
395 LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id 450 LEFT JOIN tags_entries ON tags_entries.entry_id=entries.id
396 WHERE tags_entries.tag_id = ? AND entries.user_id=?"; 451 WHERE tags_entries.tag_id = ? AND entries.user_id=?";
@@ -401,7 +456,7 @@ class Database {
401 } 456 }
402 457
403 public function retrieveTagsByEntry($entry_id) { 458 public function retrieveTagsByEntry($entry_id) {
404 $sql = 459 $sql =
405 "SELECT tags.* FROM tags 460 "SELECT tags.* FROM tags
406 LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id 461 LEFT JOIN tags_entries ON tags_entries.tag_id=tags.id
407 WHERE tags_entries.entry_id = ?"; 462 WHERE tags_entries.entry_id = ?";
diff --git a/inc/poche/Poche.class.php b/inc/poche/Poche.class.php
index 34f2ff5a..a662f695 100755
--- a/inc/poche/Poche.class.php
+++ b/inc/poche/Poche.class.php
@@ -18,7 +18,7 @@ class Poche
18 public $tpl; 18 public $tpl;
19 public $messages; 19 public $messages;
20 public $pagination; 20 public $pagination;
21 21
22 private $currentTheme = ''; 22 private $currentTheme = '';
23 private $currentLanguage = ''; 23 private $currentLanguage = '';
24 private $notInstalledMessage = array(); 24 private $notInstalledMessage = array();
@@ -32,20 +32,21 @@ class Poche
32 'fr_FR.utf8' => 'Français', 32 'fr_FR.utf8' => 'Français',
33 'it_IT.utf8' => 'Italiano', 33 'it_IT.utf8' => 'Italiano',
34 'pl_PL.utf8' => 'Polski', 34 'pl_PL.utf8' => 'Polski',
35 'pt_BR.utf8' => 'Português (Brasil)',
35 'ru_RU.utf8' => 'Pусский', 36 'ru_RU.utf8' => 'Pусский',
36 'sl_SI.utf8' => 'Slovenščina', 37 'sl_SI.utf8' => 'Slovenščina',
37 'uk_UA.utf8' => 'Українськй', 38 'uk_UA.utf8' => 'Українськ',
38 ); 39 );
39 public function __construct() 40 public function __construct()
40 { 41 {
41 if ($this->configFileIsAvailable()) { 42 if ($this->configFileIsAvailable()) {
42 $this->init(); 43 $this->init();
43 } 44 }
44 45
45 if ($this->themeIsInstalled()) { 46 if ($this->themeIsInstalled()) {
46 $this->initTpl(); 47 $this->initTpl();
47 } 48 }
48 49
49 if ($this->systemIsInstalled()) { 50 if ($this->systemIsInstalled()) {
50 $this->store = new Database(); 51 $this->store = new Database();
51 $this->messages = new Messages(); 52 $this->messages = new Messages();
@@ -56,12 +57,10 @@ class Poche
56 $this->store->checkTags(); 57 $this->store->checkTags();
57 } 58 }
58 } 59 }
59 60
60 private function init() 61 private function init()
61 { 62 {
62 Tools::initPhp(); 63 Tools::initPhp();
63 Session::$sessionName = 'poche';
64 Session::init();
65 64
66 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) { 65 if (isset($_SESSION['poche_user']) && $_SESSION['poche_user'] != array()) {
67 $this->user = $_SESSION['poche_user']; 66 $this->user = $_SESSION['poche_user'];
@@ -75,28 +74,28 @@ class Poche
75 $language = $this->user->getConfigValue('language'); 74 $language = $this->user->getConfigValue('language');
76 putenv('LC_ALL=' . $language); 75 putenv('LC_ALL=' . $language);
77 setlocale(LC_ALL, $language); 76 setlocale(LC_ALL, $language);
78 bindtextdomain($language, LOCALE); 77 bindtextdomain($language, LOCALE);
79 textdomain($language); 78 textdomain($language);
80 79
81 # Pagination 80 # Pagination
82 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p'); 81 $this->pagination = new Paginator($this->user->getConfigValue('pager'), 'p');
83 82
84 # Set up theme 83 # Set up theme
85 $themeDirectory = $this->user->getConfigValue('theme'); 84 $themeDirectory = $this->user->getConfigValue('theme');
86 85
87 if ($themeDirectory === false) { 86 if ($themeDirectory === false) {
88 $themeDirectory = DEFAULT_THEME; 87 $themeDirectory = DEFAULT_THEME;
89 } 88 }
90 89
91 $this->currentTheme = $themeDirectory; 90 $this->currentTheme = $themeDirectory;
92 91
93 # Set up language 92 # Set up language
94 $languageDirectory = $this->user->getConfigValue('language'); 93 $languageDirectory = $this->user->getConfigValue('language');
95 94
96 if ($languageDirectory === false) { 95 if ($languageDirectory === false) {
97 $languageDirectory = DEFAULT_THEME; 96 $languageDirectory = DEFAULT_THEME;
98 } 97 }
99 98
100 $this->currentLanguage = $languageDirectory; 99 $this->currentLanguage = $languageDirectory;
101 } 100 }
102 101
@@ -109,7 +108,7 @@ class Poche
109 108
110 return true; 109 return true;
111 } 110 }
112 111
113 public function themeIsInstalled() { 112 public function themeIsInstalled() {
114 $passTheme = TRUE; 113 $passTheme = TRUE;
115 # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet 114 # Twig is an absolute requirement for Poche to function. Abort immediately if the Composer installer hasn't been run yet
@@ -124,27 +123,27 @@ class Poche
124 self::$canRenderTemplates = false; 123 self::$canRenderTemplates = false;
125 124
126 $passTheme = FALSE; 125 $passTheme = FALSE;
127 } 126 }
128 127
129 # Check if the selected theme and its requirements are present 128 # Check if the selected theme and its requirements are present
130 $theme = $this->getTheme(); 129 $theme = $this->getTheme();
131 130
132 if ($theme != '' && ! is_dir(THEME . '/' . $theme)) { 131 if ($theme != '' && ! is_dir(THEME . '/' . $theme)) {
133 $this->notInstalledMessage[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME . '/' . $theme . ')'; 132 $this->notInstalledMessage[] = 'The currently selected theme (' . $theme . ') does not seem to be properly installed (Missing directory: ' . THEME . '/' . $theme . ')';
134 133
135 self::$canRenderTemplates = false; 134 self::$canRenderTemplates = false;
136 135
137 $passTheme = FALSE; 136 $passTheme = FALSE;
138 } 137 }
139 138
140 $themeInfo = $this->getThemeInfo($theme); 139 $themeInfo = $this->getThemeInfo($theme);
141 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) { 140 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
142 foreach ($themeInfo['requirements'] as $requiredTheme) { 141 foreach ($themeInfo['requirements'] as $requiredTheme) {
143 if (! is_dir(THEME . '/' . $requiredTheme)) { 142 if (! is_dir(THEME . '/' . $requiredTheme)) {
144 $this->notInstalledMessage[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')'; 143 $this->notInstalledMessage[] = 'The required "' . $requiredTheme . '" theme is missing for the current theme (' . $theme . ')';
145 144
146 self::$canRenderTemplates = false; 145 self::$canRenderTemplates = false;
147 146
148 $passTheme = FALSE; 147 $passTheme = FALSE;
149 } 148 }
150 } 149 }
@@ -154,21 +153,21 @@ class Poche
154 return FALSE; 153 return FALSE;
155 } 154 }
156 155
157 156
158 return true; 157 return true;
159 } 158 }
160 159
161 /** 160 /**
162 * all checks before installation. 161 * all checks before installation.
163 * @todo move HTML to template 162 * @todo move HTML to template
164 * @return boolean 163 * @return boolean
165 */ 164 */
166 public function systemIsInstalled() 165 public function systemIsInstalled()
167 { 166 {
168 $msg = TRUE; 167 $msg = TRUE;
169 168
170 $configSalt = defined('SALT') ? constant('SALT') : ''; 169 $configSalt = defined('SALT') ? constant('SALT') : '';
171 170
172 if (empty($configSalt)) { 171 if (empty($configSalt)) {
173 $this->notInstalledMessage[] = 'You have not yet filled in the SALT value in the config.inc.php file.'; 172 $this->notInstalledMessage[] = 'You have not yet filled in the SALT value in the config.inc.php file.';
174 $msg = FALSE; 173 $msg = FALSE;
@@ -194,7 +193,7 @@ class Poche
194 193
195 return true; 194 return true;
196 } 195 }
197 196
198 public function getNotInstalledMessage() { 197 public function getNotInstalledMessage() {
199 return $this->notInstalledMessage; 198 return $this->notInstalledMessage;
200 } 199 }
@@ -203,7 +202,7 @@ class Poche
203 { 202 {
204 $loaderChain = new Twig_Loader_Chain(); 203 $loaderChain = new Twig_Loader_Chain();
205 $theme = $this->getTheme(); 204 $theme = $this->getTheme();
206 205
207 # add the current theme as first to the loader chain so Twig will look there first for overridden template files 206 # add the current theme as first to the loader chain so Twig will look there first for overridden template files
208 try { 207 try {
209 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $theme)); 208 $loaderChain->addLoader(new Twig_Loader_Filesystem(THEME . '/' . $theme));
@@ -211,7 +210,7 @@ class Poche
211 # @todo isInstalled() should catch this, inject Twig later 210 # @todo isInstalled() should catch this, inject Twig later
212 die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME . '/' . $theme .' is missing)'); 211 die('The currently selected theme (' . $theme . ') does not seem to be properly installed (' . THEME . '/' . $theme .' is missing)');
213 } 212 }
214 213
215 # add all required themes to the loader chain 214 # add all required themes to the loader chain
216 $themeInfo = $this->getThemeInfo($theme); 215 $themeInfo = $this->getThemeInfo($theme);
217 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) { 216 if (isset($themeInfo['requirements']) && is_array($themeInfo['requirements'])) {
@@ -224,16 +223,16 @@ class Poche
224 } 223 }
225 } 224 }
226 } 225 }
227 226
228 if (DEBUG_POCHE) { 227 if (DEBUG_POCHE) {
229 $twigParams = array(); 228 $twigParams = array();
230 } else { 229 } else {
231 $twigParams = array('cache' => CACHE); 230 $twigParams = array('cache' => CACHE);
232 } 231 }
233 232
234 $this->tpl = new Twig_Environment($loaderChain, $twigParams); 233 $this->tpl = new Twig_Environment($loaderChain, $twigParams);
235 $this->tpl->addExtension(new Twig_Extensions_Extension_I18n()); 234 $this->tpl->addExtension(new Twig_Extensions_Extension_I18n());
236 235
237 # filter to display domain name of an url 236 # filter to display domain name of an url
238 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain'); 237 $filter = new Twig_SimpleFilter('getDomain', 'Tools::getDomain');
239 $this->tpl->addFilter($filter); 238 $this->tpl->addFilter($filter);
@@ -252,7 +251,7 @@ class Poche
252 'poche_url' => Tools::getPocheUrl() 251 'poche_url' => Tools::getPocheUrl()
253 )); 252 ));
254 if (isset($_GET['install'])) { 253 if (isset($_GET['install'])) {
255 if (($_POST['password'] == $_POST['password_repeat']) 254 if (($_POST['password'] == $_POST['password_repeat'])
256 && $_POST['password'] != "" && $_POST['login'] != "") { 255 && $_POST['password'] != "" && $_POST['login'] != "") {
257 # let's rock, install poche baby ! 256 # let's rock, install poche baby !
258 if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login']))) 257 if ($this->store->install($_POST['login'], Tools::encodeString($_POST['password'] . $_POST['login'])))
@@ -269,7 +268,7 @@ class Poche
269 } 268 }
270 exit(); 269 exit();
271 } 270 }
272 271
273 public function getTheme() { 272 public function getTheme() {
274 return $this->currentTheme; 273 return $this->currentTheme;
275 } 274 }
@@ -294,7 +293,7 @@ class Poche
294 if (is_file($themeIniFile) && is_readable($themeIniFile)) { 293 if (is_file($themeIniFile) && is_readable($themeIniFile)) {
295 $themeInfo = parse_ini_file($themeIniFile); 294 $themeInfo = parse_ini_file($themeIniFile);
296 } 295 }
297 296
298 if ($themeInfo === false) { 297 if ($themeInfo === false) {
299 $themeInfo = array(); 298 $themeInfo = array();
300 } 299 }
@@ -305,7 +304,7 @@ class Poche
305 304
306 return $themeInfo; 305 return $themeInfo;
307 } 306 }
308 307
309 public function getInstalledThemes() { 308 public function getInstalledThemes() {
310 $handle = opendir(THEME); 309 $handle = opendir(THEME);
311 $themes = array(); 310 $themes = array();
@@ -332,28 +331,28 @@ class Poche
332 public function getInstalledLanguages() { 331 public function getInstalledLanguages() {
333 $handle = opendir(LOCALE); 332 $handle = opendir(LOCALE);
334 $languages = array(); 333 $languages = array();
335 334
336 while (($language = readdir($handle)) !== false) { 335 while (($language = readdir($handle)) !== false) {
337 # Languages are stored in a directory, so all directory names are languages 336 # Languages are stored in a directory, so all directory names are languages
338 # @todo move language installation data to database 337 # @todo move language installation data to database
339 if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.'))) { 338 if (! is_dir(LOCALE . '/' . $language) || in_array($language, array('..', '.', 'tools'))) {
340 continue; 339 continue;
341 } 340 }
342 341
343 $current = false; 342 $current = false;
344 343
345 if ($language === $this->getLanguage()) { 344 if ($language === $this->getLanguage()) {
346 $current = true; 345 $current = true;
347 } 346 }
348 347
349 $languages[] = array('name' => $this->language_names[$language], 'value' => $language, 'current' => $current); 348 $languages[] = array('name' => (isset($this->language_names[$language]) ? $this->language_names[$language] : $language), 'value' => $language, 'current' => $current);
350 } 349 }
351 350
352 return $languages; 351 return $languages;
353 } 352 }
354 353
355 public function getDefaultConfig() 354 public function getDefaultConfig()
356 { 355 {
357 return array( 356 return array(
358 'pager' => PAGINATION, 357 'pager' => PAGINATION,
359 'language' => LANG, 358 'language' => LANG,
@@ -361,60 +360,6 @@ class Poche
361 ); 360 );
362 } 361 }
363 362
364 protected function getPageContent(Url $url)
365 {
366 // Saving and clearing context
367 $REAL = array();
368 foreach( $GLOBALS as $key => $value ) {
369 if( $key != "GLOBALS" && $key != "_SESSION" ) {
370 $GLOBALS[$key] = array();
371 $REAL[$key] = $value;
372 }
373 }
374 // Saving and clearing session
375 $REAL_SESSION = array();
376 foreach( $_SESSION as $key => $value ) {
377 $REAL_SESSION[$key] = $value;
378 unset($_SESSION[$key]);
379 }
380
381 // Running code in different context
382 $scope = function() {
383 extract( func_get_arg(1) );
384 $_GET = $_REQUEST = array(
385 "url" => $url->getUrl(),
386 "max" => 5,
387 "links" => "preserve",
388 "exc" => "",
389 "format" => "json",
390 "submit" => "Create Feed"
391 );
392 ob_start();
393 require func_get_arg(0);
394 $json = ob_get_flush();
395 return $json;
396 };
397 $json = $scope( "inc/3rdparty/makefulltextfeed.php", array("url" => $url) );
398
399 // Clearing and restoring context
400 foreach( $GLOBALS as $key => $value ) {
401 if( $key != "GLOBALS" && $key != "_SESSION" ) {
402 unset($GLOBALS[$key]);
403 }
404 }
405 foreach( $REAL as $key => $value ) {
406 $GLOBALS[$key] = $value;
407 }
408 // Clearing and restoring session
409 foreach( $_SESSION as $key => $value ) {
410 unset($_SESSION[$key]);
411 }
412 foreach( $REAL_SESSION as $key => $value ) {
413 $_SESSION[$key] = $value;
414 }
415 return json_decode($json, true);
416 }
417
418 /** 363 /**
419 * Call action (mark as fav, archive, delete, etc.) 364 * Call action (mark as fav, archive, delete, etc.)
420 */ 365 */
@@ -423,28 +368,24 @@ class Poche
423 switch ($action) 368 switch ($action)
424 { 369 {
425 case 'add': 370 case 'add':
426 $content = $this->getPageContent($url); 371 $content = Tools::getPageContent($url);
427 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'); 372 $title = ($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled');
428 $body = $content['rss']['channel']['item']['description']; 373 $body = $content['rss']['channel']['item']['description'];
429 374
430 // clean content from prevent xss attack 375 // clean content from prevent xss attack
431 $config = HTMLPurifier_Config::createDefault(); 376 $config = HTMLPurifier_Config::createDefault();
377 $config->set('Cache.SerializerPath', CACHE);
432 $purifier = new HTMLPurifier($config); 378 $purifier = new HTMLPurifier($config);
433 $title = $purifier->purify($title); 379 $title = $purifier->purify($title);
434 $body = $purifier->purify($body); 380 $body = $purifier->purify($body);
435 381
436 //search for possible duplicate if not in import mode 382 //search for possible duplicate
437 if (!$import) { 383 $duplicate = NULL;
438 $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId()); 384 $duplicate = $this->store->retrieveOneByURL($url->getUrl(), $this->user->getId());
439 }
440 385
441 if ($this->store->add($url->getUrl(), $title, $body, $this->user->getId())) { 386 $last_id = $this->store->add($url->getUrl(), $title, $body, $this->user->getId());
387 if ( $last_id ) {
442 Tools::logm('add link ' . $url->getUrl()); 388 Tools::logm('add link ' . $url->getUrl());
443 $sequence = '';
444 if (STORAGE == 'postgres') {
445 $sequence = 'entries_id_seq';
446 }
447 $last_id = $this->store->getLastId($sequence);
448 if (DOWNLOAD_PICTURES) { 389 if (DOWNLOAD_PICTURES) {
449 $content = filtre_picture($body, $url->getUrl(), $last_id); 390 $content = filtre_picture($body, $url->getUrl(), $last_id);
450 Tools::logm('updating content article'); 391 Tools::logm('updating content article');
@@ -464,23 +405,17 @@ class Poche
464 } 405 }
465 } 406 }
466 407
467 if (!$import) { 408 $this->messages->add('s', _('the link has been added successfully'));
468 $this->messages->add('s', _('the link has been added successfully'));
469 }
470 } 409 }
471 else { 410 else {
472 if (!$import) { 411 $this->messages->add('e', _('error during insertion : the link wasn\'t added'));
473 $this->messages->add('e', _('error during insertion : the link wasn\'t added')); 412 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
474 Tools::logm('error during insertion : the link wasn\'t added ' . $url->getUrl());
475 }
476 } 413 }
477 414
478 if (!$import) { 415 if ($autoclose == TRUE) {
479 if ($autoclose == TRUE) { 416 Tools::redirect('?view=home');
480 Tools::redirect('?view=home'); 417 } else {
481 } else { 418 Tools::redirect('?view=home&closewin=true');
482 Tools::redirect('?view=home&closewin=true');
483 }
484 } 419 }
485 break; 420 break;
486 case 'delete': 421 case 'delete':
@@ -501,62 +436,56 @@ class Poche
501 case 'toggle_fav' : 436 case 'toggle_fav' :
502 $this->store->favoriteById($id, $this->user->getId()); 437 $this->store->favoriteById($id, $this->user->getId());
503 Tools::logm('mark as favorite link #' . $id); 438 Tools::logm('mark as favorite link #' . $id);
504 if (!$import) { 439 Tools::redirect();
505 Tools::redirect();
506 }
507 break; 440 break;
508 case 'toggle_archive' : 441 case 'toggle_archive' :
509 $this->store->archiveById($id, $this->user->getId()); 442 $this->store->archiveById($id, $this->user->getId());
510 Tools::logm('archive link #' . $id); 443 Tools::logm('archive link #' . $id);
511 if (!$import) { 444 Tools::redirect();
512 Tools::redirect();
513 }
514 break; 445 break;
515 case 'archive_all' : 446 case 'archive_all' :
516 $this->store->archiveAll($this->user->getId()); 447 $this->store->archiveAll($this->user->getId());
517 Tools::logm('archive all links'); 448 Tools::logm('archive all links');
518 if (!$import) { 449 Tools::redirect();
519 Tools::redirect();
520 }
521 break; 450 break;
522 case 'add_tag' : 451 case 'add_tag' :
523 if($import){ 452 $tags = explode(',', $_POST['value']);
524 $entry_id = $id; 453 $entry_id = $_POST['entry_id'];
525 $tags = explode(',', $tags);
526 }
527 else{
528 $tags = explode(',', $_POST['value']);
529 $entry_id = $_POST['entry_id'];
530 }
531 $entry = $this->store->retrieveOneById($entry_id, $this->user->getId()); 454 $entry = $this->store->retrieveOneById($entry_id, $this->user->getId());
532 if (!$entry) { 455 if (!$entry) {
533 $this->messages->add('e', _('Article not found!')); 456 $this->messages->add('e', _('Article not found!'));
534 Tools::logm('error : article not found'); 457 Tools::logm('error : article not found');
535 Tools::redirect(); 458 Tools::redirect();
536 } 459 }
460 //get all already set tags to preven duplicates
461 $already_set_tags = array();
462 $entry_tags = $this->store->retrieveTagsByEntry($entry_id);
463 foreach ($entry_tags as $tag) {
464 $already_set_tags[] = $tag['value'];
465 }
537 foreach($tags as $key => $tag_value) { 466 foreach($tags as $key => $tag_value) {
538 $value = trim($tag_value); 467 $value = trim($tag_value);
539 $tag = $this->store->retrieveTagByValue($value); 468 if ($value && !in_array($value, $already_set_tags)) {
540 469 $tag = $this->store->retrieveTagByValue($value);
541 if (is_null($tag)) { 470
542 # we create the tag 471 if (is_null($tag)) {
543 $tag = $this->store->createTag($value); 472 # we create the tag
544 $sequence = ''; 473 $tag = $this->store->createTag($value);
545 if (STORAGE == 'postgres') { 474 $sequence = '';
546 $sequence = 'tags_id_seq'; 475 if (STORAGE == 'postgres') {
547 } 476 $sequence = 'tags_id_seq';
548 $tag_id = $this->store->getLastId($sequence); 477 }
549 } 478 $tag_id = $this->store->getLastId($sequence);
550 else { 479 }
551 $tag_id = $tag['id']; 480 else {
481 $tag_id = $tag['id'];
482 }
483
484 # we assign the tag to the article
485 $this->store->setTagToEntry($tag_id, $entry_id);
552 } 486 }
553
554 # we assign the tag to the article
555 $this->store->setTagToEntry($tag_id, $entry_id);
556 }
557 if(!$import) {
558 Tools::redirect();
559 } 487 }
488 Tools::redirect();
560 break; 489 break;
561 case 'remove_tag' : 490 case 'remove_tag' :
562 $tag_id = $_GET['tag_id']; 491 $tag_id = $_GET['tag_id'];
@@ -581,8 +510,12 @@ class Poche
581 switch ($view) 510 switch ($view)
582 { 511 {
583 case 'config': 512 case 'config':
584 $dev = trim($this->getPocheVersion('dev')); 513 $dev_infos = $this->getPocheVersion('dev');
585 $prod = trim($this->getPocheVersion('prod')); 514 $dev = trim($dev_infos[0]);
515 $check_time_dev = date('d-M-Y H:i', $dev_infos[1]);
516 $prod_infos = $this->getPocheVersion('prod');
517 $prod = trim($prod_infos[0]);
518 $check_time_prod = date('d-M-Y H:i', $prod_infos[1]);
586 $compare_dev = version_compare(POCHE, $dev); 519 $compare_dev = version_compare(POCHE, $dev);
587 $compare_prod = version_compare(POCHE, $prod); 520 $compare_prod = version_compare(POCHE, $prod);
588 $themes = $this->getInstalledThemes(); 521 $themes = $this->getInstalledThemes();
@@ -594,6 +527,8 @@ class Poche
594 'languages' => $languages, 527 'languages' => $languages,
595 'dev' => $dev, 528 'dev' => $dev,
596 'prod' => $prod, 529 'prod' => $prod,
530 'check_time_dev' => $check_time_dev,
531 'check_time_prod' => $check_time_prod,
597 'compare_dev' => $compare_dev, 532 'compare_dev' => $compare_dev,
598 'compare_prod' => $compare_prod, 533 'compare_prod' => $compare_prod,
599 'token' => $token, 534 'token' => $token,
@@ -619,13 +554,36 @@ class Poche
619 break; 554 break;
620 case 'tags': 555 case 'tags':
621 $token = $this->user->getConfigValue('token'); 556 $token = $this->user->getConfigValue('token');
622 $tags = $this->store->retrieveAllTags($this->user->getId()); 557 //if term is set - search tags for this term
558 $term = Tools::checkVar('term');
559 $tags = $this->store->retrieveAllTags($this->user->getId(), $term);
560 if (Tools::isAjaxRequest()) {
561 $result = array();
562 foreach ($tags as $tag) {
563 $result[] = $tag['value'];
564 }
565 echo json_encode($result);
566 exit;
567 }
623 $tpl_vars = array( 568 $tpl_vars = array(
624 'token' => $token, 569 'token' => $token,
625 'user_id' => $this->user->getId(), 570 'user_id' => $this->user->getId(),
626 'tags' => $tags, 571 'tags' => $tags,
627 ); 572 );
628 break; 573 break;
574 case 'search':
575 if (isset($_GET['search'])) {
576 $search = filter_var($_GET['search'], FILTER_SANITIZE_STRING);
577 $tpl_vars['entries'] = $this->store->search($search, $this->user->getId());
578 $count = count($tpl_vars['entries']);
579 $this->pagination->set_total($count);
580 $page_links = str_replace(array('previous', 'next'), array(_('previous'), _('next')),
581 $this->pagination->page_links('?view=' . $view . '?search=' . $search . '&sort=' . $_SESSION['sort'] . '&' ));
582 $tpl_vars['page_links'] = $page_links;
583 $tpl_vars['nb_results'] = $count;
584 $tpl_vars['search_term'] = $search;
585 }
586 break;
629 case 'view': 587 case 'view':
630 $entry = $this->store->retrieveOneById($id, $this->user->getId()); 588 $entry = $this->store->retrieveOneById($id, $this->user->getId());
631 if ($entry != NULL) { 589 if ($entry != NULL) {
@@ -660,8 +618,9 @@ class Poche
660 'entries' => '', 618 'entries' => '',
661 'page_links' => '', 619 'page_links' => '',
662 'nb_results' => '', 620 'nb_results' => '',
621 'listmode' => (isset($_COOKIE['listmode']) ? true : false),
663 ); 622 );
664 623
665 //if id is given - we retrive entries by tag: id is tag id 624 //if id is given - we retrive entries by tag: id is tag id
666 if ($id) { 625 if ($id) {
667 $tpl_vars['tag'] = $this->store->retrieveTag($id, $this->user->getId()); 626 $tpl_vars['tag'] = $this->store->retrieveTag($id, $this->user->getId());
@@ -686,8 +645,8 @@ class Poche
686 } 645 }
687 646
688 /** 647 /**
689 * update the password of the current user. 648 * update the password of the current user.
690 * if MODE_DEMO is TRUE, the password can't be updated. 649 * if MODE_DEMO is TRUE, the password can't be updated.
691 * @todo add the return value 650 * @todo add the return value
692 * @todo set the new password in function header like this updatePassword($newPassword) 651 * @todo set the new password in function header like this updatePassword($newPassword)
693 * @return boolean 652 * @return boolean
@@ -715,42 +674,44 @@ class Poche
715 } 674 }
716 } 675 }
717 } 676 }
718 677
719 public function updateTheme() 678 public function updateTheme()
720 { 679 {
721 # no data 680 # no data
722 if (empty($_POST['theme'])) { 681 if (empty($_POST['theme'])) {
723 } 682 }
724 683
725 # we are not going to change it to the current theme... 684 # we are not going to change it to the current theme...
726 if ($_POST['theme'] == $this->getTheme()) { 685 if ($_POST['theme'] == $this->getTheme()) {
727 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!')); 686 $this->messages->add('w', _('still using the "' . $this->getTheme() . '" theme!'));
728 Tools::redirect('?view=config'); 687 Tools::redirect('?view=config');
729 } 688 }
730 689
731 $themes = $this->getInstalledThemes(); 690 $themes = $this->getInstalledThemes();
732 $actualTheme = false; 691 $actualTheme = false;
733 692
734 foreach (array_keys($themes) as $theme) { 693 foreach (array_keys($themes) as $theme) {
735 if ($theme == $_POST['theme']) { 694 if ($theme == $_POST['theme']) {
736 $actualTheme = true; 695 $actualTheme = true;
737 break; 696 break;
738 } 697 }
739 } 698 }
740 699
741 if (! $actualTheme) { 700 if (! $actualTheme) {
742 $this->messages->add('e', _('that theme does not seem to be installed')); 701 $this->messages->add('e', _('that theme does not seem to be installed'));
743 Tools::redirect('?view=config'); 702 Tools::redirect('?view=config');
744 } 703 }
745 704
746 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']); 705 $this->store->updateUserConfig($this->user->getId(), 'theme', $_POST['theme']);
747 $this->messages->add('s', _('you have changed your theme preferences')); 706 $this->messages->add('s', _('you have changed your theme preferences'));
748 707
749 $currentConfig = $_SESSION['poche_user']->config; 708 $currentConfig = $_SESSION['poche_user']->config;
750 $currentConfig['theme'] = $_POST['theme']; 709 $currentConfig['theme'] = $_POST['theme'];
751 710
752 $_SESSION['poche_user']->setConfig($currentConfig); 711 $_SESSION['poche_user']->setConfig($currentConfig);
753 712
713 $this->emptyCache();
714
754 Tools::redirect('?view=config'); 715 Tools::redirect('?view=config');
755 } 716 }
756 717
@@ -759,39 +720,40 @@ class Poche
759 # no data 720 # no data
760 if (empty($_POST['language'])) { 721 if (empty($_POST['language'])) {
761 } 722 }
762 723
763 # we are not going to change it to the current language... 724 # we are not going to change it to the current language...
764 if ($_POST['language'] == $this->getLanguage()) { 725 if ($_POST['language'] == $this->getLanguage()) {
765 $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!')); 726 $this->messages->add('w', _('still using the "' . $this->getLanguage() . '" language!'));
766 Tools::redirect('?view=config'); 727 Tools::redirect('?view=config');
767 } 728 }
768 729
769 $languages = $this->getInstalledLanguages(); 730 $languages = $this->getInstalledLanguages();
770 $actualLanguage = false; 731 $actualLanguage = false;
771 732
772 foreach ($languages as $language) { 733 foreach ($languages as $language) {
773 if ($language['value'] == $_POST['language']) { 734 if ($language['value'] == $_POST['language']) {
774 $actualLanguage = true; 735 $actualLanguage = true;
775 break; 736 break;
776 } 737 }
777 } 738 }
778 739
779 if (! $actualLanguage) { 740 if (! $actualLanguage) {
780 $this->messages->add('e', _('that language does not seem to be installed')); 741 $this->messages->add('e', _('that language does not seem to be installed'));
781 Tools::redirect('?view=config'); 742 Tools::redirect('?view=config');
782 } 743 }
783 744
784 $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']); 745 $this->store->updateUserConfig($this->user->getId(), 'language', $_POST['language']);
785 $this->messages->add('s', _('you have changed your language preferences')); 746 $this->messages->add('s', _('you have changed your language preferences'));
786 747
787 $currentConfig = $_SESSION['poche_user']->config; 748 $currentConfig = $_SESSION['poche_user']->config;
788 $currentConfig['language'] = $_POST['language']; 749 $currentConfig['language'] = $_POST['language'];
789 750
790 $_SESSION['poche_user']->setConfig($currentConfig); 751 $_SESSION['poche_user']->setConfig($currentConfig);
791 752
753 $this->emptyCache();
754
792 Tools::redirect('?view=config'); 755 Tools::redirect('?view=config');
793 } 756 }
794
795 /** 757 /**
796 * get credentials from differents sources 758 * get credentials from differents sources
797 * it redirects the user to the $referer link 759 * it redirects the user to the $referer link
@@ -846,7 +808,7 @@ class Poche
846 /** 808 /**
847 * log out the poche user. It cleans the session. 809 * log out the poche user. It cleans the session.
848 * @todo add the return value 810 * @todo add the return value
849 * @return boolean 811 * @return boolean
850 */ 812 */
851 public function logout() 813 public function logout()
852 { 814 {
@@ -857,225 +819,123 @@ class Poche
857 } 819 }
858 820
859 /** 821 /**
860 * import from Instapaper. poche needs a ./instapaper-export.html file 822 * import datas into your poche
861 * @todo add the return value
862 * @param string $targetFile the file used for importing
863 * @return boolean 823 * @return boolean
864 */ 824 */
865 private function importFromInstapaper($targetFile) 825 public function import() {
866 { 826
867 # TODO gestion des articles favs 827 if (!defined('IMPORT_LIMIT')) {
868 $html = new simple_html_dom(); 828 define('IMPORT_LIMIT', 5);
869 $html->load_file($targetFile); 829 }
870 Tools::logm('starting import from instapaper'); 830 if (!defined('IMPORT_DELAY')) {
871 831 define('IMPORT_DELAY', 5);
872 $read = 0; 832 }
873 $errors = array(); 833
874 foreach($html->find('ol') as $ul) 834 if ( isset($_FILES['file']) ) {
875 { 835 // assume, that file is in json format
876 foreach($ul->find('li') as $li) 836 $str_data = file_get_contents($_FILES['file']['tmp_name']);
877 { 837 $data = json_decode($str_data, true);
878 $a = $li->find('a'); 838
879 $url = new Url(base64_encode($a[0]->href)); 839 if ( $data === null ) {
880 $this->action('add', $url, 0, TRUE); 840 //not json - assume html
881 if ($read == '1') { 841 $html = new simple_html_dom();
882 $sequence = ''; 842 $html->load_file($_FILES['file']['tmp_name']);
883 if (STORAGE == 'postgres') { 843 $data = array();
884 $sequence = 'entries_id_seq'; 844 $read = 0;
885 } 845 foreach (array('ol','ul') as $list) {
886 $last_id = $this->store->getLastId($sequence); 846 foreach ($html->find($list) as $ul) {
887 $this->action('toggle_archive', $url, $last_id, TRUE); 847 foreach ($ul->find('li') as $li) {
888 } 848 $tmpEntry = array();
849 $a = $li->find('a');
850 $tmpEntry['url'] = $a[0]->href;
851 $tmpEntry['tags'] = $a[0]->tags;
852 $tmpEntry['is_read'] = $read;
853 if ($tmpEntry['url']) {
854 $data[] = $tmpEntry;
855 }
856 }
857 # the second <ol/ul> is for read links
858 $read = ((sizeof($data) && $read)?0:1);
889 } 859 }
890 860 }
891 # the second <ol> is for read links
892 $read = 1;
893 } 861 }
894 $this->messages->add('s', _('import from instapaper completed'));
895 Tools::logm('import from instapaper completed');
896 Tools::redirect();
897 }
898 862
899 /** 863 //for readability structure
900 * import from Pocket. poche needs a ./ril_export.html file 864 foreach ($data as $record) {
901 * @todo add the return value 865 if (is_array($record)) {
902 * @param string $targetFile the file used for importing 866 $data[] = $record;
903 * @return boolean 867 foreach ($record as $record2) {
904 */ 868 if (is_array($record2)) {
905 private function importFromPocket($targetFile) 869 $data[] = $record2;
906 { 870 }
907 # TODO gestion des articles favs 871 }
908 $html = new simple_html_dom(); 872 }
909 $html->load_file($targetFile); 873 }
910 Tools::logm('starting import from pocket'); 874
911 875 $i = 0; //counter for articles inserted
912 $read = 0; 876 foreach ($data as $record) {
913 $errors = array(); 877 $url = trim( isset($record['article__url']) ? $record['article__url'] : (isset($record['url']) ? $record['url'] : '') );
914 foreach($html->find('ul') as $ul) 878 if ( $url ) {
915 { 879 $title = (isset($record['title']) ? $record['title'] : _('Untitled - Import - ').'</a> <a href="./?import">'._('click to finish import').'</a><a>');
916 foreach($ul->find('li') as $li) 880 $body = (isset($record['content']) ? $record['content'] : '');
917 { 881 $isRead = (isset($record['is_read']) ? intval($record['is_read']) : (isset($record['archive'])?intval($record['archive']):0));
918 $a = $li->find('a'); 882 $isFavorite = (isset($record['is_fav']) ? intval($record['is_fav']) : (isset($record['favorite'])?intval($record['favorite']):0) );
919 $url = new Url(base64_encode($a[0]->href)); 883 //insert new record
920 $this->action('add', $url, 0, TRUE); 884 $id = $this->store->add($url, $title, $body, $this->user->getId(), $isFavorite, $isRead);
921 $sequence = ''; 885 if ( $id ) {
922 if (STORAGE == 'postgres') { 886 //increment no of records inserted
923 $sequence = 'entries_id_seq'; 887 $i++;
924 } 888 if ( isset($record['tags']) && trim($record['tags']) ) {
925 $last_id = $this->store->getLastId($sequence); 889 //@TODO: set tags
926 if ($read == '1') { 890
927 $this->action('toggle_archive', $url, $last_id, TRUE); 891 }
928 }
929 $tags = $a[0]->tags;
930 if(!empty($tags)) {
931 $this->action('add_tag',$url,$last_id,true,false,$tags);
932 }
933 } 892 }
934 893 }
935 # the second <ul> is for read links
936 $read = 1;
937 } 894 }
938 $this->messages->add('s', _('import from pocket completed'));
939 Tools::logm('import from pocket completed');
940 Tools::redirect();
941 }
942 895
943 /** 896 if ( $i > 0 ) {
944 * import from Readability. poche needs a ./readability file 897 $this->messages->add('s', _('Articles inserted: ').$i._('. Please note, that some may be marked as "read".'));
945 * @todo add the return value
946 * @param string $targetFile the file used for importing
947 * @return boolean
948 */
949 private function importFromReadability($targetFile)
950 {
951 # TODO gestion des articles lus / favs
952 $str_data = file_get_contents($targetFile);
953 $data = json_decode($str_data,true);
954 Tools::logm('starting import from Readability');
955 $count = 0;
956 foreach ($data as $key => $value) {
957 $url = NULL;
958 $favorite = FALSE;
959 $archive = FALSE;
960 foreach ($value as $item) {
961 foreach ($item as $attr => $value) {
962 if ($attr == 'article__url') {
963 $url = new Url(base64_encode($value));
964 }
965 $sequence = '';
966 if (STORAGE == 'postgres') {
967 $sequence = 'entries_id_seq';
968 }
969 if ($value == 'true') {
970 if ($attr == 'favorite') {
971 $favorite = TRUE;
972 }
973 if ($attr == 'archive') {
974 $archive = TRUE;
975 }
976 }
977 }
978
979 # we can add the url
980 if (!is_null($url) && $url->isCorrect()) {
981 $this->action('add', $url, 0, TRUE);
982 $count++;
983 if ($favorite) {
984 $last_id = $this->store->getLastId($sequence);
985 $this->action('toggle_fav', $url, $last_id, TRUE);
986 }
987 if ($archive) {
988 $last_id = $this->store->getLastId($sequence);
989 $this->action('toggle_archive', $url, $last_id, TRUE);
990 }
991 }
992 }
993 } 898 }
994 $this->messages->add('s', _('import from Readability completed. ' . $count . ' new links.')); 899 }
995 Tools::logm('import from Readability completed'); 900 //file parsing finished here
901
902 //now download article contents if any
903
904 //check if we need to download any content
905 $recordsDownloadRequired = $this->store->retrieveUnfetchedEntriesCount($this->user->getId());
906 if ( $recordsDownloadRequired == 0 ) {
907 //nothing to download
908 $this->messages->add('s', _('Import finished.'));
996 Tools::redirect(); 909 Tools::redirect();
997 } 910 }
911 else {
912 //if just inserted - don't download anything, download will start in next reload
913 if ( !isset($_FILES['file']) ) {
914 //download next batch
915 $items = $this->store->retrieveUnfetchedEntries($this->user->getId(), IMPORT_LIMIT);
998 916
999 /** 917 $config = HTMLPurifier_Config::createDefault();
1000 * import from Poche exported file 918 $config->set('Cache.SerializerPath', CACHE);
1001 * @param string $targetFile the file used for importing 919 $purifier = new HTMLPurifier($config);
1002 * @return boolean
1003 */
1004 private function importFromPoche($targetFile)
1005 {
1006 $str_data = file_get_contents($targetFile);
1007 $data = json_decode($str_data,true);
1008 Tools::logm('starting import from Poche');
1009 920
921 foreach ($items as $item) {
922 $url = new Url(base64_encode($item['url']));
923 $content = Tools::getPageContent($url);
1010 924
1011 $sequence = ''; 925 $title = (($content['rss']['channel']['item']['title'] != '') ? $content['rss']['channel']['item']['title'] : _('Untitled'));
1012 if (STORAGE == 'postgres') { 926 $body = (($content['rss']['channel']['item']['description'] != '') ? $content['rss']['channel']['item']['description'] : _('Undefined'));
1013 $sequence = 'entries_id_seq';
1014 }
1015 927
1016 $count = 0; 928 //clean content to prevent xss attack
1017 foreach ($data as $value) { 929 $title = $purifier->purify($title);
1018 930 $body = $purifier->purify($body);
1019 $url = new Url(base64_encode($value['url'])); 931
1020 $favorite = ($value['is_fav'] == -1); 932 $this->store->updateContentAndTitle($item['id'], $title, $body, $this->user->getId());
1021 $archive = ($value['is_read'] == -1); 933 }
1022
1023 # we can add the url
1024 if (!is_null($url) && $url->isCorrect()) {
1025
1026 $this->action('add', $url, 0, TRUE);
1027
1028 $count++;
1029 if ($favorite) {
1030 $last_id = $this->store->getLastId($sequence);
1031 $this->action('toggle_fav', $url, $last_id, TRUE);
1032 }
1033 if ($archive) {
1034 $last_id = $this->store->getLastId($sequence);
1035 $this->action('toggle_archive', $url, $last_id, TRUE);
1036 }
1037 }
1038
1039 }
1040 $this->messages->add('s', _('import from Poche completed. ' . $count . ' new links.'));
1041 Tools::logm('import from Poche completed');
1042 Tools::redirect();
1043 }
1044 934
1045 /**
1046 * import datas into your poche
1047 * @param string $from name of the service to import : pocket, instapaper or readability
1048 * @todo add the return value
1049 * @return boolean
1050 */
1051 public function import($from)
1052 {
1053 $providers = array(
1054 'pocket' => 'importFromPocket',
1055 'readability' => 'importFromReadability',
1056 'instapaper' => 'importFromInstapaper',
1057 'poche' => 'importFromPoche',
1058 );
1059
1060 if (! isset($providers[$from])) {
1061 $this->messages->add('e', _('Unknown import provider.'));
1062 Tools::redirect();
1063 }
1064
1065 $targetDefinition = 'IMPORT_' . strtoupper($from) . '_FILE';
1066 $targetFile = constant($targetDefinition);
1067
1068 if (! defined($targetDefinition)) {
1069 $this->messages->add('e', _('Incomplete inc/poche/define.inc.php file, please define "' . $targetDefinition . '".'));
1070 Tools::redirect();
1071 }
1072
1073 if (! file_exists($targetFile)) {
1074 $this->messages->add('e', _('Could not find required "' . $targetFile . '" import file.'));
1075 Tools::redirect();
1076 } 935 }
1077 936 }
1078 $this->$providers[$from]($targetFile); 937
938 return array('includeImport'=>true, 'import'=>array('recordsDownloadRequired'=>$recordsDownloadRequired, 'recordsUnderDownload'=> IMPORT_LIMIT, 'delay'=> IMPORT_DELAY * 1000) );
1079 } 939 }
1080 940
1081 /** 941 /**
@@ -1084,6 +944,9 @@ class Poche
1084 */ 944 */
1085 public function export() 945 public function export()
1086 { 946 {
947 $filename = "wallabag-export-".$this->user->getId()."-".date("Y-m-d").".json";
948 header('Content-Disposition: attachment; filename='.$filename);
949
1087 $entries = $this->store->retrieveAll($this->user->getId()); 950 $entries = $this->store->retrieveAll($this->user->getId());
1088 echo $this->tpl->render('export.twig', array( 951 echo $this->tpl->render('export.twig', array(
1089 'export' => Tools::renderJson($entries), 952 'export' => Tools::renderJson($entries),
@@ -1099,21 +962,29 @@ class Poche
1099 private function getPocheVersion($which = 'prod') 962 private function getPocheVersion($which = 'prod')
1100 { 963 {
1101 $cache_file = CACHE . '/' . $which; 964 $cache_file = CACHE . '/' . $which;
965 $check_time = time();
1102 966
1103 # checks if the cached version file exists 967 # checks if the cached version file exists
1104 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) { 968 if (file_exists($cache_file) && (filemtime($cache_file) > (time() - 86400 ))) {
1105 $version = file_get_contents($cache_file); 969 $version = file_get_contents($cache_file);
970 $check_time = filemtime($cache_file);
1106 } else { 971 } else {
1107 $version = file_get_contents('http://static.wallabag.org/versions/' . $which); 972 $version = file_get_contents('http://static.wallabag.org/versions/' . $which);
1108 file_put_contents($cache_file, $version, LOCK_EX); 973 file_put_contents($cache_file, $version, LOCK_EX);
1109 } 974 }
1110 return $version; 975 return array($version, $check_time);
1111 } 976 }
1112 977
1113 public function generateToken() 978 public function generateToken()
1114 { 979 {
1115 if (ini_get('open_basedir') === '') { 980 if (ini_get('open_basedir') === '') {
1116 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15); 981 if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
982 echo 'This is a server using Windows!';
983 // alternative to /dev/urandom for Windows
984 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
985 } else {
986 $token = substr(base64_encode(file_get_contents('/dev/urandom', false, null, 0, 20)), 0, 15);
987 }
1117 } 988 }
1118 else { 989 else {
1119 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20); 990 $token = substr(base64_encode(uniqid(mt_rand(), true)), 0, 20);
@@ -1124,6 +995,7 @@ class Poche
1124 $currentConfig = $_SESSION['poche_user']->config; 995 $currentConfig = $_SESSION['poche_user']->config;
1125 $currentConfig['token'] = $token; 996 $currentConfig['token'] = $token;
1126 $_SESSION['poche_user']->setConfig($currentConfig); 997 $_SESSION['poche_user']->setConfig($currentConfig);
998 Tools::redirect();
1127 } 999 }
1128 1000
1129 public function generateFeeds($token, $user_id, $tag_id, $type = 'home') 1001 public function generateFeeds($token, $user_id, $tag_id, $type = 'home')
@@ -1131,6 +1003,10 @@ class Poche
1131 $allowed_types = array('home', 'fav', 'archive', 'tag'); 1003 $allowed_types = array('home', 'fav', 'archive', 'tag');
1132 $config = $this->store->getConfigUser($user_id); 1004 $config = $this->store->getConfigUser($user_id);
1133 1005
1006 if ($config == null) {
1007 die(_('User with this id (' . $user_id . ') does not exist.'));
1008 }
1009
1134 if (!in_array($type, $allowed_types) || 1010 if (!in_array($type, $allowed_types) ||
1135 $token != $config['token']) { 1011 $token != $config['token']) {
1136 die(_('Uh, there is a problem while generating feeds.')); 1012 die(_('Uh, there is a problem while generating feeds.'));
@@ -1140,8 +1016,9 @@ class Poche
1140 $feed = new FeedWriter(RSS2); 1016 $feed = new FeedWriter(RSS2);
1141 $feed->setTitle('wallabag — ' . $type . ' feed'); 1017 $feed->setTitle('wallabag — ' . $type . ' feed');
1142 $feed->setLink(Tools::getPocheUrl()); 1018 $feed->setLink(Tools::getPocheUrl());
1143 $feed->setChannelElement('updated', date(DATE_RSS , time())); 1019 $feed->setChannelElement('pubDate', date(DATE_RSS , time()));
1144 $feed->setChannelElement('author', 'wallabag'); 1020 $feed->setChannelElement('generator', 'wallabag');
1021 $feed->setDescription('wallabag ' . $type . ' elements');
1145 1022
1146 if ($type == 'tag') { 1023 if ($type == 'tag') {
1147 $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id); 1024 $entries = $this->store->retrieveEntriesByTag($tag_id, $user_id);
@@ -1154,7 +1031,7 @@ class Poche
1154 foreach ($entries as $entry) { 1031 foreach ($entries as $entry) {
1155 $newItem = $feed->createNewItem(); 1032 $newItem = $feed->createNewItem();
1156 $newItem->setTitle($entry['title']); 1033 $newItem->setTitle($entry['title']);
1157 $newItem->setLink(Tools::getPocheUrl() . '?view=view&amp;id=' . $entry['id']); 1034 $newItem->setLink($entry['url']);
1158 $newItem->setDate(time()); 1035 $newItem->setDate(time());
1159 $newItem->setDescription($entry['content']); 1036 $newItem->setDescription($entry['content']);
1160 $feed->addItem($newItem); 1037 $feed->addItem($newItem);
diff --git a/inc/poche/Tools.class.php b/inc/poche/Tools.class.php
index 4ed28ed1..a130e94b 100644..100755
--- a/inc/poche/Tools.class.php
+++ b/inc/poche/Tools.class.php
@@ -7,7 +7,7 @@
7 * @copyright 2013 7 * @copyright 2013
8 * @license http://www.wtfpl.net/ see COPYING file 8 * @license http://www.wtfpl.net/ see COPYING file
9 */ 9 */
10 10
11class Tools 11class Tools
12{ 12{
13 public static function initPhp() 13 public static function initPhp()
@@ -42,7 +42,7 @@ class Tools
42 && (strtolower($_SERVER['HTTPS']) == 'on')) 42 && (strtolower($_SERVER['HTTPS']) == 'on'))
43 || (isset($_SERVER["SERVER_PORT"]) 43 || (isset($_SERVER["SERVER_PORT"])
44 && $_SERVER["SERVER_PORT"] == '443') // HTTPS detection. 44 && $_SERVER["SERVER_PORT"] == '443') // HTTPS detection.
45 || (isset($_SERVER["SERVER_PORT"]) //Custom HTTPS port detection 45 || (isset($_SERVER["SERVER_PORT"]) //Custom HTTPS port detection
46 && $_SERVER["SERVER_PORT"] == SSL_PORT) 46 && $_SERVER["SERVER_PORT"] == SSL_PORT)
47 || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) 47 || (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])
48 && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'); 48 && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https');
@@ -148,7 +148,7 @@ class Tools
148 ); 148 );
149 149
150 # only download page lesser than 4MB 150 # only download page lesser than 4MB
151 $data = @file_get_contents($url, false, $context, -1, 4000000); 151 $data = @file_get_contents($url, false, $context, -1, 4000000);
152 152
153 if (isset($http_response_header) and isset($http_response_header[0])) { 153 if (isset($http_response_header) and isset($http_response_header[0])) {
154 $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)); 154 $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));
@@ -193,14 +193,14 @@ class Tools
193 193
194 public static function logm($message) 194 public static function logm($message)
195 { 195 {
196 if (DEBUG_POCHE) { 196 if (DEBUG_POCHE && php_sapi_name() != 'cli') {
197 $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n"; 197 $t = strval(date('Y/m/d_H:i:s')) . ' - ' . $_SERVER["REMOTE_ADDR"] . ' - ' . strval($message) . "\n";
198 file_put_contents(CACHE . '/log.txt', $t, FILE_APPEND); 198 file_put_contents(CACHE . '/log.txt', $t, FILE_APPEND);
199 error_log('DEBUG POCHE : ' . $message); 199 error_log('DEBUG POCHE : ' . $message);
200 } 200 }
201 } 201 }
202 202
203 public static function encodeString($string) 203 public static function encodeString($string)
204 { 204 {
205 return sha1($string . SALT); 205 return sha1($string . SALT);
206 } 206 }
@@ -241,7 +241,6 @@ class Tools
241 } 241 }
242 } 242 }
243 243
244
245 public static function download_db() { 244 public static function download_db() {
246 header('Content-Disposition: attachment; filename="poche.sqlite.gz"'); 245 header('Content-Disposition: attachment; filename="poche.sqlite.gz"');
247 self::status(200); 246 self::status(200);
@@ -252,4 +251,74 @@ class Tools
252 251
253 exit; 252 exit;
254 } 253 }
254
255 public static function getPageContent(Url $url)
256 {
257 // Saving and clearing context
258 $REAL = array();
259 foreach( $GLOBALS as $key => $value ) {
260 if( $key != 'GLOBALS' && $key != '_SESSION' && $key != 'HTTP_SESSION_VARS' ) {
261 $GLOBALS[$key] = array();
262 $REAL[$key] = $value;
263 }
264 }
265 // Saving and clearing session
266 if ( isset($_SESSION) ) {
267 $REAL_SESSION = array();
268 foreach( $_SESSION as $key => $value ) {
269 $REAL_SESSION[$key] = $value;
270 unset($_SESSION[$key]);
271 }
272 }
273
274 // Running code in different context
275 $scope = function() {
276 extract( func_get_arg(1) );
277 $_GET = $_REQUEST = array(
278 "url" => $url->getUrl(),
279 "max" => 5,
280 "links" => "preserve",
281 "exc" => "",
282 "format" => "json",
283 "submit" => "Create Feed"
284 );
285 ob_start();
286 require func_get_arg(0);
287 $json = ob_get_contents();
288 ob_end_clean();
289 return $json;
290 };
291 $json = $scope( "inc/3rdparty/makefulltextfeed.php", array("url" => $url) );
292
293 // Clearing and restoring context
294 foreach( $GLOBALS as $key => $value ) {
295 if( $key != "GLOBALS" && $key != "_SESSION" ) {
296 unset($GLOBALS[$key]);
297 }
298 }
299 foreach( $REAL as $key => $value ) {
300 $GLOBALS[$key] = $value;
301 }
302 // Clearing and restoring session
303 if ( isset($REAL_SESSION) ) {
304 foreach( $_SESSION as $key => $value ) {
305 unset($_SESSION[$key]);
306 }
307 foreach( $REAL_SESSION as $key => $value ) {
308 $_SESSION[$key] = $value;
309 }
310 }
311
312 return json_decode($json, true);
313 }
314
315 /**
316 * Returns whether we handle an AJAX (XMLHttpRequest) request.
317 * @return boolean whether we handle an AJAX (XMLHttpRequest) request.
318 */
319 public static function isAjaxRequest()
320 {
321 return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
322 }
323
255} 324}
diff --git a/inc/poche/config.inc.php.new b/inc/poche/config.inc.php.new
index 8d52497b..83b3c4c0 100755
--- a/inc/poche/config.inc.php.new
+++ b/inc/poche/config.inc.php.new
@@ -52,12 +52,8 @@ define ('CACHE', ROOT . '/cache');
52 52
53define ('PAGINATION', '10'); 53define ('PAGINATION', '10');
54 54
55define ('POCKET_FILE', '/ril_export.html'); 55//limit for download of articles during import
56define ('READABILITY_FILE', '/readability'); 56define ('IMPORT_LIMIT', 5);
57define ('INSTAPAPER_FILE', '/instapaper-export.html'); 57//delay between downloads (in sec)
58define ('POCHE_FILE', '/poche-export'); 58define ('IMPORT_DELAY', 5);
59 59
60define ('IMPORT_POCKET_FILE', ROOT . POCKET_FILE);
61define ('IMPORT_READABILITY_FILE', ROOT . READABILITY_FILE);
62define ('IMPORT_INSTAPAPER_FILE', ROOT . INSTAPAPER_FILE);
63define ('IMPORT_POCHE_FILE', ROOT . POCHE_FILE); \ No newline at end of file
diff --git a/inc/poche/global.inc.php b/inc/poche/global.inc.php
index d22b0588..15091387 100644
--- a/inc/poche/global.inc.php
+++ b/inc/poche/global.inc.php
@@ -38,7 +38,7 @@ if (! file_exists(ROOT . '/vendor/autoload.php')) {
38 require_once ROOT . '/vendor/autoload.php'; 38 require_once ROOT . '/vendor/autoload.php';
39} 39}
40 40
41# system configuration; database credentials et cetera 41# system configuration; database credentials et caetera
42if (! file_exists(INCLUDES . '/poche/config.inc.php')) { 42if (! file_exists(INCLUDES . '/poche/config.inc.php')) {
43 Poche::$configFileAvailable = false; 43 Poche::$configFileAvailable = false;
44} else { 44} else {