index.php 76 KB

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