index.php 90 KB

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