index.php 105 KB

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