index.php 91 KB

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