index.php 90 KB

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