index.php 92 KB

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