index.php 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855
  1. <?php
  2. /**
  3. * Shaarli - The personal, minimalist, super-fast, database free, bookmarking service.
  4. *
  5. * Friendly fork by the Shaarli community:
  6. * - https://github.com/shaarli/Shaarli
  7. *
  8. * Original project by sebsauvage.net:
  9. * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
  10. * - https://github.com/sebsauvage/Shaarli
  11. *
  12. * Licence: http://www.opensource.org/licenses/zlib-license.php
  13. *
  14. * Requires: PHP 5.5.x
  15. */
  16. // Set 'UTC' as the default timezone if it is not defined in php.ini
  17. // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
  18. if (date_default_timezone_get() == '') {
  19. date_default_timezone_set('UTC');
  20. }
  21. /*
  22. * PHP configuration
  23. */
  24. // http://server.com/x/shaarli --> /shaarli/
  25. define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0)));
  26. // High execution time in case of problematic imports/exports.
  27. ini_set('max_input_time','60');
  28. // Try to set max upload file size and read
  29. ini_set('memory_limit', '128M');
  30. ini_set('post_max_size', '16M');
  31. ini_set('upload_max_filesize', '16M');
  32. // See all error except warnings
  33. error_reporting(E_ALL^E_WARNING);
  34. // See all errors (for debugging only)
  35. //error_reporting(-1);
  36. // 3rd-party libraries
  37. if (! file_exists(__DIR__ . '/vendor/autoload.php')) {
  38. header('Content-Type: text/plain; charset=utf-8');
  39. echo "Error: missing Composer configuration\n\n"
  40. ."If you installed Shaarli through Git or using the development branch,\n"
  41. ."please refer to the installation documentation to install PHP"
  42. ." dependencies using Composer:\n"
  43. ."- https://shaarli.readthedocs.io/en/master/Server-configuration/\n"
  44. ."- https://shaarli.readthedocs.io/en/master/Download-and-Installation/";
  45. exit;
  46. }
  47. require_once 'inc/rain.tpl.class.php';
  48. require_once __DIR__ . '/vendor/autoload.php';
  49. // Shaarli library
  50. require_once 'application/ApplicationUtils.php';
  51. require_once 'application/Cache.php';
  52. require_once 'application/CachedPage.php';
  53. require_once 'application/config/ConfigPlugin.php';
  54. require_once 'application/FeedBuilder.php';
  55. require_once 'application/FileUtils.php';
  56. require_once 'application/History.php';
  57. require_once 'application/HttpUtils.php';
  58. require_once 'application/LinkDB.php';
  59. require_once 'application/LinkFilter.php';
  60. require_once 'application/LinkUtils.php';
  61. require_once 'application/NetscapeBookmarkUtils.php';
  62. require_once 'application/PageBuilder.php';
  63. require_once 'application/TimeZone.php';
  64. require_once 'application/Url.php';
  65. require_once 'application/Utils.php';
  66. require_once 'application/PluginManager.php';
  67. require_once 'application/Router.php';
  68. require_once 'application/Updater.php';
  69. use \Shaarli\Config\ConfigManager;
  70. use \Shaarli\Languages;
  71. use \Shaarli\Security\LoginManager;
  72. use \Shaarli\Security\SessionManager;
  73. use \Shaarli\ThemeUtils;
  74. use \Shaarli\Thumbnailer;
  75. // Ensure the PHP version is supported
  76. try {
  77. ApplicationUtils::checkPHPVersion('5.5', PHP_VERSION);
  78. } catch(Exception $exc) {
  79. header('Content-Type: text/plain; charset=utf-8');
  80. echo $exc->getMessage();
  81. exit;
  82. }
  83. define('SHAARLI_VERSION', ApplicationUtils::getVersion(__DIR__ .'/'. ApplicationUtils::$VERSION_FILE));
  84. // Force cookie path (but do not change lifetime)
  85. $cookie = session_get_cookie_params();
  86. $cookiedir = '';
  87. if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
  88. $cookiedir = dirname($_SERVER["SCRIPT_NAME"]).'/';
  89. }
  90. // Set default cookie expiration and path.
  91. session_set_cookie_params($cookie['lifetime'], $cookiedir, $_SERVER['SERVER_NAME']);
  92. // Set session parameters on server side.
  93. // Use cookies to store session.
  94. ini_set('session.use_cookies', 1);
  95. // Force cookies for session (phpsessionID forbidden in URL).
  96. ini_set('session.use_only_cookies', 1);
  97. // Prevent PHP form using sessionID in URL if cookies are disabled.
  98. ini_set('session.use_trans_sid', false);
  99. session_name('shaarli');
  100. // Start session if needed (Some server auto-start sessions).
  101. if (session_id() == '') {
  102. session_start();
  103. }
  104. // Regenerate session ID if invalid or not defined in cookie.
  105. if (isset($_COOKIE['shaarli']) && !SessionManager::checkId($_COOKIE['shaarli'])) {
  106. session_regenerate_id(true);
  107. $_COOKIE['shaarli'] = session_id();
  108. }
  109. $conf = new ConfigManager();
  110. $sessionManager = new SessionManager($_SESSION, $conf);
  111. $loginManager = new LoginManager($GLOBALS, $conf, $sessionManager);
  112. $loginManager->generateStaySignedInToken($_SERVER['REMOTE_ADDR']);
  113. $clientIpId = client_ip_id($_SERVER);
  114. // LC_MESSAGES isn't defined without php-intl, in this case use LC_COLLATE locale instead.
  115. if (! defined('LC_MESSAGES')) {
  116. define('LC_MESSAGES', LC_COLLATE);
  117. }
  118. // Sniff browser language and set date format accordingly.
  119. if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) {
  120. autoLocale($_SERVER['HTTP_ACCEPT_LANGUAGE']);
  121. }
  122. new Languages(setlocale(LC_MESSAGES, 0), $conf);
  123. $conf->setEmpty('general.timezone', date_default_timezone_get());
  124. $conf->setEmpty('general.title', t('Shared links on '). escape(index_url($_SERVER)));
  125. RainTPL::$tpl_dir = $conf->get('resource.raintpl_tpl').'/'.$conf->get('resource.theme').'/'; // template directory
  126. RainTPL::$cache_dir = $conf->get('resource.raintpl_tmp'); // cache directory
  127. $pluginManager = new PluginManager($conf);
  128. $pluginManager->load($conf->get('general.enabled_plugins'));
  129. date_default_timezone_set($conf->get('general.timezone', 'UTC'));
  130. ob_start(); // Output buffering for the page cache.
  131. // Prevent caching on client side or proxy: (yes, it's ugly)
  132. header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
  133. header("Cache-Control: no-store, no-cache, must-revalidate");
  134. header("Cache-Control: post-check=0, pre-check=0", false);
  135. header("Pragma: no-cache");
  136. if (! is_file($conf->getConfigFileExt())) {
  137. // Ensure Shaarli has proper access to its resources
  138. $errors = ApplicationUtils::checkResourcePermissions($conf);
  139. if ($errors != array()) {
  140. $message = '<p>'. t('Insufficient permissions:') .'</p><ul>';
  141. foreach ($errors as $error) {
  142. $message .= '<li>'.$error.'</li>';
  143. }
  144. $message .= '</ul>';
  145. header('Content-Type: text/html; charset=utf-8');
  146. echo $message;
  147. exit;
  148. }
  149. // Display the installation form if no existing config is found
  150. install($conf, $sessionManager, $loginManager);
  151. }
  152. $loginManager->checkLoginState($_COOKIE, $clientIpId);
  153. /**
  154. * Adapter function to ensure compatibility with third-party templates
  155. *
  156. * @see https://github.com/shaarli/Shaarli/pull/1086
  157. *
  158. * @return bool true when the user is logged in, false otherwise
  159. */
  160. function isLoggedIn()
  161. {
  162. global $loginManager;
  163. return $loginManager->isLoggedIn();
  164. }
  165. // ------------------------------------------------------------------------------------------
  166. // Process login form: Check if login/password is correct.
  167. if (isset($_POST['login'])) {
  168. if (! $loginManager->canLogin($_SERVER)) {
  169. die(t('I said: NO. You are banned for the moment. Go away.'));
  170. }
  171. if (isset($_POST['password'])
  172. && $sessionManager->checkToken($_POST['token'])
  173. && $loginManager->checkCredentials($_SERVER['REMOTE_ADDR'], $clientIpId, $_POST['login'], $_POST['password'])
  174. ) {
  175. $loginManager->handleSuccessfulLogin($_SERVER);
  176. $cookiedir = '';
  177. if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
  178. // Note: Never forget the trailing slash on the cookie path!
  179. $cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
  180. }
  181. if (!empty($_POST['longlastingsession'])) {
  182. // Keep the session cookie even after the browser closes
  183. $sessionManager->setStaySignedIn(true);
  184. $expirationTime = $sessionManager->extendSession();
  185. setcookie(
  186. $loginManager::$STAY_SIGNED_IN_COOKIE,
  187. $loginManager->getStaySignedInToken(),
  188. $expirationTime,
  189. WEB_PATH
  190. );
  191. } else {
  192. // Standard session expiration (=when browser closes)
  193. $expirationTime = 0;
  194. }
  195. // Send cookie with the new expiration date to the browser
  196. session_set_cookie_params($expirationTime, $cookiedir, $_SERVER['SERVER_NAME']);
  197. session_regenerate_id(true);
  198. // Optional redirect after login:
  199. if (isset($_GET['post'])) {
  200. $uri = '?post='. urlencode($_GET['post']);
  201. foreach (array('description', 'source', 'title', 'tags') as $param) {
  202. if (!empty($_GET[$param])) {
  203. $uri .= '&'.$param.'='.urlencode($_GET[$param]);
  204. }
  205. }
  206. header('Location: '. $uri);
  207. exit;
  208. }
  209. if (isset($_GET['edit_link'])) {
  210. header('Location: ?edit_link='. escape($_GET['edit_link']));
  211. exit;
  212. }
  213. if (isset($_POST['returnurl'])) {
  214. // Prevent loops over login screen.
  215. if (strpos($_POST['returnurl'], 'do=login') === false) {
  216. header('Location: '. generateLocation($_POST['returnurl'], $_SERVER['HTTP_HOST']));
  217. exit;
  218. }
  219. }
  220. header('Location: ?'); exit;
  221. } else {
  222. $loginManager->handleFailedLogin($_SERVER);
  223. $redir = '&username='. urlencode($_POST['login']);
  224. if (isset($_GET['post'])) {
  225. $redir .= '&post=' . urlencode($_GET['post']);
  226. foreach (array('description', 'source', 'title', 'tags') as $param) {
  227. if (!empty($_GET[$param])) {
  228. $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
  229. }
  230. }
  231. }
  232. // Redirect to login screen.
  233. echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
  234. exit;
  235. }
  236. }
  237. // ------------------------------------------------------------------------------------------
  238. // Token management for XSRF protection
  239. // Token should be used in any form which acts on data (create,update,delete,import...).
  240. if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
  241. /**
  242. * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
  243. * Gives the last 7 days (which have links).
  244. * This RSS feed cannot be filtered.
  245. *
  246. * @param ConfigManager $conf Configuration Manager instance
  247. * @param LoginManager $loginManager LoginManager instance
  248. */
  249. function showDailyRSS($conf, $loginManager) {
  250. // Cache system
  251. $query = $_SERVER['QUERY_STRING'];
  252. $cache = new CachedPage(
  253. $conf->get('config.PAGE_CACHE'),
  254. page_url($_SERVER),
  255. startsWith($query,'do=dailyrss') && !$loginManager->isLoggedIn()
  256. );
  257. $cached = $cache->cachedVersion();
  258. if (!empty($cached)) {
  259. echo $cached;
  260. exit;
  261. }
  262. // If cached was not found (or not usable), then read the database and build the response:
  263. // Read links from database (and filter private links if used it not logged in).
  264. $LINKSDB = new LinkDB(
  265. $conf->get('resource.datastore'),
  266. $loginManager->isLoggedIn(),
  267. $conf->get('privacy.hide_public_links'),
  268. $conf->get('redirector.url'),
  269. $conf->get('redirector.encode_url')
  270. );
  271. /* Some Shaarlies may have very few links, so we need to look
  272. back in time until we have enough days ($nb_of_days).
  273. */
  274. $nb_of_days = 7; // We take 7 days.
  275. $today = date('Ymd');
  276. $days = array();
  277. foreach ($LINKSDB as $link) {
  278. $day = $link['created']->format('Ymd'); // Extract day (without time)
  279. if (strcmp($day, $today) < 0) {
  280. if (empty($days[$day])) {
  281. $days[$day] = array();
  282. }
  283. $days[$day][] = $link;
  284. }
  285. if (count($days) > $nb_of_days) {
  286. break; // Have we collected enough days?
  287. }
  288. }
  289. // Build the RSS feed.
  290. header('Content-Type: application/rss+xml; charset=utf-8');
  291. $pageaddr = escape(index_url($_SERVER));
  292. echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
  293. echo '<channel>';
  294. echo '<title>Daily - '. $conf->get('general.title') . '</title>';
  295. echo '<link>'. $pageaddr .'</link>';
  296. echo '<description>Daily shared links</description>';
  297. echo '<language>en-en</language>';
  298. echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL;
  299. // For each day.
  300. foreach ($days as $day => $links) {
  301. $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
  302. $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
  303. // We pre-format some fields for proper output.
  304. foreach ($links as &$link) {
  305. $link['formatedDescription'] = format_description(
  306. $link['description'],
  307. $conf->get('redirector.url'),
  308. $conf->get('redirector.encode_url')
  309. );
  310. $link['thumbnail'] = thumbnail($conf, $link['url']);
  311. $link['timestamp'] = $link['created']->getTimestamp();
  312. if (startsWith($link['url'], '?')) {
  313. $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
  314. }
  315. }
  316. // Then build the HTML for this day:
  317. $tpl = new RainTPL;
  318. $tpl->assign('title', $conf->get('general.title'));
  319. $tpl->assign('daydate', $dayDate->getTimestamp());
  320. $tpl->assign('absurl', $absurl);
  321. $tpl->assign('links', $links);
  322. $tpl->assign('rssdate', escape($dayDate->format(DateTime::RSS)));
  323. $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
  324. $html = $tpl->draw('dailyrss', true);
  325. echo $html . PHP_EOL;
  326. }
  327. echo '</channel></rss><!-- Cached version of '. escape(page_url($_SERVER)) .' -->';
  328. $cache->cache(ob_get_contents());
  329. ob_end_flush();
  330. exit;
  331. }
  332. /**
  333. * Show the 'Daily' page.
  334. *
  335. * @param PageBuilder $pageBuilder Template engine wrapper.
  336. * @param LinkDB $LINKSDB LinkDB instance.
  337. * @param ConfigManager $conf Configuration Manager instance.
  338. * @param PluginManager $pluginManager Plugin Manager instance.
  339. * @param LoginManager $loginManager Login Manager instance
  340. */
  341. function showDaily($pageBuilder, $LINKSDB, $conf, $pluginManager, $loginManager)
  342. {
  343. $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
  344. if (isset($_GET['day'])) {
  345. $day = $_GET['day'];
  346. }
  347. $days = $LINKSDB->days();
  348. $i = array_search($day, $days);
  349. if ($i === false && count($days)) {
  350. // no links for day, but at least one day with links
  351. $i = count($days) - 1;
  352. $day = $days[$i];
  353. }
  354. $previousday = '';
  355. $nextday = '';
  356. if ($i !== false) {
  357. if ($i >= 1) {
  358. $previousday=$days[$i - 1];
  359. }
  360. if ($i < count($days) - 1) {
  361. $nextday = $days[$i + 1];
  362. }
  363. }
  364. try {
  365. $linksToDisplay = $LINKSDB->filterDay($day);
  366. } catch (Exception $exc) {
  367. error_log($exc);
  368. $linksToDisplay = array();
  369. }
  370. // We pre-format some fields for proper output.
  371. foreach($linksToDisplay as $key => $link) {
  372. $taglist = explode(' ',$link['tags']);
  373. uasort($taglist, 'strcasecmp');
  374. $linksToDisplay[$key]['taglist']=$taglist;
  375. $linksToDisplay[$key]['formatedDescription'] = format_description(
  376. $link['description'],
  377. $conf->get('redirector.url'),
  378. $conf->get('redirector.encode_url')
  379. );
  380. $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
  381. $linksToDisplay[$key]['timestamp'] = $link['created']->getTimestamp();
  382. }
  383. $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
  384. $data = array(
  385. 'pagetitle' => $conf->get('general.title') .' - '. format_date($dayDate, false),
  386. 'linksToDisplay' => $linksToDisplay,
  387. 'day' => $dayDate->getTimestamp(),
  388. 'dayDate' => $dayDate,
  389. 'previousday' => $previousday,
  390. 'nextday' => $nextday,
  391. );
  392. /* Hook is called before column construction so that plugins don't have
  393. to deal with columns. */
  394. $pluginManager->executeHooks('render_daily', $data, array('loggedin' => $loginManager->isLoggedIn()));
  395. /* We need to spread the articles on 3 columns.
  396. I did not want to use a JavaScript lib like http://masonry.desandro.com/
  397. so I manually spread entries with a simple method: I roughly evaluate the
  398. height of a div according to title and description length.
  399. */
  400. $columns = array(array(), array(), array()); // Entries to display, for each column.
  401. $fill = array(0, 0, 0); // Rough estimate of columns fill.
  402. foreach($data['linksToDisplay'] as $key => $link) {
  403. // Roughly estimate length of entry (by counting characters)
  404. // Title: 30 chars = 1 line. 1 line is 30 pixels height.
  405. // Description: 836 characters gives roughly 342 pixel height.
  406. // This is not perfect, but it's usually OK.
  407. $length = strlen($link['title']) + (342 * strlen($link['description'])) / 836;
  408. if ($link['thumbnail']) {
  409. $length += 100; // 1 thumbnails roughly takes 100 pixels height.
  410. }
  411. // Then put in column which is the less filled:
  412. $smallest = min($fill); // find smallest value in array.
  413. $index = array_search($smallest, $fill); // find index of this smallest value.
  414. array_push($columns[$index], $link); // Put entry in this column.
  415. $fill[$index] += $length;
  416. }
  417. $data['cols'] = $columns;
  418. foreach ($data as $key => $value) {
  419. $pageBuilder->assign($key, $value);
  420. }
  421. $pageBuilder->assign('pagetitle', t('Daily') .' - '. $conf->get('general.title', 'Shaarli'));
  422. $pageBuilder->renderPage('daily');
  423. exit;
  424. }
  425. /**
  426. * Renders the linklist
  427. *
  428. * @param pageBuilder $PAGE pageBuilder instance.
  429. * @param LinkDB $LINKSDB LinkDB instance.
  430. * @param ConfigManager $conf Configuration Manager instance.
  431. * @param PluginManager $pluginManager Plugin Manager instance.
  432. */
  433. function showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager) {
  434. buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager, $loginManager);
  435. $PAGE->renderPage('linklist');
  436. }
  437. /**
  438. * Render HTML page (according to URL parameters and user rights)
  439. *
  440. * @param ConfigManager $conf Configuration Manager instance.
  441. * @param PluginManager $pluginManager Plugin Manager instance,
  442. * @param LinkDB $LINKSDB
  443. * @param History $history instance
  444. * @param SessionManager $sessionManager SessionManager instance
  445. * @param LoginManager $loginManager LoginManager instance
  446. */
  447. function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
  448. {
  449. $updater = new Updater(
  450. read_updates_file($conf->get('resource.updates')),
  451. $LINKSDB,
  452. $conf,
  453. $loginManager->isLoggedIn(),
  454. $_SESSION
  455. );
  456. try {
  457. $newUpdates = $updater->update();
  458. if (! empty($newUpdates)) {
  459. write_updates_file(
  460. $conf->get('resource.updates'),
  461. $updater->getDoneUpdates()
  462. );
  463. }
  464. }
  465. catch(Exception $e) {
  466. die($e->getMessage());
  467. }
  468. $PAGE = new PageBuilder($conf, $_SESSION, $LINKSDB, $sessionManager->generateToken(), $loginManager->isLoggedIn());
  469. $PAGE->assign('linkcount', count($LINKSDB));
  470. $PAGE->assign('privateLinkcount', count_private($LINKSDB));
  471. $PAGE->assign('plugin_errors', $pluginManager->getErrors());
  472. // Determine which page will be rendered.
  473. $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
  474. $targetPage = Router::findPage($query, $_GET, $loginManager->isLoggedIn());
  475. if (
  476. // if the user isn't logged in
  477. !$loginManager->isLoggedIn() &&
  478. // and Shaarli doesn't have public content...
  479. $conf->get('privacy.hide_public_links') &&
  480. // and is configured to enforce the login
  481. $conf->get('privacy.force_login') &&
  482. // and the current page isn't already the login page
  483. $targetPage !== Router::$PAGE_LOGIN &&
  484. // and the user is not requesting a feed (which would lead to a different content-type as expected)
  485. $targetPage !== Router::$PAGE_FEED_ATOM &&
  486. $targetPage !== Router::$PAGE_FEED_RSS
  487. ) {
  488. // force current page to be the login page
  489. $targetPage = Router::$PAGE_LOGIN;
  490. }
  491. // Call plugin hooks for header, footer and includes, specifying which page will be rendered.
  492. // Then assign generated data to RainTPL.
  493. $common_hooks = array(
  494. 'includes',
  495. 'header',
  496. 'footer',
  497. );
  498. foreach($common_hooks as $name) {
  499. $plugin_data = array();
  500. $pluginManager->executeHooks('render_' . $name, $plugin_data,
  501. array(
  502. 'target' => $targetPage,
  503. 'loggedin' => $loginManager->isLoggedIn()
  504. )
  505. );
  506. $PAGE->assign('plugins_' . $name, $plugin_data);
  507. }
  508. // -------- Display login form.
  509. if ($targetPage == Router::$PAGE_LOGIN)
  510. {
  511. if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
  512. if (isset($_GET['username'])) {
  513. $PAGE->assign('username', escape($_GET['username']));
  514. }
  515. $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
  516. // add default state of the 'remember me' checkbox
  517. $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
  518. $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
  519. $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
  520. $PAGE->renderPage('loginform');
  521. exit;
  522. }
  523. // -------- User wants to logout.
  524. if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
  525. {
  526. invalidateCaches($conf->get('resource.page_cache'));
  527. $sessionManager->logout();
  528. setcookie(LoginManager::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH);
  529. header('Location: ?');
  530. exit;
  531. }
  532. // -------- Picture wall
  533. if ($targetPage == Router::$PAGE_PICWALL)
  534. {
  535. if (! $conf->get('thumbnails.enabled')) {
  536. $PAGE->renderPage('picwall');
  537. exit;
  538. }
  539. // Optionally filter the results:
  540. $links = $LINKSDB->filterSearch($_GET);
  541. $linksToDisplay = array();
  542. // Get only links which have a thumbnail.
  543. // Note: we do not retrieve thumbnails here, the request is too heavy.
  544. foreach($links as $key => $link)
  545. {
  546. if (isset($link['thumbnail']) && $link['thumbnail'] !== false) {
  547. $linksToDisplay[] = $link; // Add to array.
  548. }
  549. }
  550. $data = array(
  551. 'linksToDisplay' => $linksToDisplay,
  552. );
  553. $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => $loginManager->isLoggedIn()));
  554. foreach ($data as $key => $value) {
  555. $PAGE->assign($key, $value);
  556. }
  557. $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
  558. $PAGE->renderPage('picwall');
  559. exit;
  560. }
  561. // -------- Tag cloud
  562. if ($targetPage == Router::$PAGE_TAGCLOUD)
  563. {
  564. $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
  565. $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
  566. $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
  567. // We sort tags alphabetically, then choose a font size according to count.
  568. // First, find max value.
  569. $maxcount = 0;
  570. foreach ($tags as $value) {
  571. $maxcount = max($maxcount, $value);
  572. }
  573. alphabetical_sort($tags, false, true);
  574. $tagList = array();
  575. foreach($tags as $key => $value) {
  576. if (in_array($key, $filteringTags)) {
  577. continue;
  578. }
  579. // Tag font size scaling:
  580. // default 15 and 30 logarithm bases affect scaling,
  581. // 22 and 6 are arbitrary font sizes for max and min sizes.
  582. $size = log($value, 15) / log($maxcount, 30) * 2.2 + 0.8;
  583. $tagList[$key] = array(
  584. 'count' => $value,
  585. 'size' => number_format($size, 2, '.', ''),
  586. );
  587. }
  588. $searchTags = implode(' ', escape($filteringTags));
  589. $data = array(
  590. 'search_tags' => $searchTags,
  591. 'tags' => $tagList,
  592. );
  593. $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
  594. foreach ($data as $key => $value) {
  595. $PAGE->assign($key, $value);
  596. }
  597. $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
  598. $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
  599. $PAGE->renderPage('tag.cloud');
  600. exit;
  601. }
  602. // -------- Tag list
  603. if ($targetPage == Router::$PAGE_TAGLIST)
  604. {
  605. $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
  606. $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
  607. $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
  608. foreach ($filteringTags as $tag) {
  609. if (array_key_exists($tag, $tags)) {
  610. unset($tags[$tag]);
  611. }
  612. }
  613. if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
  614. alphabetical_sort($tags, false, true);
  615. }
  616. $searchTags = implode(' ', escape($filteringTags));
  617. $data = [
  618. 'search_tags' => $searchTags,
  619. 'tags' => $tags,
  620. ];
  621. $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
  622. foreach ($data as $key => $value) {
  623. $PAGE->assign($key, $value);
  624. }
  625. $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
  626. $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
  627. $PAGE->renderPage('tag.list');
  628. exit;
  629. }
  630. // Daily page.
  631. if ($targetPage == Router::$PAGE_DAILY) {
  632. showDaily($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
  633. }
  634. // ATOM and RSS feed.
  635. if ($targetPage == Router::$PAGE_FEED_ATOM || $targetPage == Router::$PAGE_FEED_RSS) {
  636. $feedType = $targetPage == Router::$PAGE_FEED_RSS ? FeedBuilder::$FEED_RSS : FeedBuilder::$FEED_ATOM;
  637. header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
  638. // Cache system
  639. $query = $_SERVER['QUERY_STRING'];
  640. $cache = new CachedPage(
  641. $conf->get('resource.page_cache'),
  642. page_url($_SERVER),
  643. startsWith($query,'do='. $targetPage) && !$loginManager->isLoggedIn()
  644. );
  645. $cached = $cache->cachedVersion();
  646. if (!empty($cached)) {
  647. echo $cached;
  648. exit;
  649. }
  650. // Generate data.
  651. $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, $loginManager->isLoggedIn());
  652. $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0)));
  653. $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
  654. $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
  655. $data = $feedGenerator->buildData();
  656. // Process plugin hook.
  657. $pluginManager->executeHooks('render_feed', $data, array(
  658. 'loggedin' => $loginManager->isLoggedIn(),
  659. 'target' => $targetPage,
  660. ));
  661. // Render the template.
  662. $PAGE->assignAll($data);
  663. $PAGE->renderPage('feed.'. $feedType);
  664. $cache->cache(ob_get_contents());
  665. ob_end_flush();
  666. exit;
  667. }
  668. // Display opensearch plugin (XML)
  669. if ($targetPage == Router::$PAGE_OPENSEARCH) {
  670. header('Content-Type: application/xml; charset=utf-8');
  671. $PAGE->assign('serverurl', index_url($_SERVER));
  672. $PAGE->renderPage('opensearch');
  673. exit;
  674. }
  675. // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
  676. if (isset($_GET['addtag']))
  677. {
  678. // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
  679. if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER
  680. parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
  681. // Prevent redirection loop
  682. if (isset($params['addtag'])) {
  683. unset($params['addtag']);
  684. }
  685. // Check if this tag is already in the search query and ignore it if it is.
  686. // Each tag is always separated by a space
  687. if (isset($params['searchtags'])) {
  688. $current_tags = explode(' ', $params['searchtags']);
  689. } else {
  690. $current_tags = array();
  691. }
  692. $addtag = true;
  693. foreach ($current_tags as $value) {
  694. if ($value === $_GET['addtag']) {
  695. $addtag = false;
  696. break;
  697. }
  698. }
  699. // Append the tag if necessary
  700. if (empty($params['searchtags'])) {
  701. $params['searchtags'] = trim($_GET['addtag']);
  702. }
  703. elseif ($addtag) {
  704. $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
  705. }
  706. unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
  707. header('Location: ?'.http_build_query($params));
  708. exit;
  709. }
  710. // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
  711. if (isset($_GET['removetag'])) {
  712. // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
  713. if (empty($_SERVER['HTTP_REFERER'])) {
  714. header('Location: ?');
  715. exit;
  716. }
  717. // In case browser does not send HTTP_REFERER
  718. parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
  719. // Prevent redirection loop
  720. if (isset($params['removetag'])) {
  721. unset($params['removetag']);
  722. }
  723. if (isset($params['searchtags'])) {
  724. $tags = explode(' ', $params['searchtags']);
  725. // Remove value from array $tags.
  726. $tags = array_diff($tags, array($_GET['removetag']));
  727. $params['searchtags'] = implode(' ',$tags);
  728. if (empty($params['searchtags'])) {
  729. unset($params['searchtags']);
  730. }
  731. unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
  732. }
  733. header('Location: ?'.http_build_query($params));
  734. exit;
  735. }
  736. // -------- User wants to change the number of links per page (linksperpage=...)
  737. if (isset($_GET['linksperpage'])) {
  738. if (is_numeric($_GET['linksperpage'])) {
  739. $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
  740. }
  741. if (! empty($_SERVER['HTTP_REFERER'])) {
  742. $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
  743. } else {
  744. $location = '?';
  745. }
  746. header('Location: '. $location);
  747. exit;
  748. }
  749. // -------- User wants to see only private links (toggle)
  750. if (isset($_GET['visibility'])) {
  751. if ($_GET['visibility'] === 'private') {
  752. // Visibility not set or not already private, set private, otherwise reset it
  753. if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
  754. // See only private links
  755. $_SESSION['visibility'] = 'private';
  756. } else {
  757. unset($_SESSION['visibility']);
  758. }
  759. } elseif ($_GET['visibility'] === 'public') {
  760. if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
  761. // See only public links
  762. $_SESSION['visibility'] = 'public';
  763. } else {
  764. unset($_SESSION['visibility']);
  765. }
  766. }
  767. if (! empty($_SERVER['HTTP_REFERER'])) {
  768. $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
  769. } else {
  770. $location = '?';
  771. }
  772. header('Location: '. $location);
  773. exit;
  774. }
  775. // -------- User wants to see only untagged links (toggle)
  776. if (isset($_GET['untaggedonly'])) {
  777. $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
  778. if (! empty($_SERVER['HTTP_REFERER'])) {
  779. $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
  780. } else {
  781. $location = '?';
  782. }
  783. header('Location: '. $location);
  784. exit;
  785. }
  786. // -------- Handle other actions allowed for non-logged in users:
  787. if (!$loginManager->isLoggedIn())
  788. {
  789. // User tries to post new link but is not logged in:
  790. // Show login screen, then redirect to ?post=...
  791. if (isset($_GET['post']))
  792. {
  793. header( // Redirect to login page, then back to post link.
  794. 'Location: ?do=login&post='.urlencode($_GET['post']).
  795. (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
  796. (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
  797. (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
  798. (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
  799. );
  800. exit;
  801. }
  802. showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
  803. if (isset($_GET['edit_link'])) {
  804. header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
  805. exit;
  806. }
  807. exit; // Never remove this one! All operations below are reserved for logged in user.
  808. }
  809. // -------- All other functions are reserved for the registered user:
  810. // -------- Display the Tools menu if requested (import/export/bookmarklet...)
  811. if ($targetPage == Router::$PAGE_TOOLS)
  812. {
  813. $data = [
  814. 'pageabsaddr' => index_url($_SERVER),
  815. 'sslenabled' => is_https($_SERVER),
  816. ];
  817. $pluginManager->executeHooks('render_tools', $data);
  818. foreach ($data as $key => $value) {
  819. $PAGE->assign($key, $value);
  820. }
  821. $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
  822. $PAGE->renderPage('tools');
  823. exit;
  824. }
  825. // -------- User wants to change his/her password.
  826. if ($targetPage == Router::$PAGE_CHANGEPASSWORD)
  827. {
  828. if ($conf->get('security.open_shaarli')) {
  829. die(t('You are not supposed to change a password on an Open Shaarli.'));
  830. }
  831. if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
  832. {
  833. if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away!
  834. // Make sure old password is correct.
  835. $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
  836. if ($oldhash!= $conf->get('credentials.hash')) {
  837. echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>';
  838. exit;
  839. }
  840. // Save new password
  841. // Salt renders rainbow-tables attacks useless.
  842. $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
  843. $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt')));
  844. try {
  845. $conf->write($loginManager->isLoggedIn());
  846. }
  847. catch(Exception $e) {
  848. error_log(
  849. 'ERROR while writing config file after changing password.' . PHP_EOL .
  850. $e->getMessage()
  851. );
  852. // TODO: do not handle exceptions/errors in JS.
  853. echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
  854. exit;
  855. }
  856. echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
  857. exit;
  858. }
  859. else // show the change password form.
  860. {
  861. $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
  862. $PAGE->renderPage('changepassword');
  863. exit;
  864. }
  865. }
  866. // -------- User wants to change configuration
  867. if ($targetPage == Router::$PAGE_CONFIGURE)
  868. {
  869. if (!empty($_POST['title']) )
  870. {
  871. if (!$sessionManager->checkToken($_POST['token'])) {
  872. die(t('Wrong token.')); // Go away!
  873. }
  874. $tz = 'UTC';
  875. if (!empty($_POST['continent']) && !empty($_POST['city'])
  876. && isTimeZoneValid($_POST['continent'], $_POST['city'])
  877. ) {
  878. $tz = $_POST['continent'] . '/' . $_POST['city'];
  879. }
  880. $conf->set('general.timezone', $tz);
  881. $conf->set('general.title', escape($_POST['title']));
  882. $conf->set('general.header_link', escape($_POST['titleLink']));
  883. $conf->set('resource.theme', escape($_POST['theme']));
  884. $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
  885. $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
  886. $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
  887. $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
  888. $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
  889. $conf->set('api.enabled', !empty($_POST['enableApi']));
  890. $conf->set('api.secret', escape($_POST['apiSecret']));
  891. $conf->set('translation.language', escape($_POST['language']));
  892. $thumbnailsEnabled = extension_loaded('gd') && !empty($_POST['enableThumbnails']);
  893. $conf->set('thumbnails.enabled', $thumbnailsEnabled);
  894. if (! $conf->get('thumbnails.enabled') && $thumbnailsEnabled) {
  895. $_SESSION['warnings'][] = t(
  896. 'You have enabled thumbnails. <a href="?do=thumbs_update">Please synchonize them</a>.'
  897. );
  898. }
  899. try {
  900. $conf->write($loginManager->isLoggedIn());
  901. $history->updateSettings();
  902. invalidateCaches($conf->get('resource.page_cache'));
  903. }
  904. catch(Exception $e) {
  905. error_log(
  906. 'ERROR while writing config file after configuration update.' . PHP_EOL .
  907. $e->getMessage()
  908. );
  909. // TODO: do not handle exceptions/errors in JS.
  910. echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
  911. exit;
  912. }
  913. echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
  914. exit;
  915. }
  916. else // Show the configuration form.
  917. {
  918. $PAGE->assign('title', $conf->get('general.title'));
  919. $PAGE->assign('theme', $conf->get('resource.theme'));
  920. $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl')));
  921. list($continents, $cities) = generateTimeZoneData(
  922. timezone_identifiers_list(),
  923. $conf->get('general.timezone')
  924. );
  925. $PAGE->assign('continents', $continents);
  926. $PAGE->assign('cities', $cities);
  927. $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
  928. $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
  929. $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
  930. $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
  931. $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
  932. $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
  933. $PAGE->assign('api_secret', $conf->get('api.secret'));
  934. $PAGE->assign('languages', Languages::getAvailableLanguages());
  935. $PAGE->assign('language', $conf->get('translation.language'));
  936. $PAGE->assign('gd_enabled', extension_loaded('gd'));
  937. $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
  938. $PAGE->renderPage('configure');
  939. exit;
  940. }
  941. }
  942. // -------- User wants to rename a tag or delete it
  943. if ($targetPage == Router::$PAGE_CHANGETAG)
  944. {
  945. if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
  946. $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
  947. $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
  948. $PAGE->renderPage('changetag');
  949. exit;
  950. }
  951. if (!$sessionManager->checkToken($_POST['token'])) {
  952. die(t('Wrong token.'));
  953. }
  954. $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), escape($_POST['totag']));
  955. $LINKSDB->save($conf->get('resource.page_cache'));
  956. foreach ($alteredLinks as $link) {
  957. $history->updateLink($link);
  958. }
  959. $delete = empty($_POST['totag']);
  960. $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
  961. $count = count($alteredLinks);
  962. $alert = $delete
  963. ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d links.', $count), $count)
  964. : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d links.', $count), $count);
  965. echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
  966. exit;
  967. }
  968. // -------- User wants to add a link without using the bookmarklet: Show form.
  969. if ($targetPage == Router::$PAGE_ADDLINK)
  970. {
  971. $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
  972. $PAGE->renderPage('addlink');
  973. exit;
  974. }
  975. // -------- User clicked the "Save" button when editing a link: Save link to database.
  976. if (isset($_POST['save_edit']))
  977. {
  978. // Go away!
  979. if (! $sessionManager->checkToken($_POST['token'])) {
  980. die(t('Wrong token.'));
  981. }
  982. // lf_id should only be present if the link exists.
  983. $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
  984. // Linkdate is kept here to:
  985. // - use the same permalink for notes as they're displayed when creating them
  986. // - let users hack creation date of their posts
  987. // See: https://shaarli.readthedocs.io/en/master/Various-hacks/#changing-the-timestamp-for-a-shaare
  988. $linkdate = escape($_POST['lf_linkdate']);
  989. if (isset($LINKSDB[$id])) {
  990. // Edit
  991. $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
  992. $updated = new DateTime();
  993. $shortUrl = $LINKSDB[$id]['shorturl'];
  994. $new = false;
  995. } else {
  996. // New link
  997. $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
  998. $updated = null;
  999. $shortUrl = link_small_hash($created, $id);
  1000. $new = true;
  1001. }
  1002. // Remove multiple spaces.
  1003. $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
  1004. // Remove first '-' char in tags.
  1005. $tags = preg_replace('/(^| )\-/', '$1', $tags);
  1006. // Remove duplicates.
  1007. $tags = implode(' ', array_unique(explode(' ', $tags)));
  1008. if (empty(trim($_POST['lf_url']))) {
  1009. $_POST['lf_url'] = '?' . smallHash($linkdate . $id);
  1010. }
  1011. $url = whitelist_protocols(trim($_POST['lf_url']), $conf->get('security.allowed_protocols'));
  1012. $link = array(
  1013. 'id' => $id,
  1014. 'title' => trim($_POST['lf_title']),
  1015. 'url' => $url,
  1016. 'description' => $_POST['lf_description'],
  1017. 'private' => (isset($_POST['lf_private']) ? 1 : 0),
  1018. 'created' => $created,
  1019. 'updated' => $updated,
  1020. 'tags' => str_replace(',', ' ', $tags),
  1021. 'shorturl' => $shortUrl,
  1022. );
  1023. // If title is empty, use the URL as title.
  1024. if ($link['title'] == '') {
  1025. $link['title'] = $link['url'];
  1026. }
  1027. if ($conf->get('thumbnails.enabled')) {
  1028. $thumbnailer = new Thumbnailer($conf);
  1029. $link['thumbnail'] = $thumbnailer->get($url);
  1030. }
  1031. $pluginManager->executeHooks('save_link', $link);
  1032. $LINKSDB[$id] = $link;
  1033. $LINKSDB->save($conf->get('resource.page_cache'));
  1034. if ($new) {
  1035. $history->addLink($link);
  1036. } else {
  1037. $history->updateLink($link);
  1038. }
  1039. // If we are called from the bookmarklet, we must close the popup:
  1040. if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
  1041. echo '<script>self.close();</script>';
  1042. exit;
  1043. }
  1044. $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?';
  1045. $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
  1046. // Scroll to the link which has been edited.
  1047. $location .= '#' . $link['shorturl'];
  1048. // After saving the link, redirect to the page the user was on.
  1049. header('Location: '. $location);
  1050. exit;
  1051. }
  1052. // -------- User clicked the "Cancel" button when editing a link.
  1053. if (isset($_POST['cancel_edit']))
  1054. {
  1055. $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
  1056. if (! isset($LINKSDB[$id])) {
  1057. header('Location: ?');
  1058. }
  1059. // If we are called from the bookmarklet, we must close the popup:
  1060. if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
  1061. $link = $LINKSDB[$id];
  1062. $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
  1063. // Scroll to the link which has been edited.
  1064. $returnurl .= '#'. $link['shorturl'];
  1065. $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
  1066. header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
  1067. exit;
  1068. }
  1069. // -------- User clicked the "Delete" button when editing a link: Delete link from database.
  1070. if ($targetPage == Router::$PAGE_DELETELINK)
  1071. {
  1072. if (! $sessionManager->checkToken($_GET['token'])) {
  1073. die(t('Wrong token.'));
  1074. }
  1075. $ids = trim($_GET['lf_linkdate']);
  1076. if (strpos($ids, ' ') !== false) {
  1077. // multiple, space-separated ids provided
  1078. $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
  1079. } else {
  1080. // only a single id provided
  1081. $ids = [$ids];
  1082. }
  1083. // assert at least one id is given
  1084. if(!count($ids)){
  1085. die('no id provided');
  1086. }
  1087. foreach ($ids as $id) {
  1088. $id = (int) escape($id);
  1089. $link = $LINKSDB[$id];
  1090. $pluginManager->executeHooks('delete_link', $link);
  1091. unset($LINKSDB[$id]);
  1092. }
  1093. $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
  1094. $history->deleteLink($link);
  1095. // If we are called from the bookmarklet, we must close the popup:
  1096. if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
  1097. $location = '?';
  1098. if (isset($_SERVER['HTTP_REFERER'])) {
  1099. // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
  1100. $location = generateLocation(
  1101. $_SERVER['HTTP_REFERER'],
  1102. $_SERVER['HTTP_HOST'],
  1103. ['delete_link', 'edit_link', $link['shorturl']]
  1104. );
  1105. }
  1106. header('Location: ' . $location); // After deleting the link, redirect to appropriate location
  1107. exit;
  1108. }
  1109. // -------- User clicked the "EDIT" button on a link: Display link edit form.
  1110. if (isset($_GET['edit_link']))
  1111. {
  1112. $id = (int) escape($_GET['edit_link']);
  1113. $link = $LINKSDB[$id]; // Read database
  1114. if (!$link) { header('Location: ?'); exit; } // Link not found in database.
  1115. $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
  1116. $data = array(
  1117. 'link' => $link,
  1118. 'link_is_new' => false,
  1119. 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
  1120. 'tags' => $LINKSDB->linksCountPerTag(),
  1121. );
  1122. $pluginManager->executeHooks('render_editlink', $data);
  1123. foreach ($data as $key => $value) {
  1124. $PAGE->assign($key, $value);
  1125. }
  1126. $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
  1127. $PAGE->renderPage('editlink');
  1128. exit;
  1129. }
  1130. // -------- User want to post a new link: Display link edit form.
  1131. if (isset($_GET['post'])) {
  1132. $url = cleanup_url($_GET['post']);
  1133. $link_is_new = false;
  1134. // Check if URL is not already in database (in this case, we will edit the existing link)
  1135. $link = $LINKSDB->getLinkFromUrl($url);
  1136. if (! $link)
  1137. {
  1138. $link_is_new = true;
  1139. $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT));
  1140. // Get title if it was provided in URL (by the bookmarklet).
  1141. $title = empty($_GET['title']) ? '' : escape($_GET['title']);
  1142. // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
  1143. $description = empty($_GET['description']) ? '' : escape($_GET['description']);
  1144. $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
  1145. $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
  1146. // If this is an HTTP(S) link, we try go get the page to extract the title (otherwise we will to straight to the edit form.)
  1147. if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
  1148. // Short timeout to keep the application responsive
  1149. // The callback will fill $charset and $title with data from the downloaded page.
  1150. get_http_response(
  1151. $url,
  1152. $conf->get('general.download_timeout', 30),
  1153. $conf->get('general.download_max_size', 4194304),
  1154. get_curl_download_callback($charset, $title)
  1155. );
  1156. if (! empty($title) && strtolower($charset) != 'utf-8') {
  1157. $title = mb_convert_encoding($title, 'utf-8', $charset);
  1158. }
  1159. }
  1160. if ($url == '') {
  1161. $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
  1162. $title = $conf->get('general.default_note_title', t('Note: '));
  1163. }
  1164. $url = escape($url);
  1165. $title = escape($title);
  1166. $link = array(
  1167. 'linkdate' => $linkdate,
  1168. 'title' => $title,
  1169. 'url' => $url,
  1170. 'description' => $description,
  1171. 'tags' => $tags,
  1172. 'private' => $private,
  1173. );
  1174. } else {
  1175. $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
  1176. }
  1177. $data = array(
  1178. 'link' => $link,
  1179. 'link_is_new' => $link_is_new,
  1180. 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
  1181. 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
  1182. 'tags' => $LINKSDB->linksCountPerTag(),
  1183. 'default_private_links' => $conf->get('privacy.default_private_links', false),
  1184. );
  1185. $pluginManager->executeHooks('render_editlink', $data);
  1186. foreach ($data as $key => $value) {
  1187. $PAGE->assign($key, $value);
  1188. }
  1189. $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
  1190. $PAGE->renderPage('editlink');
  1191. exit;
  1192. }
  1193. if ($targetPage == Router::$PAGE_EXPORT) {
  1194. // Export links as a Netscape Bookmarks file
  1195. if (empty($_GET['selection'])) {
  1196. $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
  1197. $PAGE->renderPage('export');
  1198. exit;
  1199. }
  1200. // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
  1201. $selection = $_GET['selection'];
  1202. if (isset($_GET['prepend_note_url'])) {
  1203. $prependNoteUrl = $_GET['prepend_note_url'];
  1204. } else {
  1205. $prependNoteUrl = false;
  1206. }
  1207. try {
  1208. $PAGE->assign(
  1209. 'links',
  1210. NetscapeBookmarkUtils::filterAndFormat(
  1211. $LINKSDB,
  1212. $selection,
  1213. $prependNoteUrl,
  1214. index_url($_SERVER)
  1215. )
  1216. );
  1217. } catch (Exception $exc) {
  1218. header('Content-Type: text/plain; charset=utf-8');
  1219. echo $exc->getMessage();
  1220. exit;
  1221. }
  1222. $now = new DateTime();
  1223. header('Content-Type: text/html; charset=utf-8');
  1224. header(
  1225. 'Content-disposition: attachment; filename=bookmarks_'
  1226. .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html'
  1227. );
  1228. $PAGE->assign('date', $now->format(DateTime::RFC822));
  1229. $PAGE->assign('eol', PHP_EOL);
  1230. $PAGE->assign('selection', $selection);
  1231. $PAGE->renderPage('export.bookmarks');
  1232. exit;
  1233. }
  1234. if ($targetPage == Router::$PAGE_IMPORT) {
  1235. // Upload a Netscape bookmark dump to import its contents
  1236. if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
  1237. // Show import dialog
  1238. $PAGE->assign(
  1239. 'maxfilesize',
  1240. get_max_upload_size(
  1241. ini_get('post_max_size'),
  1242. ini_get('upload_max_filesize'),
  1243. false
  1244. )
  1245. );
  1246. $PAGE->assign(
  1247. 'maxfilesizeHuman',
  1248. get_max_upload_size(
  1249. ini_get('post_max_size'),
  1250. ini_get('upload_max_filesize'),
  1251. true
  1252. )
  1253. );
  1254. $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
  1255. $PAGE->renderPage('import');
  1256. exit;
  1257. }
  1258. // Import bookmarks from an uploaded file
  1259. if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
  1260. // The file is too big or some form field may be missing.
  1261. $msg = sprintf(
  1262. t(
  1263. 'The file you are trying to upload is probably bigger than what this webserver can accept'
  1264. .' (%s). Please upload in smaller chunks.'
  1265. ),
  1266. get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
  1267. );
  1268. echo '<script>alert("'. $msg .'");document.location=\'?do='.Router::$PAGE_IMPORT .'\';</script>';
  1269. exit;
  1270. }
  1271. if (! $sessionManager->checkToken($_POST['token'])) {
  1272. die('Wrong token.');
  1273. }
  1274. $status = NetscapeBookmarkUtils::import(
  1275. $_POST,
  1276. $_FILES,
  1277. $LINKSDB,
  1278. $conf,
  1279. $history
  1280. );
  1281. echo '<script>alert("'.$status.'");document.location=\'?do='
  1282. .Router::$PAGE_IMPORT .'\';</script>';
  1283. exit;
  1284. }
  1285. // Plugin administration page
  1286. if ($targetPage == Router::$PAGE_PLUGINSADMIN) {
  1287. $pluginMeta = $pluginManager->getPluginsMeta();
  1288. // Split plugins into 2 arrays: ordered enabled plugins and disabled.
  1289. $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; });
  1290. // Load parameters.
  1291. $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
  1292. uasort(
  1293. $enabledPlugins,
  1294. function($a, $b) { return $a['order'] - $b['order']; }
  1295. );
  1296. $disabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] === false; });
  1297. $PAGE->assign('enabledPlugins', $enabledPlugins);
  1298. $PAGE->assign('disabledPlugins', $disabledPlugins);
  1299. $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
  1300. $PAGE->renderPage('pluginsadmin');
  1301. exit;
  1302. }
  1303. // Plugin administration form action
  1304. if ($targetPage == Router::$PAGE_SAVE_PLUGINSADMIN) {
  1305. try {
  1306. if (isset($_POST['parameters_form'])) {
  1307. unset($_POST['parameters_form']);
  1308. foreach ($_POST as $param => $value) {
  1309. $conf->set('plugins.'. $param, escape($value));
  1310. }
  1311. }
  1312. else {
  1313. $conf->set('general.enabled_plugins', save_plugin_config($_POST));
  1314. }
  1315. $conf->write($loginManager->isLoggedIn());
  1316. $history->updateSettings();
  1317. }
  1318. catch (Exception $e) {
  1319. error_log(
  1320. 'ERROR while saving plugin configuration:.' . PHP_EOL .
  1321. $e->getMessage()
  1322. );
  1323. // TODO: do not handle exceptions/errors in JS.
  1324. echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router::$PAGE_PLUGINSADMIN .'\';</script>';
  1325. exit;
  1326. }
  1327. header('Location: ?do='. Router::$PAGE_PLUGINSADMIN);
  1328. exit;
  1329. }
  1330. // Get a fresh token
  1331. if ($targetPage == Router::$GET_TOKEN) {
  1332. header('Content-Type:text/plain');
  1333. echo $sessionManager->generateToken($conf);
  1334. exit;
  1335. }
  1336. // -------- Thumbnails Update
  1337. if ($targetPage == Router::$PAGE_THUMBS_UPDATE) {
  1338. $ids = [];
  1339. foreach ($LINKSDB as $link) {
  1340. // A note or not HTTP(S)
  1341. if ($link['url'][0] === '?' || ! startsWith(strtolower($link['url']), 'http')) {
  1342. continue;
  1343. }
  1344. $ids[] = $link['id'];
  1345. }
  1346. $PAGE->assign('ids', $ids);
  1347. $PAGE->assign('pagetitle', t('Thumbnail update') .' - '. $conf->get('general.title', 'Shaarli'));
  1348. $PAGE->renderPage('thumbnails');
  1349. exit;
  1350. }
  1351. // -------- Single Thumbnail Update
  1352. if ($targetPage == Router::$AJAX_THUMB_UPDATE) {
  1353. if (! isset($_POST['id']) || ! ctype_digit($_POST['id'])) {
  1354. http_response_code(400);
  1355. exit;
  1356. }
  1357. $id = (int) $_POST['id'];
  1358. if (empty($LINKSDB[$id])) {
  1359. http_response_code(404);
  1360. exit;
  1361. }
  1362. $thumbnailer = new Thumbnailer($conf);
  1363. $link = $LINKSDB[$id];
  1364. $link['thumbnail'] = $thumbnailer->get($link['url']);
  1365. $LINKSDB[$id] = $link;
  1366. $LINKSDB->save($conf->get('resource.page_cache'));
  1367. echo json_encode($link);
  1368. exit;
  1369. }
  1370. // -------- Otherwise, simply display search form and links:
  1371. showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
  1372. exit;
  1373. }
  1374. /**
  1375. * Template for the list of links (<div id="linklist">)
  1376. * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
  1377. *
  1378. * @param pageBuilder $PAGE pageBuilder instance.
  1379. * @param LinkDB $LINKSDB LinkDB instance.
  1380. * @param ConfigManager $conf Configuration Manager instance.
  1381. * @param PluginManager $pluginManager Plugin Manager instance.
  1382. * @param LoginManager $loginManager LoginManager instance
  1383. */
  1384. function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
  1385. {
  1386. // Used in templates
  1387. if (isset($_GET['searchtags'])) {
  1388. if (! empty($_GET['searchtags'])) {
  1389. $searchtags = escape(normalize_spaces($_GET['searchtags']));
  1390. } else {
  1391. $searchtags = false;
  1392. }
  1393. } else {
  1394. $searchtags = '';
  1395. }
  1396. $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
  1397. // Smallhash filter
  1398. if (! empty($_SERVER['QUERY_STRING'])
  1399. && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
  1400. try {
  1401. $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
  1402. } catch (LinkNotFoundException $e) {
  1403. $PAGE->render404($e->getMessage());
  1404. exit;
  1405. }
  1406. } else {
  1407. // Filter links according search parameters.
  1408. $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
  1409. $request = [
  1410. 'searchtags' => $searchtags,
  1411. 'searchterm' => $searchterm,
  1412. ];
  1413. $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
  1414. }
  1415. // ---- Handle paging.
  1416. $keys = array();
  1417. foreach ($linksToDisplay as $key => $value) {
  1418. $keys[] = $key;
  1419. }
  1420. // Select articles according to paging.
  1421. $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
  1422. $pagecount = $pagecount == 0 ? 1 : $pagecount;
  1423. $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
  1424. $page = $page < 1 ? 1 : $page;
  1425. $page = $page > $pagecount ? $pagecount : $page;
  1426. // Start index.
  1427. $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
  1428. $end = $i + $_SESSION['LINKS_PER_PAGE'];
  1429. if ($conf->get('thumbnails.enabled')) {
  1430. $thumbnailer = new Thumbnailer($conf);
  1431. }
  1432. $linkDisp = array();
  1433. while ($i<$end && $i<count($keys))
  1434. {
  1435. $link = $linksToDisplay[$keys[$i]];
  1436. $link['description'] = format_description(
  1437. $link['description'],
  1438. $conf->get('redirector.url'),
  1439. $conf->get('redirector.encode_url')
  1440. );
  1441. $classLi = ($i % 2) != 0 ? '' : 'publicLinkHightLight';
  1442. $link['class'] = $link['private'] == 0 ? $classLi : 'private';
  1443. $link['timestamp'] = $link['created']->getTimestamp();
  1444. if (! empty($link['updated'])) {
  1445. $link['updated_timestamp'] = $link['updated']->getTimestamp();
  1446. } else {
  1447. $link['updated_timestamp'] = '';
  1448. }
  1449. $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY);
  1450. uasort($taglist, 'strcasecmp');
  1451. $link['taglist'] = $taglist;
  1452. // Thumbnails enabled, not a note,
  1453. // and (never retrieved yet or no valid cache file)
  1454. if ($conf->get('thumbnails.enabled') && $link['url'][0] != '?'
  1455. && (! isset($link['thumbnail']) || ($link['thumbnail'] !== false && ! is_file($link['thumbnail'])))
  1456. ) {
  1457. $elem = $LINKSDB[$keys[$i]];
  1458. $elem['thumbnail'] = $thumbnailer->get($link['url']);
  1459. $LINKSDB[$keys[$i]] = $elem;
  1460. $updateDB = true;
  1461. $link['thumbnail'] = $elem['thumbnail'];
  1462. }
  1463. // Check for both signs of a note: starting with ? and 7 chars long.
  1464. if ($link['url'][0] === '?' && strlen($link['url']) === 7) {
  1465. $link['url'] = index_url($_SERVER) . $link['url'];
  1466. }
  1467. $linkDisp[$keys[$i]] = $link;
  1468. $i++;
  1469. }
  1470. // If we retrieved new thumbnails, we update the database.
  1471. if (!empty($updateDB)) {
  1472. $LINKSDB->save($conf->get('resource.page_cache'));
  1473. }
  1474. // Compute paging navigation
  1475. $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
  1476. $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
  1477. $previous_page_url = '';
  1478. if ($i != count($keys)) {
  1479. $previous_page_url = '?page=' . ($page+1) . $searchtermUrl . $searchtagsUrl;
  1480. }
  1481. $next_page_url='';
  1482. if ($page>1) {
  1483. $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
  1484. }
  1485. // Fill all template fields.
  1486. $data = array(
  1487. 'previous_page_url' => $previous_page_url,
  1488. 'next_page_url' => $next_page_url,
  1489. 'page_current' => $page,
  1490. 'page_max' => $pagecount,
  1491. 'result_count' => count($linksToDisplay),
  1492. 'search_term' => $searchterm,
  1493. 'search_tags' => $searchtags,
  1494. 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
  1495. 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
  1496. 'links' => $linkDisp,
  1497. );
  1498. // If there is only a single link, we change on-the-fly the title of the page.
  1499. if (count($linksToDisplay) == 1) {
  1500. $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
  1501. } elseif (! empty($searchterm) || ! empty($searchtags)) {
  1502. $data['pagetitle'] = t('Search: ');
  1503. $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
  1504. $bracketWrap = function ($tag) {
  1505. return '['. $tag .']';
  1506. };
  1507. $data['pagetitle'] .= ! empty($searchtags)
  1508. ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
  1509. : '';
  1510. $data['pagetitle'] .= '- '. $conf->get('general.title');
  1511. }
  1512. $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
  1513. foreach ($data as $key => $value) {
  1514. $PAGE->assign($key, $value);
  1515. }
  1516. return;
  1517. }
  1518. /**
  1519. * Installation
  1520. * This function should NEVER be called if the file data/config.php exists.
  1521. *
  1522. * @param ConfigManager $conf Configuration Manager instance.
  1523. * @param SessionManager $sessionManager SessionManager instance
  1524. * @param LoginManager $loginManager LoginManager instance
  1525. */
  1526. function install($conf, $sessionManager, $loginManager) {
  1527. // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
  1528. if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
  1529. // This part makes sure sessions works correctly.
  1530. // (Because on some hosts, session.save_path may not be set correctly,
  1531. // or we may not have write access to it.)
  1532. if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working'))
  1533. {
  1534. // Step 2: Check if data in session is correct.
  1535. $msg = t(
  1536. '<pre>Sessions do not seem to work correctly on your server.<br>'.
  1537. 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
  1538. 'and that you have write access to it.<br>'.
  1539. 'It currently points to %s.<br>'.
  1540. 'On some browsers, accessing your server via a hostname like \'localhost\' '.
  1541. 'or any custom hostname without a dot causes cookie storage to fail. '.
  1542. 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
  1543. );
  1544. $msg = sprintf($msg, session_save_path());
  1545. echo $msg;
  1546. echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
  1547. die;
  1548. }
  1549. if (!isset($_SESSION['session_tested']))
  1550. { // Step 1 : Try to store data in session and reload page.
  1551. $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
  1552. header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
  1553. }
  1554. if (isset($_GET['test_session']))
  1555. { // Step 3: Sessions are OK. Remove test parameter from URL.
  1556. header('Location: '.index_url($_SERVER));
  1557. }
  1558. if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
  1559. {
  1560. $tz = 'UTC';
  1561. if (!empty($_POST['continent']) && !empty($_POST['city'])
  1562. && isTimeZoneValid($_POST['continent'], $_POST['city'])
  1563. ) {
  1564. $tz = $_POST['continent'].'/'.$_POST['city'];
  1565. }
  1566. $conf->set('general.timezone', $tz);
  1567. $login = $_POST['setlogin'];
  1568. $conf->set('credentials.login', $login);
  1569. $salt = sha1(uniqid('', true) .'_'. mt_rand());
  1570. $conf->set('credentials.salt', $salt);
  1571. $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
  1572. if (!empty($_POST['title'])) {
  1573. $conf->set('general.title', escape($_POST['title']));
  1574. } else {
  1575. $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
  1576. }
  1577. $conf->set('translation.language', escape($_POST['language']));
  1578. $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
  1579. $conf->set('api.enabled', !empty($_POST['enableApi']));
  1580. $conf->set(
  1581. 'api.secret',
  1582. generate_api_secret(
  1583. $conf->get('credentials.login'),
  1584. $conf->get('credentials.salt')
  1585. )
  1586. );
  1587. try {
  1588. // Everything is ok, let's create config file.
  1589. $conf->write($loginManager->isLoggedIn());
  1590. }
  1591. catch(Exception $e) {
  1592. error_log(
  1593. 'ERROR while writing config file after installation.' . PHP_EOL .
  1594. $e->getMessage()
  1595. );
  1596. // TODO: do not handle exceptions/errors in JS.
  1597. echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
  1598. exit;
  1599. }
  1600. echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
  1601. exit;
  1602. }
  1603. $PAGE = new PageBuilder($conf, $_SESSION, null, $sessionManager->generateToken());
  1604. list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
  1605. $PAGE->assign('continents', $continents);
  1606. $PAGE->assign('cities', $cities);
  1607. $PAGE->assign('languages', Languages::getAvailableLanguages());
  1608. $PAGE->renderPage('install');
  1609. exit;
  1610. }
  1611. if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf); exit; }
  1612. if (!isset($_SESSION['LINKS_PER_PAGE'])) {
  1613. $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
  1614. }
  1615. try {
  1616. $history = new History($conf->get('resource.history'));
  1617. } catch(Exception $e) {
  1618. die($e->getMessage());
  1619. }
  1620. $linkDb = new LinkDB(
  1621. $conf->get('resource.datastore'),
  1622. $loginManager->isLoggedIn(),
  1623. $conf->get('privacy.hide_public_links'),
  1624. $conf->get('redirector.url'),
  1625. $conf->get('redirector.encode_url')
  1626. );
  1627. $container = new \Slim\Container();
  1628. $container['conf'] = $conf;
  1629. $container['plugins'] = $pluginManager;
  1630. $container['history'] = $history;
  1631. $app = new \Slim\App($container);
  1632. // REST API routes
  1633. $app->group('/api/v1', function() {
  1634. $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
  1635. $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
  1636. $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
  1637. $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
  1638. $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
  1639. $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
  1640. $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
  1641. })->add('\Shaarli\Api\ApiMiddleware');
  1642. $response = $app->run(true);
  1643. // Hack to make Slim and Shaarli router work together:
  1644. // If a Slim route isn't found and NOT API call, we call renderPage().
  1645. if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
  1646. // We use UTF-8 for proper international characters handling.
  1647. header('Content-Type: text/html; charset=utf-8');
  1648. renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
  1649. } else {
  1650. $app->respond($response);
  1651. }