index.php 89 KB

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