index.php 89 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197
  1. <?php
  2. /**
  3. * Shaarli - The personal, minimalist, super-fast, database free, bookmarking service.
  4. *
  5. * Friendly fork by the Shaarli community:
  6. * - https://github.com/shaarli/Shaarli
  7. *
  8. * Original project by sebsauvage.net:
  9. * - http://sebsauvage.net/wiki/doku.php?id=php:shaarli
  10. * - https://github.com/sebsauvage/Shaarli
  11. *
  12. * Licence: http://www.opensource.org/licenses/zlib-license.php
  13. *
  14. * Requires: PHP 5.5.x
  15. */
  16. // Set 'UTC' as the default timezone if it is not defined in php.ini
  17. // See http://php.net/manual/en/datetime.configuration.php#ini.date.timezone
  18. if (date_default_timezone_get() == '') {
  19. date_default_timezone_set('UTC');
  20. }
  21. /*
  22. * PHP configuration
  23. */
  24. // http://server.com/x/shaarli --> /shaarli/
  25. define('WEB_PATH', substr($_SERVER['REQUEST_URI'], 0, 1+strrpos($_SERVER['REQUEST_URI'], '/', 0)));
  26. // High execution time in case of problematic imports/exports.
  27. ini_set('max_input_time','60');
  28. // Try to set max upload file size and read
  29. ini_set('memory_limit', '128M');
  30. ini_set('post_max_size', '16M');
  31. ini_set('upload_max_filesize', '16M');
  32. // See all error except warnings
  33. error_reporting(E_ALL^E_WARNING);
  34. // See all errors (for debugging only)
  35. //error_reporting(-1);
  36. // 3rd-party libraries
  37. if (! file_exists(__DIR__ . '/vendor/autoload.php')) {
  38. header('Content-Type: text/plain; charset=utf-8');
  39. echo "Error: missing Composer configuration\n\n"
  40. ."If you installed Shaarli through Git or using the development branch,\n"
  41. ."please refer to the installation documentation to install PHP"
  42. ." dependencies using Composer:\n"
  43. ."- https://shaarli.readthedocs.io/en/master/Server-configuration/\n"
  44. ."- https://shaarli.readthedocs.io/en/master/Download-and-Installation/";
  45. exit;
  46. }
  47. require_once 'inc/rain.tpl.class.php';
  48. require_once __DIR__ . '/vendor/autoload.php';
  49. // Shaarli library
  50. require_once 'application/ApplicationUtils.php';
  51. require_once 'application/Cache.php';
  52. require_once 'application/CachedPage.php';
  53. require_once 'application/config/ConfigPlugin.php';
  54. require_once 'application/FeedBuilder.php';
  55. require_once 'application/FileUtils.php';
  56. require_once 'application/History.php';
  57. require_once 'application/HttpUtils.php';
  58. require_once 'application/LinkDB.php';
  59. require_once 'application/LinkFilter.php';
  60. require_once 'application/LinkUtils.php';
  61. require_once 'application/NetscapeBookmarkUtils.php';
  62. require_once 'application/PageBuilder.php';
  63. require_once 'application/TimeZone.php';
  64. require_once 'application/Url.php';
  65. require_once 'application/Utils.php';
  66. require_once 'application/PluginManager.php';
  67. require_once 'application/Router.php';
  68. require_once 'application/Updater.php';
  69. use \Shaarli\Languages;
  70. use \Shaarli\ThemeUtils;
  71. use \Shaarli\Config\ConfigManager;
  72. use \Shaarli\Security\LoginManager;
  73. use \Shaarli\Security\SessionManager;
  74. // Ensure the PHP version is supported
  75. try {
  76. ApplicationUtils::checkPHPVersion('5.5', 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_id() == '') {
  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($GLOBALS, $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: ?'); exit;
  220. } else {
  221. $loginManager->handleFailedLogin($_SERVER);
  222. $redir = '&username='. urlencode($_POST['login']);
  223. if (isset($_GET['post'])) {
  224. $redir .= '&post=' . urlencode($_GET['post']);
  225. foreach (array('description', 'source', 'title', 'tags') as $param) {
  226. if (!empty($_GET[$param])) {
  227. $redir .= '&' . $param . '=' . urlencode($_GET[$param]);
  228. }
  229. }
  230. }
  231. // Redirect to login screen.
  232. echo '<script>alert("'. t("Wrong login/password.") .'");document.location=\'?do=login'.$redir.'\';</script>';
  233. exit;
  234. }
  235. }
  236. // ------------------------------------------------------------------------------------------
  237. // Token management for XSRF protection
  238. // Token should be used in any form which acts on data (create,update,delete,import...).
  239. if (!isset($_SESSION['tokens'])) $_SESSION['tokens']=array(); // Token are attached to the session.
  240. /**
  241. * Daily RSS feed: 1 RSS entry per day giving all the links on that day.
  242. * Gives the last 7 days (which have links).
  243. * This RSS feed cannot be filtered.
  244. *
  245. * @param ConfigManager $conf Configuration Manager instance
  246. * @param LoginManager $loginManager LoginManager instance
  247. */
  248. function showDailyRSS($conf, $loginManager) {
  249. // Cache system
  250. $query = $_SERVER['QUERY_STRING'];
  251. $cache = new CachedPage(
  252. $conf->get('config.PAGE_CACHE'),
  253. page_url($_SERVER),
  254. startsWith($query,'do=dailyrss') && !$loginManager->isLoggedIn()
  255. );
  256. $cached = $cache->cachedVersion();
  257. if (!empty($cached)) {
  258. echo $cached;
  259. exit;
  260. }
  261. // If cached was not found (or not usable), then read the database and build the response:
  262. // Read links from database (and filter private links if used it not logged in).
  263. $LINKSDB = new LinkDB(
  264. $conf->get('resource.datastore'),
  265. $loginManager->isLoggedIn(),
  266. $conf->get('privacy.hide_public_links'),
  267. $conf->get('redirector.url'),
  268. $conf->get('redirector.encode_url')
  269. );
  270. /* Some Shaarlies may have very few links, so we need to look
  271. back in time until we have enough days ($nb_of_days).
  272. */
  273. $nb_of_days = 7; // We take 7 days.
  274. $today = date('Ymd');
  275. $days = array();
  276. foreach ($LINKSDB as $link) {
  277. $day = $link['created']->format('Ymd'); // Extract day (without time)
  278. if (strcmp($day, $today) < 0) {
  279. if (empty($days[$day])) {
  280. $days[$day] = array();
  281. }
  282. $days[$day][] = $link;
  283. }
  284. if (count($days) > $nb_of_days) {
  285. break; // Have we collected enough days?
  286. }
  287. }
  288. // Build the RSS feed.
  289. header('Content-Type: application/rss+xml; charset=utf-8');
  290. $pageaddr = escape(index_url($_SERVER));
  291. echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0">';
  292. echo '<channel>';
  293. echo '<title>Daily - '. $conf->get('general.title') . '</title>';
  294. echo '<link>'. $pageaddr .'</link>';
  295. echo '<description>Daily shared links</description>';
  296. echo '<language>en-en</language>';
  297. echo '<copyright>'. $pageaddr .'</copyright>'. PHP_EOL;
  298. // For each day.
  299. foreach ($days as $day => $links) {
  300. $dayDate = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $day.'_000000');
  301. $absurl = escape(index_url($_SERVER).'?do=daily&day='.$day); // Absolute URL of the corresponding "Daily" page.
  302. // We pre-format some fields for proper output.
  303. foreach ($links as &$link) {
  304. $link['formatedDescription'] = format_description(
  305. $link['description'],
  306. $conf->get('redirector.url'),
  307. $conf->get('redirector.encode_url')
  308. );
  309. $link['thumbnail'] = thumbnail($conf, $link['url']);
  310. $link['timestamp'] = $link['created']->getTimestamp();
  311. if (startsWith($link['url'], '?')) {
  312. $link['url'] = index_url($_SERVER) . $link['url']; // make permalink URL absolute
  313. }
  314. }
  315. // Then build the HTML for this day:
  316. $tpl = new RainTPL;
  317. $tpl->assign('title', $conf->get('general.title'));
  318. $tpl->assign('daydate', $dayDate->getTimestamp());
  319. $tpl->assign('absurl', $absurl);
  320. $tpl->assign('links', $links);
  321. $tpl->assign('rssdate', escape($dayDate->format(DateTime::RSS)));
  322. $tpl->assign('hide_timestamps', $conf->get('privacy.hide_timestamps', false));
  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. $day = date('Ymd', strtotime('-1 day')); // Yesterday, in format YYYYMMDD.
  343. if (isset($_GET['day'])) {
  344. $day = $_GET['day'];
  345. }
  346. $days = $LINKSDB->days();
  347. $i = array_search($day, $days);
  348. if ($i === false && count($days)) {
  349. // no links for day, but at least one day with links
  350. $i = count($days) - 1;
  351. $day = $days[$i];
  352. }
  353. $previousday = '';
  354. $nextday = '';
  355. if ($i !== false) {
  356. if ($i >= 1) {
  357. $previousday=$days[$i - 1];
  358. }
  359. if ($i < count($days) - 1) {
  360. $nextday = $days[$i + 1];
  361. }
  362. }
  363. try {
  364. $linksToDisplay = $LINKSDB->filterDay($day);
  365. } catch (Exception $exc) {
  366. error_log($exc);
  367. $linksToDisplay = array();
  368. }
  369. // We pre-format some fields for proper output.
  370. foreach($linksToDisplay as $key => $link) {
  371. $taglist = explode(' ',$link['tags']);
  372. uasort($taglist, 'strcasecmp');
  373. $linksToDisplay[$key]['taglist']=$taglist;
  374. $linksToDisplay[$key]['formatedDescription'] = format_description(
  375. $link['description'],
  376. $conf->get('redirector.url'),
  377. $conf->get('redirector.encode_url')
  378. );
  379. $linksToDisplay[$key]['thumbnail'] = thumbnail($conf, $link['url']);
  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 ($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. buildLinkList($PAGE,$LINKSDB, $conf, $pluginManager, $loginManager);
  434. $PAGE->renderPage('linklist');
  435. }
  436. /**
  437. * Render HTML page (according to URL parameters and user rights)
  438. *
  439. * @param ConfigManager $conf Configuration Manager instance.
  440. * @param PluginManager $pluginManager Plugin Manager instance,
  441. * @param LinkDB $LINKSDB
  442. * @param History $history instance
  443. * @param SessionManager $sessionManager SessionManager instance
  444. * @param LoginManager $loginManager LoginManager instance
  445. */
  446. function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager, $loginManager)
  447. {
  448. $updater = new Updater(
  449. read_updates_file($conf->get('resource.updates')),
  450. $LINKSDB,
  451. $conf,
  452. $loginManager->isLoggedIn()
  453. );
  454. try {
  455. $newUpdates = $updater->update();
  456. if (! empty($newUpdates)) {
  457. write_updates_file(
  458. $conf->get('resource.updates'),
  459. $updater->getDoneUpdates()
  460. );
  461. }
  462. }
  463. catch(Exception $e) {
  464. die($e->getMessage());
  465. }
  466. $PAGE = new PageBuilder($conf, $LINKSDB, $sessionManager->generateToken(), $loginManager->isLoggedIn());
  467. $PAGE->assign('linkcount', count($LINKSDB));
  468. $PAGE->assign('privateLinkcount', count_private($LINKSDB));
  469. $PAGE->assign('plugin_errors', $pluginManager->getErrors());
  470. // Determine which page will be rendered.
  471. $query = (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : '';
  472. $targetPage = Router::findPage($query, $_GET, $loginManager->isLoggedIn());
  473. if (
  474. // 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('render_' . $name, $plugin_data,
  499. array(
  500. 'target' => $targetPage,
  501. 'loggedin' => $loginManager->isLoggedIn()
  502. )
  503. );
  504. $PAGE->assign('plugins_' . $name, $plugin_data);
  505. }
  506. // -------- Display login form.
  507. if ($targetPage == Router::$PAGE_LOGIN)
  508. {
  509. if ($conf->get('security.open_shaarli')) { header('Location: ?'); exit; } // No need to login for open Shaarli
  510. if (isset($_GET['username'])) {
  511. $PAGE->assign('username', escape($_GET['username']));
  512. }
  513. $PAGE->assign('returnurl',(isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']):''));
  514. // add default state of the 'remember me' checkbox
  515. $PAGE->assign('remember_user_default', $conf->get('privacy.remember_user_default'));
  516. $PAGE->assign('user_can_login', $loginManager->canLogin($_SERVER));
  517. $PAGE->assign('pagetitle', t('Login') .' - '. $conf->get('general.title', 'Shaarli'));
  518. $PAGE->renderPage('loginform');
  519. exit;
  520. }
  521. // -------- User wants to logout.
  522. if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
  523. {
  524. invalidateCaches($conf->get('resource.page_cache'));
  525. $sessionManager->logout();
  526. setcookie(LoginManager::$STAY_SIGNED_IN_COOKIE, 'false', 0, WEB_PATH);
  527. header('Location: ?');
  528. exit;
  529. }
  530. // -------- Picture wall
  531. if ($targetPage == Router::$PAGE_PICWALL)
  532. {
  533. // Optionally filter the results:
  534. $links = $LINKSDB->filterSearch($_GET);
  535. $linksToDisplay = array();
  536. // Get only links which have a thumbnail.
  537. foreach($links as $link)
  538. {
  539. $permalink='?'.$link['shorturl'];
  540. $thumb=lazyThumbnail($conf, $link['url'],$permalink);
  541. if ($thumb!='') // Only output links which have a thumbnail.
  542. {
  543. $link['thumbnail']=$thumb; // Thumbnail HTML code.
  544. $linksToDisplay[]=$link; // Add to array.
  545. }
  546. }
  547. $data = array(
  548. 'linksToDisplay' => $linksToDisplay,
  549. );
  550. $pluginManager->executeHooks('render_picwall', $data, array('loggedin' => $loginManager->isLoggedIn()));
  551. foreach ($data as $key => $value) {
  552. $PAGE->assign($key, $value);
  553. }
  554. $PAGE->assign('pagetitle', t('Picture wall') .' - '. $conf->get('general.title', 'Shaarli'));
  555. $PAGE->renderPage('picwall');
  556. exit;
  557. }
  558. // -------- Tag cloud
  559. if ($targetPage == Router::$PAGE_TAGCLOUD)
  560. {
  561. $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
  562. $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
  563. $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
  564. // We sort tags alphabetically, then choose a font size according to count.
  565. // First, find max value.
  566. $maxcount = 0;
  567. foreach ($tags as $value) {
  568. $maxcount = max($maxcount, $value);
  569. }
  570. alphabetical_sort($tags, false, true);
  571. $tagList = array();
  572. foreach($tags as $key => $value) {
  573. if (in_array($key, $filteringTags)) {
  574. continue;
  575. }
  576. // Tag font size scaling:
  577. // default 15 and 30 logarithm bases affect scaling,
  578. // 22 and 6 are arbitrary font sizes for max and min sizes.
  579. $size = log($value, 15) / log($maxcount, 30) * 2.2 + 0.8;
  580. $tagList[$key] = array(
  581. 'count' => $value,
  582. 'size' => number_format($size, 2, '.', ''),
  583. );
  584. }
  585. $searchTags = implode(' ', escape($filteringTags));
  586. $data = array(
  587. 'search_tags' => $searchTags,
  588. 'tags' => $tagList,
  589. );
  590. $pluginManager->executeHooks('render_tagcloud', $data, array('loggedin' => $loginManager->isLoggedIn()));
  591. foreach ($data as $key => $value) {
  592. $PAGE->assign($key, $value);
  593. }
  594. $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
  595. $PAGE->assign('pagetitle', $searchTags. t('Tag cloud') .' - '. $conf->get('general.title', 'Shaarli'));
  596. $PAGE->renderPage('tag.cloud');
  597. exit;
  598. }
  599. // -------- Tag list
  600. if ($targetPage == Router::$PAGE_TAGLIST)
  601. {
  602. $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
  603. $filteringTags = isset($_GET['searchtags']) ? explode(' ', $_GET['searchtags']) : [];
  604. $tags = $LINKSDB->linksCountPerTag($filteringTags, $visibility);
  605. foreach ($filteringTags as $tag) {
  606. if (array_key_exists($tag, $tags)) {
  607. unset($tags[$tag]);
  608. }
  609. }
  610. if (! empty($_GET['sort']) && $_GET['sort'] === 'alpha') {
  611. alphabetical_sort($tags, false, true);
  612. }
  613. $searchTags = implode(' ', escape($filteringTags));
  614. $data = [
  615. 'search_tags' => $searchTags,
  616. 'tags' => $tags,
  617. ];
  618. $pluginManager->executeHooks('render_taglist', $data, ['loggedin' => $loginManager->isLoggedIn()]);
  619. foreach ($data as $key => $value) {
  620. $PAGE->assign($key, $value);
  621. }
  622. $searchTags = ! empty($searchTags) ? $searchTags .' - ' : '';
  623. $PAGE->assign('pagetitle', $searchTags . t('Tag list') .' - '. $conf->get('general.title', 'Shaarli'));
  624. $PAGE->renderPage('tag.list');
  625. exit;
  626. }
  627. // Daily page.
  628. if ($targetPage == Router::$PAGE_DAILY) {
  629. showDaily($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
  630. }
  631. // ATOM and RSS feed.
  632. if ($targetPage == Router::$PAGE_FEED_ATOM || $targetPage == Router::$PAGE_FEED_RSS) {
  633. $feedType = $targetPage == Router::$PAGE_FEED_RSS ? FeedBuilder::$FEED_RSS : FeedBuilder::$FEED_ATOM;
  634. header('Content-Type: application/'. $feedType .'+xml; charset=utf-8');
  635. // Cache system
  636. $query = $_SERVER['QUERY_STRING'];
  637. $cache = new CachedPage(
  638. $conf->get('resource.page_cache'),
  639. page_url($_SERVER),
  640. startsWith($query,'do='. $targetPage) && !$loginManager->isLoggedIn()
  641. );
  642. $cached = $cache->cachedVersion();
  643. if (!empty($cached)) {
  644. echo $cached;
  645. exit;
  646. }
  647. // Generate data.
  648. $feedGenerator = new FeedBuilder($LINKSDB, $feedType, $_SERVER, $_GET, $loginManager->isLoggedIn());
  649. $feedGenerator->setLocale(strtolower(setlocale(LC_COLLATE, 0)));
  650. $feedGenerator->setHideDates($conf->get('privacy.hide_timestamps') && !$loginManager->isLoggedIn());
  651. $feedGenerator->setUsePermalinks(isset($_GET['permalinks']) || !$conf->get('feed.rss_permalinks'));
  652. $data = $feedGenerator->buildData();
  653. // Process plugin hook.
  654. $pluginManager->executeHooks('render_feed', $data, array(
  655. 'loggedin' => $loginManager->isLoggedIn(),
  656. 'target' => $targetPage,
  657. ));
  658. // Render the template.
  659. $PAGE->assignAll($data);
  660. $PAGE->renderPage('feed.'. $feedType);
  661. $cache->cache(ob_get_contents());
  662. ob_end_flush();
  663. exit;
  664. }
  665. // Display opensearch plugin (XML)
  666. if ($targetPage == Router::$PAGE_OPENSEARCH) {
  667. header('Content-Type: application/xml; charset=utf-8');
  668. $PAGE->assign('serverurl', index_url($_SERVER));
  669. $PAGE->renderPage('opensearch');
  670. exit;
  671. }
  672. // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...)
  673. if (isset($_GET['addtag']))
  674. {
  675. // Get previous URL (http_referer) and add the tag to the searchtags parameters in query.
  676. if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER
  677. parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params);
  678. // Prevent redirection loop
  679. if (isset($params['addtag'])) {
  680. unset($params['addtag']);
  681. }
  682. // Check if this tag is already in the search query and ignore it if it is.
  683. // Each tag is always separated by a space
  684. if (isset($params['searchtags'])) {
  685. $current_tags = explode(' ', $params['searchtags']);
  686. } else {
  687. $current_tags = array();
  688. }
  689. $addtag = true;
  690. foreach ($current_tags as $value) {
  691. if ($value === $_GET['addtag']) {
  692. $addtag = false;
  693. break;
  694. }
  695. }
  696. // Append the tag if necessary
  697. if (empty($params['searchtags'])) {
  698. $params['searchtags'] = trim($_GET['addtag']);
  699. }
  700. elseif ($addtag) {
  701. $params['searchtags'] = trim($params['searchtags']).' '.trim($_GET['addtag']);
  702. }
  703. unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
  704. header('Location: ?'.http_build_query($params));
  705. exit;
  706. }
  707. // -------- User clicks on a tag in result count: Remove the tag from the list of searched tags (searchtags=...)
  708. if (isset($_GET['removetag'])) {
  709. // Get previous URL (http_referer) and remove the tag from the searchtags parameters in query.
  710. if (empty($_SERVER['HTTP_REFERER'])) {
  711. header('Location: ?');
  712. exit;
  713. }
  714. // In case browser does not send HTTP_REFERER
  715. parse_str(parse_url($_SERVER['HTTP_REFERER'], PHP_URL_QUERY), $params);
  716. // Prevent redirection loop
  717. if (isset($params['removetag'])) {
  718. unset($params['removetag']);
  719. }
  720. if (isset($params['searchtags'])) {
  721. $tags = explode(' ', $params['searchtags']);
  722. // Remove value from array $tags.
  723. $tags = array_diff($tags, array($_GET['removetag']));
  724. $params['searchtags'] = implode(' ',$tags);
  725. if (empty($params['searchtags'])) {
  726. unset($params['searchtags']);
  727. }
  728. unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different)
  729. }
  730. header('Location: ?'.http_build_query($params));
  731. exit;
  732. }
  733. // -------- User wants to change the number of links per page (linksperpage=...)
  734. if (isset($_GET['linksperpage'])) {
  735. if (is_numeric($_GET['linksperpage'])) {
  736. $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage']));
  737. }
  738. if (! empty($_SERVER['HTTP_REFERER'])) {
  739. $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('linksperpage'));
  740. } else {
  741. $location = '?';
  742. }
  743. header('Location: '. $location);
  744. exit;
  745. }
  746. // -------- User wants to see only private links (toggle)
  747. if (isset($_GET['visibility'])) {
  748. if ($_GET['visibility'] === 'private') {
  749. // Visibility not set or not already private, set private, otherwise reset it
  750. if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'private') {
  751. // See only private links
  752. $_SESSION['visibility'] = 'private';
  753. } else {
  754. unset($_SESSION['visibility']);
  755. }
  756. } elseif ($_GET['visibility'] === 'public') {
  757. if (empty($_SESSION['visibility']) || $_SESSION['visibility'] !== 'public') {
  758. // See only public links
  759. $_SESSION['visibility'] = 'public';
  760. } else {
  761. unset($_SESSION['visibility']);
  762. }
  763. }
  764. if (! empty($_SERVER['HTTP_REFERER'])) {
  765. $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('visibility'));
  766. } else {
  767. $location = '?';
  768. }
  769. header('Location: '. $location);
  770. exit;
  771. }
  772. // -------- User wants to see only untagged links (toggle)
  773. if (isset($_GET['untaggedonly'])) {
  774. $_SESSION['untaggedonly'] = empty($_SESSION['untaggedonly']);
  775. if (! empty($_SERVER['HTTP_REFERER'])) {
  776. $location = generateLocation($_SERVER['HTTP_REFERER'], $_SERVER['HTTP_HOST'], array('untaggedonly'));
  777. } else {
  778. $location = '?';
  779. }
  780. header('Location: '. $location);
  781. exit;
  782. }
  783. // -------- Handle other actions allowed for non-logged in users:
  784. if (!$loginManager->isLoggedIn())
  785. {
  786. // User tries to post new link but is not logged in:
  787. // Show login screen, then redirect to ?post=...
  788. if (isset($_GET['post']))
  789. {
  790. header( // Redirect to login page, then back to post link.
  791. 'Location: ?do=login&post='.urlencode($_GET['post']).
  792. (!empty($_GET['title'])?'&title='.urlencode($_GET['title']):'').
  793. (!empty($_GET['description'])?'&description='.urlencode($_GET['description']):'').
  794. (!empty($_GET['tags'])?'&tags='.urlencode($_GET['tags']):'').
  795. (!empty($_GET['source'])?'&source='.urlencode($_GET['source']):'')
  796. );
  797. exit;
  798. }
  799. showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
  800. if (isset($_GET['edit_link'])) {
  801. header('Location: ?do=login&edit_link='. escape($_GET['edit_link']));
  802. exit;
  803. }
  804. exit; // Never remove this one! All operations below are reserved for logged in user.
  805. }
  806. // -------- All other functions are reserved for the registered user:
  807. // -------- Display the Tools menu if requested (import/export/bookmarklet...)
  808. if ($targetPage == Router::$PAGE_TOOLS)
  809. {
  810. $data = [
  811. 'pageabsaddr' => index_url($_SERVER),
  812. 'sslenabled' => is_https($_SERVER),
  813. ];
  814. $pluginManager->executeHooks('render_tools', $data);
  815. foreach ($data as $key => $value) {
  816. $PAGE->assign($key, $value);
  817. }
  818. $PAGE->assign('pagetitle', t('Tools') .' - '. $conf->get('general.title', 'Shaarli'));
  819. $PAGE->renderPage('tools');
  820. exit;
  821. }
  822. // -------- User wants to change his/her password.
  823. if ($targetPage == Router::$PAGE_CHANGEPASSWORD)
  824. {
  825. if ($conf->get('security.open_shaarli')) {
  826. die(t('You are not supposed to change a password on an Open Shaarli.'));
  827. }
  828. if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword']))
  829. {
  830. if (!$sessionManager->checkToken($_POST['token'])) die(t('Wrong token.')); // Go away!
  831. // Make sure old password is correct.
  832. $oldhash = sha1($_POST['oldpassword'].$conf->get('credentials.login').$conf->get('credentials.salt'));
  833. if ($oldhash!= $conf->get('credentials.hash')) {
  834. echo '<script>alert("'. t('The old password is not correct.') .'");document.location=\'?do=changepasswd\';</script>';
  835. exit;
  836. }
  837. // Save new password
  838. // Salt renders rainbow-tables attacks useless.
  839. $conf->set('credentials.salt', sha1(uniqid('', true) .'_'. mt_rand()));
  840. $conf->set('credentials.hash', sha1($_POST['setpassword'] . $conf->get('credentials.login') . $conf->get('credentials.salt')));
  841. try {
  842. $conf->write($loginManager->isLoggedIn());
  843. }
  844. catch(Exception $e) {
  845. error_log(
  846. 'ERROR while writing config file after changing password.' . PHP_EOL .
  847. $e->getMessage()
  848. );
  849. // TODO: do not handle exceptions/errors in JS.
  850. echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=tools\';</script>';
  851. exit;
  852. }
  853. echo '<script>alert("'. t('Your password has been changed') .'");document.location=\'?do=tools\';</script>';
  854. exit;
  855. }
  856. else // show the change password form.
  857. {
  858. $PAGE->assign('pagetitle', t('Change password') .' - '. $conf->get('general.title', 'Shaarli'));
  859. $PAGE->renderPage('changepassword');
  860. exit;
  861. }
  862. }
  863. // -------- User wants to change configuration
  864. if ($targetPage == Router::$PAGE_CONFIGURE)
  865. {
  866. if (!empty($_POST['title']) )
  867. {
  868. if (!$sessionManager->checkToken($_POST['token'])) {
  869. die(t('Wrong token.')); // Go away!
  870. }
  871. $tz = 'UTC';
  872. if (!empty($_POST['continent']) && !empty($_POST['city'])
  873. && isTimeZoneValid($_POST['continent'], $_POST['city'])
  874. ) {
  875. $tz = $_POST['continent'] . '/' . $_POST['city'];
  876. }
  877. $conf->set('general.timezone', $tz);
  878. $conf->set('general.title', escape($_POST['title']));
  879. $conf->set('general.header_link', escape($_POST['titleLink']));
  880. $conf->set('resource.theme', escape($_POST['theme']));
  881. $conf->set('security.session_protection_disabled', !empty($_POST['disablesessionprotection']));
  882. $conf->set('privacy.default_private_links', !empty($_POST['privateLinkByDefault']));
  883. $conf->set('feed.rss_permalinks', !empty($_POST['enableRssPermalinks']));
  884. $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
  885. $conf->set('privacy.hide_public_links', !empty($_POST['hidePublicLinks']));
  886. $conf->set('api.enabled', !empty($_POST['enableApi']));
  887. $conf->set('api.secret', escape($_POST['apiSecret']));
  888. $conf->set('translation.language', escape($_POST['language']));
  889. try {
  890. $conf->write($loginManager->isLoggedIn());
  891. $history->updateSettings();
  892. invalidateCaches($conf->get('resource.page_cache'));
  893. }
  894. catch(Exception $e) {
  895. error_log(
  896. 'ERROR while writing config file after configuration update.' . PHP_EOL .
  897. $e->getMessage()
  898. );
  899. // TODO: do not handle exceptions/errors in JS.
  900. echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do=configure\';</script>';
  901. exit;
  902. }
  903. echo '<script>alert("'. t('Configuration was saved.') .'");document.location=\'?do=configure\';</script>';
  904. exit;
  905. }
  906. else // Show the configuration form.
  907. {
  908. $PAGE->assign('title', $conf->get('general.title'));
  909. $PAGE->assign('theme', $conf->get('resource.theme'));
  910. $PAGE->assign('theme_available', ThemeUtils::getThemes($conf->get('resource.raintpl_tpl')));
  911. list($continents, $cities) = generateTimeZoneData(
  912. timezone_identifiers_list(),
  913. $conf->get('general.timezone')
  914. );
  915. $PAGE->assign('continents', $continents);
  916. $PAGE->assign('cities', $cities);
  917. $PAGE->assign('private_links_default', $conf->get('privacy.default_private_links', false));
  918. $PAGE->assign('session_protection_disabled', $conf->get('security.session_protection_disabled', false));
  919. $PAGE->assign('enable_rss_permalinks', $conf->get('feed.rss_permalinks', false));
  920. $PAGE->assign('enable_update_check', $conf->get('updates.check_updates', true));
  921. $PAGE->assign('hide_public_links', $conf->get('privacy.hide_public_links', false));
  922. $PAGE->assign('api_enabled', $conf->get('api.enabled', true));
  923. $PAGE->assign('api_secret', $conf->get('api.secret'));
  924. $PAGE->assign('languages', Languages::getAvailableLanguages());
  925. $PAGE->assign('language', $conf->get('translation.language'));
  926. $PAGE->assign('pagetitle', t('Configure') .' - '. $conf->get('general.title', 'Shaarli'));
  927. $PAGE->renderPage('configure');
  928. exit;
  929. }
  930. }
  931. // -------- User wants to rename a tag or delete it
  932. if ($targetPage == Router::$PAGE_CHANGETAG)
  933. {
  934. if (empty($_POST['fromtag']) || (empty($_POST['totag']) && isset($_POST['renametag']))) {
  935. $PAGE->assign('fromtag', ! empty($_GET['fromtag']) ? escape($_GET['fromtag']) : '');
  936. $PAGE->assign('pagetitle', t('Manage tags') .' - '. $conf->get('general.title', 'Shaarli'));
  937. $PAGE->renderPage('changetag');
  938. exit;
  939. }
  940. if (!$sessionManager->checkToken($_POST['token'])) {
  941. die(t('Wrong token.'));
  942. }
  943. $alteredLinks = $LINKSDB->renameTag(escape($_POST['fromtag']), escape($_POST['totag']));
  944. $LINKSDB->save($conf->get('resource.page_cache'));
  945. foreach ($alteredLinks as $link) {
  946. $history->updateLink($link);
  947. }
  948. $delete = empty($_POST['totag']);
  949. $redirect = $delete ? 'do=changetag' : 'searchtags='. urlencode(escape($_POST['totag']));
  950. $count = count($alteredLinks);
  951. $alert = $delete
  952. ? sprintf(t('The tag was removed from %d link.', 'The tag was removed from %d links.', $count), $count)
  953. : sprintf(t('The tag was renamed in %d link.', 'The tag was renamed in %d links.', $count), $count);
  954. echo '<script>alert("'. $alert .'");document.location=\'?'. $redirect .'\';</script>';
  955. exit;
  956. }
  957. // -------- User wants to add a link without using the bookmarklet: Show form.
  958. if ($targetPage == Router::$PAGE_ADDLINK)
  959. {
  960. $PAGE->assign('pagetitle', t('Shaare a new link') .' - '. $conf->get('general.title', 'Shaarli'));
  961. $PAGE->renderPage('addlink');
  962. exit;
  963. }
  964. // -------- User clicked the "Save" button when editing a link: Save link to database.
  965. if (isset($_POST['save_edit']))
  966. {
  967. // Go away!
  968. if (! $sessionManager->checkToken($_POST['token'])) {
  969. die(t('Wrong token.'));
  970. }
  971. // lf_id should only be present if the link exists.
  972. $id = isset($_POST['lf_id']) ? intval(escape($_POST['lf_id'])) : $LINKSDB->getNextId();
  973. // Linkdate is kept here to:
  974. // - use the same permalink for notes as they're displayed when creating them
  975. // - let users hack creation date of their posts
  976. // See: https://shaarli.readthedocs.io/en/master/Various-hacks/#changing-the-timestamp-for-a-shaare
  977. $linkdate = escape($_POST['lf_linkdate']);
  978. if (isset($LINKSDB[$id])) {
  979. // Edit
  980. $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
  981. $updated = new DateTime();
  982. $shortUrl = $LINKSDB[$id]['shorturl'];
  983. $new = false;
  984. } else {
  985. // New link
  986. $created = DateTime::createFromFormat(LinkDB::LINK_DATE_FORMAT, $linkdate);
  987. $updated = null;
  988. $shortUrl = link_small_hash($created, $id);
  989. $new = true;
  990. }
  991. // Remove multiple spaces.
  992. $tags = trim(preg_replace('/\s\s+/', ' ', $_POST['lf_tags']));
  993. // Remove first '-' char in tags.
  994. $tags = preg_replace('/(^| )\-/', '$1', $tags);
  995. // Remove duplicates.
  996. $tags = implode(' ', array_unique(explode(' ', $tags)));
  997. if (empty(trim($_POST['lf_url']))) {
  998. $_POST['lf_url'] = '?' . smallHash($linkdate . $id);
  999. }
  1000. $url = whitelist_protocols(trim($_POST['lf_url']), $conf->get('security.allowed_protocols'));
  1001. $link = array(
  1002. 'id' => $id,
  1003. 'title' => trim($_POST['lf_title']),
  1004. 'url' => $url,
  1005. 'description' => $_POST['lf_description'],
  1006. 'private' => (isset($_POST['lf_private']) ? 1 : 0),
  1007. 'created' => $created,
  1008. 'updated' => $updated,
  1009. 'tags' => str_replace(',', ' ', $tags),
  1010. 'shorturl' => $shortUrl,
  1011. );
  1012. // If title is empty, use the URL as title.
  1013. if ($link['title'] == '') {
  1014. $link['title'] = $link['url'];
  1015. }
  1016. $pluginManager->executeHooks('save_link', $link);
  1017. $LINKSDB[$id] = $link;
  1018. $LINKSDB->save($conf->get('resource.page_cache'));
  1019. if ($new) {
  1020. $history->addLink($link);
  1021. } else {
  1022. $history->updateLink($link);
  1023. }
  1024. // If we are called from the bookmarklet, we must close the popup:
  1025. if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) {
  1026. echo '<script>self.close();</script>';
  1027. exit;
  1028. }
  1029. $returnurl = !empty($_POST['returnurl']) ? $_POST['returnurl'] : '?';
  1030. $location = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
  1031. // Scroll to the link which has been edited.
  1032. $location .= '#' . $link['shorturl'];
  1033. // After saving the link, redirect to the page the user was on.
  1034. header('Location: '. $location);
  1035. exit;
  1036. }
  1037. // -------- User clicked the "Cancel" button when editing a link.
  1038. if (isset($_POST['cancel_edit']))
  1039. {
  1040. $id = isset($_POST['lf_id']) ? (int) escape($_POST['lf_id']) : false;
  1041. if (! isset($LINKSDB[$id])) {
  1042. header('Location: ?');
  1043. }
  1044. // If we are called from the bookmarklet, we must close the popup:
  1045. if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
  1046. $link = $LINKSDB[$id];
  1047. $returnurl = ( isset($_POST['returnurl']) ? $_POST['returnurl'] : '?' );
  1048. // Scroll to the link which has been edited.
  1049. $returnurl .= '#'. $link['shorturl'];
  1050. $returnurl = generateLocation($returnurl, $_SERVER['HTTP_HOST'], array('addlink', 'post', 'edit_link'));
  1051. header('Location: '.$returnurl); // After canceling, redirect to the page the user was on.
  1052. exit;
  1053. }
  1054. // -------- User clicked the "Delete" button when editing a link: Delete link from database.
  1055. if ($targetPage == Router::$PAGE_DELETELINK)
  1056. {
  1057. if (! $sessionManager->checkToken($_GET['token'])) {
  1058. die(t('Wrong token.'));
  1059. }
  1060. $ids = trim($_GET['lf_linkdate']);
  1061. if (strpos($ids, ' ') !== false) {
  1062. // multiple, space-separated ids provided
  1063. $ids = array_values(array_filter(preg_split('/\s+/', escape($ids))));
  1064. } else {
  1065. // only a single id provided
  1066. $ids = [$ids];
  1067. }
  1068. // assert at least one id is given
  1069. if(!count($ids)){
  1070. die('no id provided');
  1071. }
  1072. foreach ($ids as $id) {
  1073. $id = (int) escape($id);
  1074. $link = $LINKSDB[$id];
  1075. $pluginManager->executeHooks('delete_link', $link);
  1076. unset($LINKSDB[$id]);
  1077. }
  1078. $LINKSDB->save($conf->get('resource.page_cache')); // save to disk
  1079. $history->deleteLink($link);
  1080. // If we are called from the bookmarklet, we must close the popup:
  1081. if (isset($_GET['source']) && ($_GET['source']=='bookmarklet' || $_GET['source']=='firefoxsocialapi')) { echo '<script>self.close();</script>'; exit; }
  1082. $location = '?';
  1083. if (isset($_SERVER['HTTP_REFERER'])) {
  1084. // Don't redirect to where we were previously if it was a permalink or an edit_link, because it would 404.
  1085. $location = generateLocation(
  1086. $_SERVER['HTTP_REFERER'],
  1087. $_SERVER['HTTP_HOST'],
  1088. ['delete_link', 'edit_link', $link['shorturl']]
  1089. );
  1090. }
  1091. header('Location: ' . $location); // After deleting the link, redirect to appropriate location
  1092. exit;
  1093. }
  1094. // -------- User clicked the "EDIT" button on a link: Display link edit form.
  1095. if (isset($_GET['edit_link']))
  1096. {
  1097. $id = (int) escape($_GET['edit_link']);
  1098. $link = $LINKSDB[$id]; // Read database
  1099. if (!$link) { header('Location: ?'); exit; } // Link not found in database.
  1100. $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
  1101. $data = array(
  1102. 'link' => $link,
  1103. 'link_is_new' => false,
  1104. 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
  1105. 'tags' => $LINKSDB->linksCountPerTag(),
  1106. );
  1107. $pluginManager->executeHooks('render_editlink', $data);
  1108. foreach ($data as $key => $value) {
  1109. $PAGE->assign($key, $value);
  1110. }
  1111. $PAGE->assign('pagetitle', t('Edit') .' '. t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
  1112. $PAGE->renderPage('editlink');
  1113. exit;
  1114. }
  1115. // -------- User want to post a new link: Display link edit form.
  1116. if (isset($_GET['post'])) {
  1117. $url = cleanup_url($_GET['post']);
  1118. $link_is_new = false;
  1119. // Check if URL is not already in database (in this case, we will edit the existing link)
  1120. $link = $LINKSDB->getLinkFromUrl($url);
  1121. if (! $link)
  1122. {
  1123. $link_is_new = true;
  1124. $linkdate = strval(date(LinkDB::LINK_DATE_FORMAT));
  1125. // Get title if it was provided in URL (by the bookmarklet).
  1126. $title = empty($_GET['title']) ? '' : escape($_GET['title']);
  1127. // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
  1128. $description = empty($_GET['description']) ? '' : escape($_GET['description']);
  1129. $tags = empty($_GET['tags']) ? '' : escape($_GET['tags']);
  1130. $private = !empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0;
  1131. // If this is an HTTP(S) link, we try go get the page to extract the title (otherwise we will to straight to the edit form.)
  1132. if (empty($title) && strpos(get_url_scheme($url), 'http') !== false) {
  1133. // Short timeout to keep the application responsive
  1134. // The callback will fill $charset and $title with data from the downloaded page.
  1135. get_http_response(
  1136. $url,
  1137. $conf->get('general.download_timeout', 30),
  1138. $conf->get('general.download_max_size', 4194304),
  1139. get_curl_download_callback($charset, $title)
  1140. );
  1141. if (! empty($title) && strtolower($charset) != 'utf-8') {
  1142. $title = mb_convert_encoding($title, 'utf-8', $charset);
  1143. }
  1144. }
  1145. if ($url == '') {
  1146. $url = '?' . smallHash($linkdate . $LINKSDB->getNextId());
  1147. $title = $conf->get('general.default_note_title', t('Note: '));
  1148. }
  1149. $url = escape($url);
  1150. $title = escape($title);
  1151. $link = array(
  1152. 'linkdate' => $linkdate,
  1153. 'title' => $title,
  1154. 'url' => $url,
  1155. 'description' => $description,
  1156. 'tags' => $tags,
  1157. 'private' => $private,
  1158. );
  1159. } else {
  1160. $link['linkdate'] = $link['created']->format(LinkDB::LINK_DATE_FORMAT);
  1161. }
  1162. $data = array(
  1163. 'link' => $link,
  1164. 'link_is_new' => $link_is_new,
  1165. 'http_referer' => (isset($_SERVER['HTTP_REFERER']) ? escape($_SERVER['HTTP_REFERER']) : ''),
  1166. 'source' => (isset($_GET['source']) ? $_GET['source'] : ''),
  1167. 'tags' => $LINKSDB->linksCountPerTag(),
  1168. 'default_private_links' => $conf->get('privacy.default_private_links', false),
  1169. );
  1170. $pluginManager->executeHooks('render_editlink', $data);
  1171. foreach ($data as $key => $value) {
  1172. $PAGE->assign($key, $value);
  1173. }
  1174. $PAGE->assign('pagetitle', t('Shaare') .' - '. $conf->get('general.title', 'Shaarli'));
  1175. $PAGE->renderPage('editlink');
  1176. exit;
  1177. }
  1178. if ($targetPage == Router::$PAGE_EXPORT) {
  1179. // Export links as a Netscape Bookmarks file
  1180. if (empty($_GET['selection'])) {
  1181. $PAGE->assign('pagetitle', t('Export') .' - '. $conf->get('general.title', 'Shaarli'));
  1182. $PAGE->renderPage('export');
  1183. exit;
  1184. }
  1185. // export as bookmarks_(all|private|public)_YYYYmmdd_HHMMSS.html
  1186. $selection = $_GET['selection'];
  1187. if (isset($_GET['prepend_note_url'])) {
  1188. $prependNoteUrl = $_GET['prepend_note_url'];
  1189. } else {
  1190. $prependNoteUrl = false;
  1191. }
  1192. try {
  1193. $PAGE->assign(
  1194. 'links',
  1195. NetscapeBookmarkUtils::filterAndFormat(
  1196. $LINKSDB,
  1197. $selection,
  1198. $prependNoteUrl,
  1199. index_url($_SERVER)
  1200. )
  1201. );
  1202. } catch (Exception $exc) {
  1203. header('Content-Type: text/plain; charset=utf-8');
  1204. echo $exc->getMessage();
  1205. exit;
  1206. }
  1207. $now = new DateTime();
  1208. header('Content-Type: text/html; charset=utf-8');
  1209. header(
  1210. 'Content-disposition: attachment; filename=bookmarks_'
  1211. .$selection.'_'.$now->format(LinkDB::LINK_DATE_FORMAT).'.html'
  1212. );
  1213. $PAGE->assign('date', $now->format(DateTime::RFC822));
  1214. $PAGE->assign('eol', PHP_EOL);
  1215. $PAGE->assign('selection', $selection);
  1216. $PAGE->renderPage('export.bookmarks');
  1217. exit;
  1218. }
  1219. if ($targetPage == Router::$PAGE_IMPORT) {
  1220. // Upload a Netscape bookmark dump to import its contents
  1221. if (! isset($_POST['token']) || ! isset($_FILES['filetoupload'])) {
  1222. // Show import dialog
  1223. $PAGE->assign(
  1224. 'maxfilesize',
  1225. get_max_upload_size(
  1226. ini_get('post_max_size'),
  1227. ini_get('upload_max_filesize'),
  1228. false
  1229. )
  1230. );
  1231. $PAGE->assign(
  1232. 'maxfilesizeHuman',
  1233. get_max_upload_size(
  1234. ini_get('post_max_size'),
  1235. ini_get('upload_max_filesize'),
  1236. true
  1237. )
  1238. );
  1239. $PAGE->assign('pagetitle', t('Import') .' - '. $conf->get('general.title', 'Shaarli'));
  1240. $PAGE->renderPage('import');
  1241. exit;
  1242. }
  1243. // Import bookmarks from an uploaded file
  1244. if (isset($_FILES['filetoupload']['size']) && $_FILES['filetoupload']['size'] == 0) {
  1245. // The file is too big or some form field may be missing.
  1246. $msg = sprintf(
  1247. t(
  1248. 'The file you are trying to upload is probably bigger than what this webserver can accept'
  1249. .' (%s). Please upload in smaller chunks.'
  1250. ),
  1251. get_max_upload_size(ini_get('post_max_size'), ini_get('upload_max_filesize'))
  1252. );
  1253. echo '<script>alert("'. $msg .'");document.location=\'?do='.Router::$PAGE_IMPORT .'\';</script>';
  1254. exit;
  1255. }
  1256. if (! $sessionManager->checkToken($_POST['token'])) {
  1257. die('Wrong token.');
  1258. }
  1259. $status = NetscapeBookmarkUtils::import(
  1260. $_POST,
  1261. $_FILES,
  1262. $LINKSDB,
  1263. $conf,
  1264. $history
  1265. );
  1266. echo '<script>alert("'.$status.'");document.location=\'?do='
  1267. .Router::$PAGE_IMPORT .'\';</script>';
  1268. exit;
  1269. }
  1270. // Plugin administration page
  1271. if ($targetPage == Router::$PAGE_PLUGINSADMIN) {
  1272. $pluginMeta = $pluginManager->getPluginsMeta();
  1273. // Split plugins into 2 arrays: ordered enabled plugins and disabled.
  1274. $enabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] !== false; });
  1275. // Load parameters.
  1276. $enabledPlugins = load_plugin_parameter_values($enabledPlugins, $conf->get('plugins', array()));
  1277. uasort(
  1278. $enabledPlugins,
  1279. function($a, $b) { return $a['order'] - $b['order']; }
  1280. );
  1281. $disabledPlugins = array_filter($pluginMeta, function($v) { return $v['order'] === false; });
  1282. $PAGE->assign('enabledPlugins', $enabledPlugins);
  1283. $PAGE->assign('disabledPlugins', $disabledPlugins);
  1284. $PAGE->assign('pagetitle', t('Plugin administration') .' - '. $conf->get('general.title', 'Shaarli'));
  1285. $PAGE->renderPage('pluginsadmin');
  1286. exit;
  1287. }
  1288. // Plugin administration form action
  1289. if ($targetPage == Router::$PAGE_SAVE_PLUGINSADMIN) {
  1290. try {
  1291. if (isset($_POST['parameters_form'])) {
  1292. unset($_POST['parameters_form']);
  1293. foreach ($_POST as $param => $value) {
  1294. $conf->set('plugins.'. $param, escape($value));
  1295. }
  1296. }
  1297. else {
  1298. $conf->set('general.enabled_plugins', save_plugin_config($_POST));
  1299. }
  1300. $conf->write($loginManager->isLoggedIn());
  1301. $history->updateSettings();
  1302. }
  1303. catch (Exception $e) {
  1304. error_log(
  1305. 'ERROR while saving plugin configuration:.' . PHP_EOL .
  1306. $e->getMessage()
  1307. );
  1308. // TODO: do not handle exceptions/errors in JS.
  1309. echo '<script>alert("'. $e->getMessage() .'");document.location=\'?do='. Router::$PAGE_PLUGINSADMIN .'\';</script>';
  1310. exit;
  1311. }
  1312. header('Location: ?do='. Router::$PAGE_PLUGINSADMIN);
  1313. exit;
  1314. }
  1315. // Get a fresh token
  1316. if ($targetPage == Router::$GET_TOKEN) {
  1317. header('Content-Type:text/plain');
  1318. echo $sessionManager->generateToken($conf);
  1319. exit;
  1320. }
  1321. // -------- Otherwise, simply display search form and links:
  1322. showLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager);
  1323. exit;
  1324. }
  1325. /**
  1326. * Template for the list of links (<div id="linklist">)
  1327. * This function fills all the necessary fields in the $PAGE for the template 'linklist.html'
  1328. *
  1329. * @param pageBuilder $PAGE pageBuilder instance.
  1330. * @param LinkDB $LINKSDB LinkDB instance.
  1331. * @param ConfigManager $conf Configuration Manager instance.
  1332. * @param PluginManager $pluginManager Plugin Manager instance.
  1333. * @param LoginManager $loginManager LoginManager instance
  1334. */
  1335. function buildLinkList($PAGE, $LINKSDB, $conf, $pluginManager, $loginManager)
  1336. {
  1337. // Used in templates
  1338. if (isset($_GET['searchtags'])) {
  1339. if (! empty($_GET['searchtags'])) {
  1340. $searchtags = escape(normalize_spaces($_GET['searchtags']));
  1341. } else {
  1342. $searchtags = false;
  1343. }
  1344. } else {
  1345. $searchtags = '';
  1346. }
  1347. $searchterm = !empty($_GET['searchterm']) ? escape(normalize_spaces($_GET['searchterm'])) : '';
  1348. // Smallhash filter
  1349. if (! empty($_SERVER['QUERY_STRING'])
  1350. && preg_match('/^[a-zA-Z0-9-_@]{6}($|&|#)/', $_SERVER['QUERY_STRING'])) {
  1351. try {
  1352. $linksToDisplay = $LINKSDB->filterHash($_SERVER['QUERY_STRING']);
  1353. } catch (LinkNotFoundException $e) {
  1354. $PAGE->render404($e->getMessage());
  1355. exit;
  1356. }
  1357. } else {
  1358. // Filter links according search parameters.
  1359. $visibility = ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '';
  1360. $request = [
  1361. 'searchtags' => $searchtags,
  1362. 'searchterm' => $searchterm,
  1363. ];
  1364. $linksToDisplay = $LINKSDB->filterSearch($request, false, $visibility, !empty($_SESSION['untaggedonly']));
  1365. }
  1366. // ---- Handle paging.
  1367. $keys = array();
  1368. foreach ($linksToDisplay as $key => $value) {
  1369. $keys[] = $key;
  1370. }
  1371. // Select articles according to paging.
  1372. $pagecount = ceil(count($keys) / $_SESSION['LINKS_PER_PAGE']);
  1373. $pagecount = $pagecount == 0 ? 1 : $pagecount;
  1374. $page= empty($_GET['page']) ? 1 : intval($_GET['page']);
  1375. $page = $page < 1 ? 1 : $page;
  1376. $page = $page > $pagecount ? $pagecount : $page;
  1377. // Start index.
  1378. $i = ($page-1) * $_SESSION['LINKS_PER_PAGE'];
  1379. $end = $i + $_SESSION['LINKS_PER_PAGE'];
  1380. $linkDisp = array();
  1381. while ($i<$end && $i<count($keys))
  1382. {
  1383. $link = $linksToDisplay[$keys[$i]];
  1384. $link['description'] = format_description(
  1385. $link['description'],
  1386. $conf->get('redirector.url'),
  1387. $conf->get('redirector.encode_url')
  1388. );
  1389. $classLi = ($i % 2) != 0 ? '' : 'publicLinkHightLight';
  1390. $link['class'] = $link['private'] == 0 ? $classLi : 'private';
  1391. $link['timestamp'] = $link['created']->getTimestamp();
  1392. if (! empty($link['updated'])) {
  1393. $link['updated_timestamp'] = $link['updated']->getTimestamp();
  1394. } else {
  1395. $link['updated_timestamp'] = '';
  1396. }
  1397. $taglist = preg_split('/\s+/', $link['tags'], -1, PREG_SPLIT_NO_EMPTY);
  1398. uasort($taglist, 'strcasecmp');
  1399. $link['taglist'] = $taglist;
  1400. // Check for both signs of a note: starting with ? and 7 chars long.
  1401. if ($link['url'][0] === '?' &&
  1402. strlen($link['url']) === 7) {
  1403. $link['url'] = index_url($_SERVER) . $link['url'];
  1404. }
  1405. $linkDisp[$keys[$i]] = $link;
  1406. $i++;
  1407. }
  1408. // Compute paging navigation
  1409. $searchtagsUrl = $searchtags === '' ? '' : '&searchtags=' . urlencode($searchtags);
  1410. $searchtermUrl = empty($searchterm) ? '' : '&searchterm=' . urlencode($searchterm);
  1411. $previous_page_url = '';
  1412. if ($i != count($keys)) {
  1413. $previous_page_url = '?page=' . ($page+1) . $searchtermUrl . $searchtagsUrl;
  1414. }
  1415. $next_page_url='';
  1416. if ($page>1) {
  1417. $next_page_url = '?page=' . ($page-1) . $searchtermUrl . $searchtagsUrl;
  1418. }
  1419. // Fill all template fields.
  1420. $data = array(
  1421. 'previous_page_url' => $previous_page_url,
  1422. 'next_page_url' => $next_page_url,
  1423. 'page_current' => $page,
  1424. 'page_max' => $pagecount,
  1425. 'result_count' => count($linksToDisplay),
  1426. 'search_term' => $searchterm,
  1427. 'search_tags' => $searchtags,
  1428. 'visibility' => ! empty($_SESSION['visibility']) ? $_SESSION['visibility'] : '',
  1429. 'redirector' => $conf->get('redirector.url'), // Optional redirector URL.
  1430. 'links' => $linkDisp,
  1431. );
  1432. // If there is only a single link, we change on-the-fly the title of the page.
  1433. if (count($linksToDisplay) == 1) {
  1434. $data['pagetitle'] = $linksToDisplay[$keys[0]]['title'] .' - '. $conf->get('general.title');
  1435. } elseif (! empty($searchterm) || ! empty($searchtags)) {
  1436. $data['pagetitle'] = t('Search: ');
  1437. $data['pagetitle'] .= ! empty($searchterm) ? $searchterm .' ' : '';
  1438. $bracketWrap = function ($tag) {
  1439. return '['. $tag .']';
  1440. };
  1441. $data['pagetitle'] .= ! empty($searchtags)
  1442. ? implode(' ', array_map($bracketWrap, preg_split('/\s+/', $searchtags))).' '
  1443. : '';
  1444. $data['pagetitle'] .= '- '. $conf->get('general.title');
  1445. }
  1446. $pluginManager->executeHooks('render_linklist', $data, array('loggedin' => $loginManager->isLoggedIn()));
  1447. foreach ($data as $key => $value) {
  1448. $PAGE->assign($key, $value);
  1449. }
  1450. return;
  1451. }
  1452. /**
  1453. * Compute the thumbnail for a link.
  1454. *
  1455. * With a link to the original URL.
  1456. * Understands various services (youtube.com...)
  1457. * Input: $url = URL for which the thumbnail must be found.
  1458. * $href = if provided, this URL will be followed instead of $url
  1459. * Returns an associative array with thumbnail attributes (src,href,width,height,style,alt)
  1460. * Some of them may be missing.
  1461. * Return an empty array if no thumbnail available.
  1462. *
  1463. * @param ConfigManager $conf Configuration Manager instance.
  1464. * @param string $url
  1465. * @param string|bool $href
  1466. *
  1467. * @return array
  1468. */
  1469. function computeThumbnail($conf, $url, $href = false)
  1470. {
  1471. if (!$conf->get('thumbnail.enable_thumbnails')) return array();
  1472. if ($href==false) $href=$url;
  1473. // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link.
  1474. // (e.g. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/default.jpg )
  1475. // ^^^^^^^^^^^ ^^^^^^^^^^^
  1476. $domain = parse_url($url,PHP_URL_HOST);
  1477. if ($domain=='youtube.com' || $domain=='www.youtube.com')
  1478. {
  1479. parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract video ID and get thumbnail
  1480. if (!empty($params['v'])) return array('src'=>'https://img.youtube.com/vi/'.$params['v'].'/default.jpg',
  1481. 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
  1482. }
  1483. if ($domain=='youtu.be') // Youtube short links
  1484. {
  1485. $path = parse_url($url,PHP_URL_PATH);
  1486. return array('src'=>'https://img.youtube.com/vi'.$path.'/default.jpg',
  1487. 'href'=>$href,'width'=>'120','height'=>'90','alt'=>'YouTube thumbnail');
  1488. }
  1489. if ($domain=='pix.toile-libre.org') // pix.toile-libre.org image hosting
  1490. {
  1491. parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract image filename.
  1492. if (!empty($params) && !empty($params['img'])) return array('src'=>'http://pix.toile-libre.org/upload/thumb/'.urlencode($params['img']),
  1493. 'href'=>$href,'style'=>'max-width:120px; max-height:150px','alt'=>'pix.toile-libre.org thumbnail');
  1494. }
  1495. if ($domain=='imgur.com')
  1496. {
  1497. $path = parse_url($url,PHP_URL_PATH);
  1498. if (startsWith($path,'/a/')) return array(); // Thumbnails for albums are not available.
  1499. if (startsWith($path,'/r/')) return array('src'=>'https://i.imgur.com/'.basename($path).'s.jpg',
  1500. 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
  1501. if (startsWith($path,'/gallery/')) return array('src'=>'https://i.imgur.com'.substr($path,8).'s.jpg',
  1502. 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
  1503. if (substr_count($path,'/')==1) return array('src'=>'https://i.imgur.com/'.substr($path,1).'s.jpg',
  1504. 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
  1505. }
  1506. if ($domain=='i.imgur.com')
  1507. {
  1508. $pi = pathinfo(parse_url($url,PHP_URL_PATH));
  1509. if (!empty($pi['filename'])) return array('src'=>'https://i.imgur.com/'.$pi['filename'].'s.jpg',
  1510. 'href'=>$href,'width'=>'90','height'=>'90','alt'=>'imgur.com thumbnail');
  1511. }
  1512. if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com')
  1513. {
  1514. if (strpos($url,'dailymotion.com/video/')!==false)
  1515. {
  1516. $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url);
  1517. return array('src'=>$thumburl,
  1518. 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'DailyMotion thumbnail');
  1519. }
  1520. }
  1521. if (endsWith($domain,'.imageshack.us'))
  1522. {
  1523. $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
  1524. if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
  1525. {
  1526. $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext;
  1527. return array('src'=>$thumburl,
  1528. 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'imageshack.us thumbnail');
  1529. }
  1530. }
  1531. // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL.
  1532. // So we deport the thumbnail generation in order not to slow down page generation
  1533. // (and we also cache the thumbnail)
  1534. if (! $conf->get('thumbnail.enable_localcache')) return array(); // If local cache is disabled, no thumbnails for services which require the use a local cache.
  1535. if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')
  1536. || $domain=='vimeo.com'
  1537. || $domain=='ted.com' || endsWith($domain,'.ted.com')
  1538. || $domain=='xkcd.com' || endsWith($domain,'.xkcd.com')
  1539. )
  1540. {
  1541. if ($domain=='vimeo.com')
  1542. { // Make sure this vimeo URL points to a video (/xxx... where xxx is numeric)
  1543. $path = parse_url($url,PHP_URL_PATH);
  1544. if (!preg_match('!/\d+.+?!',$path)) return array(); // This is not a single video URL.
  1545. }
  1546. if ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
  1547. { // Make sure this URL points to a single comic (/xxx... where xxx is numeric)
  1548. $path = parse_url($url,PHP_URL_PATH);
  1549. if (!preg_match('!/\d+.+?!',$path)) return array();
  1550. }
  1551. if ($domain=='ted.com' || endsWith($domain,'.ted.com'))
  1552. { // Make sure this TED URL points to a video (/talks/...)
  1553. $path = parse_url($url,PHP_URL_PATH);
  1554. if ("/talks/" !== substr($path,0,7)) return array(); // This is not a single video URL.
  1555. }
  1556. $sign = hash_hmac('sha256', $url, $conf->get('credentials.salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
  1557. return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
  1558. 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
  1559. }
  1560. // For all other, we try to make a thumbnail of links ending with .jpg/jpeg/png/gif
  1561. // Technically speaking, we should download ALL links and check their Content-Type to see if they are images.
  1562. // But using the extension will do.
  1563. $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION));
  1564. if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif')
  1565. {
  1566. $sign = hash_hmac('sha256', $url, $conf->get('credentials.salt')); // We use the salt to sign data (it's random, secret, and specific to each installation)
  1567. return array('src'=>index_url($_SERVER).'?do=genthumbnail&hmac='.$sign.'&url='.urlencode($url),
  1568. 'href'=>$href,'width'=>'120','style'=>'height:auto;','alt'=>'thumbnail');
  1569. }
  1570. return array(); // No thumbnail.
  1571. }
  1572. // Returns the HTML code to display a thumbnail for a link
  1573. // with a link to the original URL.
  1574. // Understands various services (youtube.com...)
  1575. // Input: $url = URL for which the thumbnail must be found.
  1576. // $href = if provided, this URL will be followed instead of $url
  1577. // Returns '' if no thumbnail available.
  1578. function thumbnail($url,$href=false)
  1579. {
  1580. // FIXME!
  1581. global $conf;
  1582. $t = computeThumbnail($conf, $url,$href);
  1583. if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
  1584. $html='<a href="'.escape($t['href']).'"><img src="'.escape($t['src']).'"';
  1585. if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
  1586. if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
  1587. if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
  1588. if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
  1589. $html.='></a>';
  1590. return $html;
  1591. }
  1592. // Returns the HTML code to display a thumbnail for a link
  1593. // for the picture wall (using lazy image loading)
  1594. // Understands various services (youtube.com...)
  1595. // Input: $url = URL for which the thumbnail must be found.
  1596. // $href = if provided, this URL will be followed instead of $url
  1597. // Returns '' if no thumbnail available.
  1598. function lazyThumbnail($conf, $url,$href=false)
  1599. {
  1600. // FIXME!
  1601. global $conf;
  1602. $t = computeThumbnail($conf, $url,$href);
  1603. if (count($t)==0) return ''; // Empty array = no thumbnail for this URL.
  1604. $html='<a href="'.escape($t['href']).'">';
  1605. // Lazy image
  1606. $html.='<img class="b-lazy" src="#" data-src="'.escape($t['src']).'"';
  1607. if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
  1608. if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
  1609. if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
  1610. if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
  1611. $html.='>';
  1612. // No-JavaScript fallback.
  1613. $html.='<noscript><img src="'.escape($t['src']).'"';
  1614. if (!empty($t['width'])) $html.=' width="'.escape($t['width']).'"';
  1615. if (!empty($t['height'])) $html.=' height="'.escape($t['height']).'"';
  1616. if (!empty($t['style'])) $html.=' style="'.escape($t['style']).'"';
  1617. if (!empty($t['alt'])) $html.=' alt="'.escape($t['alt']).'"';
  1618. $html.='></noscript></a>';
  1619. return $html;
  1620. }
  1621. /**
  1622. * Installation
  1623. * This function should NEVER be called if the file data/config.php exists.
  1624. *
  1625. * @param ConfigManager $conf Configuration Manager instance.
  1626. * @param SessionManager $sessionManager SessionManager instance
  1627. * @param LoginManager $loginManager LoginManager instance
  1628. */
  1629. function install($conf, $sessionManager, $loginManager) {
  1630. // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
  1631. if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
  1632. // This part makes sure sessions works correctly.
  1633. // (Because on some hosts, session.save_path may not be set correctly,
  1634. // or we may not have write access to it.)
  1635. if (isset($_GET['test_session']) && ( !isset($_SESSION) || !isset($_SESSION['session_tested']) || $_SESSION['session_tested']!='Working'))
  1636. {
  1637. // Step 2: Check if data in session is correct.
  1638. $msg = t(
  1639. '<pre>Sessions do not seem to work correctly on your server.<br>'.
  1640. 'Make sure the variable "session.save_path" is set correctly in your PHP config, '.
  1641. 'and that you have write access to it.<br>'.
  1642. 'It currently points to %s.<br>'.
  1643. 'On some browsers, accessing your server via a hostname like \'localhost\' '.
  1644. 'or any custom hostname without a dot causes cookie storage to fail. '.
  1645. 'We recommend accessing your server via it\'s IP address or Fully Qualified Domain Name.<br>'
  1646. );
  1647. $msg = sprintf($msg, session_save_path());
  1648. echo $msg;
  1649. echo '<br><a href="?">'. t('Click to try again.') .'</a></pre>';
  1650. die;
  1651. }
  1652. if (!isset($_SESSION['session_tested']))
  1653. { // Step 1 : Try to store data in session and reload page.
  1654. $_SESSION['session_tested'] = 'Working'; // Try to set a variable in session.
  1655. header('Location: '.index_url($_SERVER).'?test_session'); // Redirect to check stored data.
  1656. }
  1657. if (isset($_GET['test_session']))
  1658. { // Step 3: Sessions are OK. Remove test parameter from URL.
  1659. header('Location: '.index_url($_SERVER));
  1660. }
  1661. if (!empty($_POST['setlogin']) && !empty($_POST['setpassword']))
  1662. {
  1663. $tz = 'UTC';
  1664. if (!empty($_POST['continent']) && !empty($_POST['city'])
  1665. && isTimeZoneValid($_POST['continent'], $_POST['city'])
  1666. ) {
  1667. $tz = $_POST['continent'].'/'.$_POST['city'];
  1668. }
  1669. $conf->set('general.timezone', $tz);
  1670. $login = $_POST['setlogin'];
  1671. $conf->set('credentials.login', $login);
  1672. $salt = sha1(uniqid('', true) .'_'. mt_rand());
  1673. $conf->set('credentials.salt', $salt);
  1674. $conf->set('credentials.hash', sha1($_POST['setpassword'] . $login . $salt));
  1675. if (!empty($_POST['title'])) {
  1676. $conf->set('general.title', escape($_POST['title']));
  1677. } else {
  1678. $conf->set('general.title', 'Shared links on '.escape(index_url($_SERVER)));
  1679. }
  1680. $conf->set('translation.language', escape($_POST['language']));
  1681. $conf->set('updates.check_updates', !empty($_POST['updateCheck']));
  1682. $conf->set('api.enabled', !empty($_POST['enableApi']));
  1683. $conf->set(
  1684. 'api.secret',
  1685. generate_api_secret(
  1686. $conf->get('credentials.login'),
  1687. $conf->get('credentials.salt')
  1688. )
  1689. );
  1690. try {
  1691. // Everything is ok, let's create config file.
  1692. $conf->write($loginManager->isLoggedIn());
  1693. }
  1694. catch(Exception $e) {
  1695. error_log(
  1696. 'ERROR while writing config file after installation.' . PHP_EOL .
  1697. $e->getMessage()
  1698. );
  1699. // TODO: do not handle exceptions/errors in JS.
  1700. echo '<script>alert("'. $e->getMessage() .'");document.location=\'?\';</script>';
  1701. exit;
  1702. }
  1703. echo '<script>alert("Shaarli is now configured. Please enter your login/password and start shaaring your links!");document.location=\'?do=login\';</script>';
  1704. exit;
  1705. }
  1706. $PAGE = new PageBuilder($conf, null, $sessionManager->generateToken());
  1707. list($continents, $cities) = generateTimeZoneData(timezone_identifiers_list(), date_default_timezone_get());
  1708. $PAGE->assign('continents', $continents);
  1709. $PAGE->assign('cities', $cities);
  1710. $PAGE->assign('languages', Languages::getAvailableLanguages());
  1711. $PAGE->renderPage('install');
  1712. exit;
  1713. }
  1714. /**
  1715. * Because some f*cking services like flickr require an extra HTTP request to get the thumbnail URL,
  1716. * I have deported the thumbnail URL code generation here, otherwise this would slow down page generation.
  1717. * The following function takes the URL a link (e.g. a flickr page) and return the proper thumbnail.
  1718. * This function is called by passing the URL:
  1719. * http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL]
  1720. * [URL] is the URL of the link (e.g. a flickr page)
  1721. * [HMAC] is the signature for the [URL] (so that these URL cannot be forged).
  1722. * The function below will fetch the image from the webservice and store it in the cache.
  1723. *
  1724. * @param ConfigManager $conf Configuration Manager instance,
  1725. */
  1726. function genThumbnail($conf)
  1727. {
  1728. // Make sure the parameters in the URL were generated by us.
  1729. $sign = hash_hmac('sha256', $_GET['url'], $conf->get('credentials.salt'));
  1730. if ($sign!=$_GET['hmac']) die('Naughty boy!');
  1731. $cacheDir = $conf->get('resource.thumbnails_cache', 'cache');
  1732. // Let's see if we don't already have the image for this URL in the cache.
  1733. $thumbname=hash('sha1',$_GET['url']).'.jpg';
  1734. if (is_file($cacheDir .'/'. $thumbname))
  1735. { // We have the thumbnail, just serve it:
  1736. header('Content-Type: image/jpeg');
  1737. echo file_get_contents($cacheDir .'/'. $thumbname);
  1738. return;
  1739. }
  1740. // We may also serve a blank image (if service did not respond)
  1741. $blankname=hash('sha1',$_GET['url']).'.gif';
  1742. if (is_file($cacheDir .'/'. $blankname))
  1743. {
  1744. header('Content-Type: image/gif');
  1745. echo file_get_contents($cacheDir .'/'. $blankname);
  1746. return;
  1747. }
  1748. // Otherwise, generate the thumbnail.
  1749. $url = $_GET['url'];
  1750. $domain = parse_url($url,PHP_URL_HOST);
  1751. if ($domain=='flickr.com' || endsWith($domain,'.flickr.com'))
  1752. {
  1753. // Crude replacement to handle new flickr domain policy (They prefer www. now)
  1754. $url = str_replace('http://flickr.com/','http://www.flickr.com/',$url);
  1755. // Is this a link to an image, or to a flickr page ?
  1756. $imageurl='';
  1757. if (endsWith(parse_url($url, PHP_URL_PATH), '.jpg'))
  1758. { // This is a direct link to an image. e.g. http://farm1.staticflickr.com/5/5921913_ac83ed27bd_o.jpg
  1759. preg_match('!(http://farm\d+\.staticflickr\.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches);
  1760. if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg';
  1761. }
  1762. else // This is a flickr page (html)
  1763. {
  1764. // Get the flickr html page.
  1765. list($headers, $content) = get_http_response($url, 20);
  1766. if (strpos($headers[0], '200 OK') !== false)
  1767. {
  1768. // flickr now nicely provides the URL of the thumbnail in each flickr page.
  1769. preg_match('!<link rel=\"image_src\" href=\"(.+?)\"!', $content, $matches);
  1770. if (!empty($matches[1])) $imageurl=$matches[1];
  1771. // In albums (and some other pages), the link rel="image_src" is not provided,
  1772. // but flickr provides:
  1773. // <meta property="og:image" content="http://farm4.staticflickr.com/3398/3239339068_25d13535ff_z.jpg" />
  1774. if ($imageurl=='')
  1775. {
  1776. preg_match('!<meta property=\"og:image\" content=\"(.+?)\"!', $content, $matches);
  1777. if (!empty($matches[1])) $imageurl=$matches[1];
  1778. }
  1779. }
  1780. }
  1781. if ($imageurl!='')
  1782. { // Let's download the image.
  1783. // Image is 240x120, so 10 seconds to download should be enough.
  1784. list($headers, $content) = get_http_response($imageurl, 10);
  1785. if (strpos($headers[0], '200 OK') !== false) {
  1786. // Save image to cache.
  1787. file_put_contents($cacheDir .'/'. $thumbname, $content);
  1788. header('Content-Type: image/jpeg');
  1789. echo $content;
  1790. return;
  1791. }
  1792. }
  1793. }
  1794. elseif ($domain=='vimeo.com' )
  1795. {
  1796. // This is more complex: we have to perform a HTTP request, then parse the result.
  1797. // Maybe we should deport this to JavaScript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098
  1798. $vid = substr(parse_url($url,PHP_URL_PATH),1);
  1799. list($headers, $content) = get_http_response('https://vimeo.com/api/v2/video/'.escape($vid).'.php', 5);
  1800. if (strpos($headers[0], '200 OK') !== false) {
  1801. $t = unserialize($content);
  1802. $imageurl = $t[0]['thumbnail_medium'];
  1803. // Then we download the image and serve it to our client.
  1804. list($headers, $content) = get_http_response($imageurl, 10);
  1805. if (strpos($headers[0], '200 OK') !== false) {
  1806. // Save image to cache.
  1807. file_put_contents($cacheDir .'/'. $thumbname, $content);
  1808. header('Content-Type: image/jpeg');
  1809. echo $content;
  1810. return;
  1811. }
  1812. }
  1813. }
  1814. elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
  1815. {
  1816. // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
  1817. // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
  1818. // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
  1819. list($headers, $content) = get_http_response($url, 5);
  1820. if (strpos($headers[0], '200 OK') !== false) {
  1821. // Extract the link to the thumbnail
  1822. preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)"!', $content, $matches);
  1823. if (!empty($matches[1]))
  1824. { // Let's download the image.
  1825. $imageurl=$matches[1];
  1826. // No control on image size, so wait long enough
  1827. list($headers, $content) = get_http_response($imageurl, 20);
  1828. if (strpos($headers[0], '200 OK') !== false) {
  1829. $filepath = $cacheDir .'/'. $thumbname;
  1830. file_put_contents($filepath, $content); // Save image to cache.
  1831. if (resizeImage($filepath))
  1832. {
  1833. header('Content-Type: image/jpeg');
  1834. echo file_get_contents($filepath);
  1835. return;
  1836. }
  1837. }
  1838. }
  1839. }
  1840. }
  1841. elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
  1842. {
  1843. // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
  1844. // http://xkcd.com/327/
  1845. // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
  1846. list($headers, $content) = get_http_response($url, 5);
  1847. if (strpos($headers[0], '200 OK') !== false) {
  1848. // Extract the link to the thumbnail
  1849. preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!', $content, $matches);
  1850. if (!empty($matches[1]))
  1851. { // Let's download the image.
  1852. $imageurl=$matches[1];
  1853. // No control on image size, so wait long enough
  1854. list($headers, $content) = get_http_response($imageurl, 20);
  1855. if (strpos($headers[0], '200 OK') !== false) {
  1856. $filepath = $cacheDir.'/'.$thumbname;
  1857. // Save image to cache.
  1858. file_put_contents($filepath, $content);
  1859. if (resizeImage($filepath))
  1860. {
  1861. header('Content-Type: image/jpeg');
  1862. echo file_get_contents($filepath);
  1863. return;
  1864. }
  1865. }
  1866. }
  1867. }
  1868. }
  1869. else
  1870. {
  1871. // For all other domains, we try to download the image and make a thumbnail.
  1872. // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
  1873. list($headers, $content) = get_http_response($url, 30);
  1874. if (strpos($headers[0], '200 OK') !== false) {
  1875. $filepath = $cacheDir .'/'.$thumbname;
  1876. // Save image to cache.
  1877. file_put_contents($filepath, $content);
  1878. if (resizeImage($filepath))
  1879. {
  1880. header('Content-Type: image/jpeg');
  1881. echo file_get_contents($filepath);
  1882. return;
  1883. }
  1884. }
  1885. }
  1886. // Otherwise, return an empty image (8x8 transparent gif)
  1887. $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
  1888. // Also put something in cache so that this URL is not requested twice.
  1889. file_put_contents($cacheDir .'/'. $blankname, $blankgif);
  1890. header('Content-Type: image/gif');
  1891. echo $blankgif;
  1892. }
  1893. // Make a thumbnail of the image (to width: 120 pixels)
  1894. // Returns true if success, false otherwise.
  1895. function resizeImage($filepath)
  1896. {
  1897. if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
  1898. // Trick: some stupid people rename GIF as JPEG... or else.
  1899. // So we really try to open each image type whatever the extension is.
  1900. $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
  1901. $im=false;
  1902. $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
  1903. $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
  1904. $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
  1905. if (!$im) return false; // Unable to open image (corrupted or not an image)
  1906. $w = imagesx($im);
  1907. $h = imagesy($im);
  1908. $ystart = 0; $yheight=$h;
  1909. if ($h>$w) { $ystart= ($h/2)-($w/2); $yheight=$w/2; }
  1910. $nw = 120; // Desired width
  1911. $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
  1912. // Resize image:
  1913. $im2 = imagecreatetruecolor($nw,$nh);
  1914. imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
  1915. imageinterlace($im2,true); // For progressive JPEG.
  1916. $tempname=$filepath.'_TEMP.jpg';
  1917. imagejpeg($im2, $tempname, 90);
  1918. imagedestroy($im);
  1919. imagedestroy($im2);
  1920. unlink($filepath);
  1921. rename($tempname,$filepath); // Overwrite original picture with thumbnail.
  1922. return true;
  1923. }
  1924. if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=genthumbnail')) { genThumbnail($conf); exit; } // Thumbnail generation/cache does not need the link database.
  1925. if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=dailyrss')) { showDailyRSS($conf); exit; }
  1926. if (!isset($_SESSION['LINKS_PER_PAGE'])) {
  1927. $_SESSION['LINKS_PER_PAGE'] = $conf->get('general.links_per_page', 20);
  1928. }
  1929. try {
  1930. $history = new History($conf->get('resource.history'));
  1931. } catch(Exception $e) {
  1932. die($e->getMessage());
  1933. }
  1934. $linkDb = new LinkDB(
  1935. $conf->get('resource.datastore'),
  1936. $loginManager->isLoggedIn(),
  1937. $conf->get('privacy.hide_public_links'),
  1938. $conf->get('redirector.url'),
  1939. $conf->get('redirector.encode_url')
  1940. );
  1941. $container = new \Slim\Container();
  1942. $container['conf'] = $conf;
  1943. $container['plugins'] = $pluginManager;
  1944. $container['history'] = $history;
  1945. $app = new \Slim\App($container);
  1946. // REST API routes
  1947. $app->group('/api/v1', function() {
  1948. $this->get('/info', '\Shaarli\Api\Controllers\Info:getInfo')->setName('getInfo');
  1949. $this->get('/links', '\Shaarli\Api\Controllers\Links:getLinks')->setName('getLinks');
  1950. $this->get('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:getLink')->setName('getLink');
  1951. $this->post('/links', '\Shaarli\Api\Controllers\Links:postLink')->setName('postLink');
  1952. $this->put('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:putLink')->setName('putLink');
  1953. $this->delete('/links/{id:[\d]+}', '\Shaarli\Api\Controllers\Links:deleteLink')->setName('deleteLink');
  1954. $this->get('/tags', '\Shaarli\Api\Controllers\Tags:getTags')->setName('getTags');
  1955. $this->get('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:getTag')->setName('getTag');
  1956. $this->put('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:putTag')->setName('putTag');
  1957. $this->delete('/tags/{tagName:[\w]+}', '\Shaarli\Api\Controllers\Tags:deleteTag')->setName('deleteTag');
  1958. $this->get('/history', '\Shaarli\Api\Controllers\History:getHistory')->setName('getHistory');
  1959. })->add('\Shaarli\Api\ApiMiddleware');
  1960. $response = $app->run(true);
  1961. // Hack to make Slim and Shaarli router work together:
  1962. // If a Slim route isn't found and NOT API call, we call renderPage().
  1963. if ($response->getStatusCode() == 404 && strpos($_SERVER['REQUEST_URI'], '/api/v1') === false) {
  1964. // We use UTF-8 for proper international characters handling.
  1965. header('Content-Type: text/html; charset=utf-8');
  1966. renderPage($conf, $pluginManager, $linkDb, $history, $sessionManager, $loginManager);
  1967. } else {
  1968. $app->respond($response);
  1969. }