index.php 92 KB

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