index.php 76 KB

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