index.php 92 KB

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