X-Git-Url: https://git.immae.eu/?a=blobdiff_plain;f=index.php;h=a9491ed365366f15550ab0ef0b3976a57fb56f71;hb=dcd653d10e168e655ce080da6886ef9fc2c1d3e1;hp=babce3dca8f6aa5b380b1c11775cec37883af557;hpb=9aadcdaefaceec86c0610499e48bc41273f5d26f;p=github%2Fshaarli%2FShaarli.git diff --git a/index.php b/index.php index babce3dc..a9491ed3 100644 --- a/index.php +++ b/index.php @@ -1,5 +1,5 @@ =5 && $minor>=1) return; // 5.1.x or higher is ok. header('Content-Type: text/plain; charset=utf-8'); - echo 'Your server supports php '.$ver.'. Shaarli requires at last php 5.1, and thus cannot run. Sorry.'; + echo 'Your server supports php '.PHP_VERSION.'. Shaarli requires at last php 5.1.0, and thus cannot run. Sorry.'; exit; + } +} + +// Checks if an update is available for Shaarli. +// (at most once a day, and only for registered user.) +// Output: '' = no new version. +// other= the available version. +function checkUpdate() +{ + if (!isLoggedIn()) return ''; // Do not check versions for visitors. + + // Get latest version number at most once a day. + if (!is_file(UPDATECHECK_FILENAME) || (filemtime(UPDATECHECK_FILENAME)links=(file_exists(DATASTORE) ? unserialize(gzinflate(base64_decode(substr(file_get_contents(DATASTORE),strlen(PHPPREFIX),-strlen(PHPSUFFIX))))) : array() ); + // Note that gzinflate is faster than gzuncompress. See: http://www.php.net/manual/en/function.gzdeflate.php#96439 // If user is not logged in, filter private links. if (!$this->loggedin) @@ -483,7 +534,7 @@ class linkdb implements Iterator, Countable, ArrayAccess } // Case insentitive search among links (in url, title and description). Returns filtered list of links. - // eg. print_r($mydb->filterTags('hollandais')); + // eg. print_r($mydb->filterFulltext('hollandais')); public function filterFulltext($searchterms) { // FIXME: explode(' ',$searchterms) and perform a AND search. @@ -502,14 +553,14 @@ class linkdb implements Iterator, Countable, ArrayAccess // Filter by tag. // You can specify one or more tags (tags can be separated by space or comma). // eg. print_r($mydb->filterTags('linux programming')); - public function filterTags($tags) + public function filterTags($tags,$casesensitive=false) { - $t = str_replace(',',' ',strtolower($tags)); + $t = str_replace(',',' ',($casesensitive?$tags:strtolower($tags))); $searchtags=explode(' ',$t); $filtered=array(); foreach($this->links as $l) { - $linktags = explode(' ',strtolower($l['tags'])); + $linktags = explode(' ',($casesensitive?$l['tags']:strtolower($l['tags']))); if (count(array_intersect($linktags,$searchtags)) == count($searchtags)) $filtered[$l['linkdate']] = $l; } @@ -527,8 +578,7 @@ class linkdb implements Iterator, Countable, ArrayAccess if (!empty($tag)) $tags[$tag]=(empty($tags[$tag]) ? 1 : $tags[$tag]+1); arsort($tags); // Sort tags by usage (most used tag first) return $tags; - } - + } } // ------------------------------------------------------------------------------------------ @@ -540,13 +590,13 @@ function showRSS() // Optionnaly filter the results: $linksToDisplay=array(); if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']); - elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags($_GET['searchtags']); + elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags'])); else $linksToDisplay = $LINKSDB; - header('Content-Type: application/xhtml+xml; charset=utf-8'); + header('Content-Type: application/rss+xml; charset=utf-8'); $pageaddr=htmlspecialchars(serverUrl().$_SERVER["SCRIPT_NAME"]); echo ''; - echo 'Shared links on '.$pageaddr.''.$pageaddr.''; + echo ''.htmlspecialchars($GLOBALS['title']).''.$pageaddr.''; echo 'Shared links'.$pageaddr.''."\n\n"; $i=0; $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys(). @@ -554,14 +604,55 @@ function showRSS() { $link = $linksToDisplay[$keys[$i]]; $rfc822date = linkdate2rfc822($link['linkdate']); - echo ''.htmlspecialchars($link['title']).''.htmlspecialchars($link['url']).''.htmlspecialchars($link['url']).''.htmlspecialchars($rfc822date).''; - echo ''."\n"; + echo ''.htmlspecialchars($link['title']).''.htmlspecialchars($link['url']).''.htmlspecialchars($link['url']).''; + if (!HIDE_TIMESTAMPS || isLoggedIn()) echo ''.htmlspecialchars($rfc822date).''; + echo ''."\n"; $i++; } echo ''; exit; } +// ------------------------------------------------------------------------------------------ +// Ouput the last 50 links in ATOM format. +function showATOM() +{ + global $LINKSDB; + + // Optionnaly filter the results: + $linksToDisplay=array(); + if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']); + elseif (!empty($_GET['searchtags'])) $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags'])); + else $linksToDisplay = $LINKSDB; + + header('Content-Type: application/atom+xml; charset=utf-8'); + $pageaddr=htmlspecialchars(serverUrl().$_SERVER["SCRIPT_NAME"]); + $latestDate = ''; + $entries=''; + $i=0; + $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; } // No, I can't use array_keys(). + while ($i<50 && $i'.htmlspecialchars($link['url']).''; + if (!HIDE_TIMESTAMPS || isLoggedIn()) $entries.=''.htmlspecialchars($iso8601date).''; + $entries.=''.nl2br(htmlspecialchars($link['description'])).''."\n"; + $i++; + } + $feed=''; + $feed.=''.htmlspecialchars($GLOBALS['title']).''; + if (!HIDE_TIMESTAMPS || isLoggedIn()) $feed.=''.htmlspecialchars($latestDate).''; + $feed.=''; + $feed.=''.htmlspecialchars($pageaddr).''; + $feed.=''.htmlspecialchars($pageaddr).''."\n\n"; // Yes, I know I should use a real IRI (RFC3987), but the site URL will do. + $feed.=$entries; + $feed.=''; + echo $feed; + exit; +} + // ------------------------------------------------------------------------------------------ // Render HTML page: function renderPage() @@ -584,13 +675,13 @@ function renderPage() exit; } $returnurl_html = (isset($_SERVER['HTTP_REFERER']) ? '' : ''); - $loginform='
Login:    Password : '.$returnurl_html.'
'; + $loginform='
Login:    Password :
'; + $loginform.=''.$returnurl_html.'
'; $onload = 'onload="document.loginform.login.focus();"'; $data = array('pageheader'=>$loginform,'body'=>'','onload'=>$onload); templatePage($data); exit; } - // -------- User wants to logout. if (startswith($_SERVER["QUERY_STRING"],'do=logout')) { @@ -598,7 +689,29 @@ function renderPage() logout(); header('Location: ?'); exit; - } + } + + // -------- Tag cloud + if (startswith($_SERVER["QUERY_STRING"],'do=tagcloud')) + { + $tags= $LINKSDB->allTags(); + // We sort tags alphabetically, then choose a font size according to count. + // First, find max value. + $maxcount=0; foreach($tags as $key=>$value) $maxcount=max($maxcount,$value); + ksort($tags); + $cloud=''; + foreach($tags as $key=>$value) + { + $size = max(40*$value/$maxcount,8); // Minimum size 8. + $colorvalue = 128-ceil(127*$value/$maxcount); + $color='rgb('.$colorvalue.','.$colorvalue.','.$colorvalue.')'; + $cloud.= ''.$value.''.htmlspecialchars($key).' '; + } + $cloud='
'.$cloud.'
'; + $data = array('pageheader'=>'','body'=>$cloud,'onload'=>''); + templatePage($data); + exit; + } // -------- User clicks on a tag in a link: The tag is added to the list of searched tags (searchtags=...) if (isset($_GET['addtag'])) @@ -606,7 +719,7 @@ function renderPage() // Get previous URL (http_referer) and add the tag to the searchtags parameters in query. if (empty($_SERVER['HTTP_REFERER'])) { header('Location: ?searchtags='.urlencode($_GET['addtag'])); exit; } // In case browser does not send HTTP_REFERER parse_str(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_QUERY), $params); - $params['searchtags'] = (empty($params['searchtags']) ? trim($_GET['addtag']) : trim($params['searchtags'].' '.urlencode($_GET['addtag']))); + $params['searchtags'] = (empty($params['searchtags']) ? trim($_GET['addtag']) : trim($params['searchtags']).' '.urlencode(trim($_GET['addtag']))); unset($params['page']); // We also remove page (keeping the same page has no sense, since the results are different) header('Location: ?'.http_build_query($params)); exit; @@ -645,7 +758,7 @@ function renderPage() // Show login screen, then redirect to ?post=... if (isset($_GET['post'])) { - header('Location: ?do=login&post='.urlencode($_GET['post']).(isset($_GET['source'])?'&source='.urlencode($_GET['source']):'')); // Redirect to login page, then back to post link. + header('Location: ?do=login&post='.urlencode($_GET['post']).(isset($_GET['title'])?'&title='.urlencode($_GET['title']):'').(isset($_GET['source'])?'&source='.urlencode($_GET['source']):'')); // Redirect to login page, then back to post link. exit; } @@ -653,13 +766,12 @@ function renderPage() $searchform=<<
-
+
HTML; - $onload = 'document.searchform.searchterm.focus();'; - $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload); + $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>''); templatePage($data); - exit; // Never remove this one ! + exit; // Never remove this one ! All operations below are reserved for logged in user. } // -------- All other functions are reserved for the registered user: @@ -669,8 +781,12 @@ HTML; { $pageabsaddr=serverUrl().$_SERVER["SCRIPT_NAME"]; // Why doesn't php have a built-in function for that ? // The javascript code for the bookmarklet: + $changepwd = (OPEN_SHAARLI ? '' : 'Change password - Change your password.

' ); $toolbar= <<
+ {$changepwd} + Configure your Shaarli - Change Title, timezone...

+ Rename/delete tags - Rename or delete a tag in all links.

Import - Import Netscape html bookmarks (as exported from Firefox, Chrome, Opera, delicious...)

Export - Export Netscape html bookmarks (which can be imported in Firefox, Chrome, Opera, delicious...)

Shaare link - Drag this link to your bookmarks toolbar (or right-click it and choose Bookmark This Link....). Then click "Shaare link" button in any page you want to share.

@@ -680,11 +796,138 @@ HTML; templatePage($data); exit; } + + // -------- User wants to change his/her password. + if (startswith($_SERVER["QUERY_STRING"],'do=changepasswd')) + { + if (OPEN_SHAARLI) die('You are not supposed to change a password on an Open Shaarli.'); + if (!empty($_POST['setpassword']) && !empty($_POST['oldpassword'])) + { + if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away ! + + // Make sure old password is correct. + $oldhash = sha1($_POST['oldpassword'].$GLOBALS['login'].$GLOBALS['salt']); + if ($oldhash!=$GLOBALS['hash']) { echo ''; exit; } + // Save new password + $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless. + $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']); + writeConfig(); + echo ''; + exit; + } + else + { + $token = getToken(); + $changepwdform= << +Old password:     +New password: + + +HTML; + $data = array('pageheader'=>$changepwdform,'body'=>'','onload'=>'onload="document.changepasswordform.oldpassword.focus();"'); + templatePage($data); + exit; + } + } + + // -------- User wants to change configuration + if (startswith($_SERVER["QUERY_STRING"],'do=configure')) + { + if (!empty($_POST['title']) ) + { + if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away ! + $tz = 'UTC'; + if (!empty($_POST['continent']) && !empty($_POST['city'])) + if (isTZvalid($_POST['continent'],$_POST['city'])) + $tz = $_POST['continent'].'/'.$_POST['city']; + $GLOBALS['timezone'] = $tz; + $GLOBALS['title']=$_POST['title']; + writeConfig(); + echo ''; + exit; + } + else + { + $token = getToken(); + $title = htmlspecialchars( empty($GLOBALS['title']) ? '' : $GLOBALS['title'] , ENT_QUOTES); + list($timezone_form,$timezone_js) = templateTZform($GLOBALS['timezone']); + $timezone_html=''; if ($timezone_form!='') $timezone_html='Timezone:'.$timezone_form.''; + $changepwdform= << + + +{$timezone_html} + +
Page title:
+ +HTML; + $data = array('pageheader'=>$changepwdform,'body'=>'','onload'=>'onload="document.configform.title.focus();"'); + templatePage($data); + exit; + } + } + + // -------- User wants to rename a tag or delete it + if (startswith($_SERVER["QUERY_STRING"],'do=changetag')) + { + if (empty($_POST['fromtag'])) + { + $token = getToken(); + $changetagform = << + +Tag: + +  or 
(Case sensitive) + +HTML; + $data = array('pageheader'=>$changetagform,'body'=>'','onload'=>'onload="document.changetag.fromtag.focus();"'); + templatePage($data); + exit; + } + if (!tokenOk($_POST['token'])) die('Wrong token.'); + + if (!empty($_POST['deletetag']) && !empty($_POST['fromtag'])) + { + $needle=trim($_POST['fromtag']); + $linksToAlter = $LINKSDB->filterTags($needle,true); // true for case-sensitive tag search. + foreach($linksToAlter as $key=>$value) + { + $tags = explode(' ',trim($value['tags'])); + unset($tags[array_search($needle,$tags)]); // Remove tag. + $value['tags']=trim(implode(' ',$tags)); + $LINKSDB[$key]=$value; + } + $LINKSDB->savedb(); // save to disk + invalidateCaches(); + echo ''; + exit; + } + + // Rename a tag: + if (!empty($_POST['renametag']) && !empty($_POST['fromtag']) && !empty($_POST['totag'])) + { + $needle=trim($_POST['fromtag']); + $linksToAlter = $LINKSDB->filterTags($needle,true); // true for case-sensitive tag search. + foreach($linksToAlter as $key=>$value) + { + $tags = explode(' ',trim($value['tags'])); + $tags[array_search($needle,$tags)] = trim($_POST['totag']); // Remplace tags value. + $value['tags']=trim(implode(' ',$tags)); + $LINKSDB[$key]=$value; + } + $LINKSDB->savedb(); // save to disk + invalidateCaches(); + echo ''; + exit; + } + } // -------- User wants to add a link without using the bookmarklet: show form. if (startswith($_SERVER["QUERY_STRING"],'do=addlink')) { - $onload = 'document.addform.post.focus();'; + $onload = 'onload="document.addform.post.focus();"'; $addform= '
'; $data = array('pageheader'=>$addform,'body'=>'','onload'=>$onload); templatePage($data); @@ -695,9 +938,10 @@ HTML; if (isset($_POST['save_edit'])) { if (!tokenOk($_POST['token'])) die('Wrong token.'); // Go away ! + $tags = trim(preg_replace('/\s\s+/',' ', $_POST['lf_tags'])); // Remove multiple spaces. $linkdate=$_POST['lf_linkdate']; $link = array('title'=>trim($_POST['lf_title']),'url'=>trim($_POST['lf_url']),'description'=>trim($_POST['lf_description']),'private'=>(isset($_POST['lf_private']) ? 1 : 0), - 'linkdate'=>$linkdate,'tags'=>trim($_POST['lf_tags'])); + 'linkdate'=>$linkdate,'tags'=>str_replace(',',' ',$tags)); if ($link['title']=='') $link['title']=$link['url']; // If title is empty, use the URL as title. $LINKSDB[$linkdate] = $link; $LINKSDB->savedb(); // save to disk @@ -854,12 +1098,12 @@ HTML;
Import Netscape html bookmarks (as exported from Firefox/Chrome/Opera/delicious/diigo...) (Max: {$maxfilesize} bytes). - +
-  Import all links as private
-  Overwrite existing links +  Import all links as private
+  Overwrite existing links
HTML; @@ -872,11 +1116,10 @@ HTML; $searchform=<<
-
+
HTML; - $onload = 'document.searchform.searchterm.focus();'; - $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>$onload); + $data = array('pageheader'=>$searchform,'body'=>templateLinkList(),'onload'=>''); templatePage($data); exit; } @@ -999,13 +1242,13 @@ function templateLinkList() $searched=''; if (!empty($_GET['searchterm'])) // Fulltext search { - $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']); - $searched=' '.count($linksToDisplay).' results for '.htmlspecialchars($_GET['searchterm']).':'; + $linksToDisplay = $LINKSDB->filterFulltext(trim($_GET['searchterm'])); + $searched=' '.count($linksToDisplay).' results for '.htmlspecialchars(trim($_GET['searchterm'])).':'; } elseif (!empty($_GET['searchtags'])) // Search by tag { - $linksToDisplay = $LINKSDB->filterTags($_GET['searchtags']); - $tagshtml=''; foreach(explode(' ',$_GET['searchtags']) as $tag) $tagshtml.=''.htmlspecialchars($tag).' x '; + $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags'])); + $tagshtml=''; foreach(explode(' ',trim($_GET['searchtags'])) as $tag) $tagshtml.=''.htmlspecialchars($tag).' x '; $searched=' '.count($linksToDisplay).' results for tags '.$tagshtml.':'; } else @@ -1036,9 +1279,11 @@ function templateLinkList() if (isLoggedIn()) $actions='
'; $tags=''; if ($link['tags']!='') foreach(explode(' ',$link['tags']) as $tag) { $tags.=''.htmlspecialchars($tag).' '; } - $linklist.='
  • '.htmlspecialchars($title).''.$actions.'
    '; + $linklist.='
  • '.thumbnail($link['url']); + $linklist.='
  • \n"; + if (!HIDE_TIMESTAMPS || isLoggedIn()) $linklist.=''.htmlspecialchars(linkdate2locale($link['linkdate'])).' - '; + $linklist.=''.htmlspecialchars($link['url']).'
    '.$tags."\n"; $i++; } @@ -1059,6 +1304,62 @@ HTML; return $linklist; } +// Returns the HTML code to display a thumbnail for a link. +// Understands various services (youtube.com...) +function thumbnail($url) +{ + if (!ENABLE_THUMBNAILS) return ''; + + // For most hosts, the URL of the thumbnail can be easily deduced from the URL of the link. + // (eg. http://www.youtube.com/watch?v=spVypYk4kto ---> http://img.youtube.com/vi/spVypYk4kto/2.jpg ) + // ^^^^^^^^^^^ ^^^^^^^^^^^ + $domain = parse_url($url,PHP_URL_HOST); + if ($domain=='youtube.com' || $domain=='www.youtube.com') + { + parse_str(parse_url($url,PHP_URL_QUERY), $params); // Extract video ID and get thumbnail + if (!empty($params['v'])) return '
    '; + } + if ($domain=='imgur.com') + { + $path = parse_url($url,PHP_URL_PATH); + if (substr_count($path,'/')==1) return '
    '; + } + if ($domain=='i.imgur.com') + { + $pi = pathinfo(parse_url($url,PHP_URL_PATH)); + if (!empty($pi['filename'])) return '
    '; + } + if ($domain=='dailymotion.com' || $domain=='www.dailymotion.com') + { + if (strpos($url,'dailymotion.com/video/')) + { + $thumburl=str_replace('dailymotion.com/video/','dailymotion.com/thumbnail/video/',$url); + return '
    '; + } + } + if (endsWith($domain,'.imageshack.us')) + { + $ext=strtolower(pathinfo($url,PATHINFO_EXTENSION)); + if ($ext=='jpg' || $ext=='jpeg' || $ext=='png' || $ext=='gif') + { + $thumburl = substr($url,0,strlen($url)-strlen($ext)).'th.'.$ext; + return '
    '; + } + } + + // Some other hosts are SLOW AS HELL and usually require an extra HTTP request to get the thumbnail URL. + // So we deport the thumbnail generation in order not to slow down page generation + // (and we also cache the thumbnail) + if ($domain=='flickr.com' || endsWith($domain,'.flickr.com') || $domain=='vimeo.com') + { + $sign = hash_hmac('sha256', $url, $GLOBALS['salt']); // We use the salt to sign data (it's random, secret, and specific to each installation) + return '
    '; + } + + return ''; // No thumbnail. + +} + // ----------------------------------------------------------------------------------------------- // Template for the whole page. /* Input: $data (associative array). @@ -1071,6 +1372,9 @@ function templatePage($data) global $STARTTIME; global $LINKSDB; $shaarli_version = shaarli_version; + + $newversion=checkUpdate(); + if ($newversion!='') $newversion='
    Shaarli '.htmlspecialchars($newversion).' is available.
    '; $linkcount = count($LINKSDB); $open=''; if (OPEN_SHAARLI) @@ -1079,7 +1383,8 @@ function templatePage($data) $open='Open '; } else - $menu=(isLoggedIn() ? ' Logout  Tools  Add link' : ' Login'); + $menu=(isLoggedIn() ? ' Logout  Tools  Add link' : ' Login'); + foreach(array('pageheader','body','onload') as $k) // make sure all required fields exist (put an empty string if not). { if (!array_key_exists($k,$data)) $data[$k]=''; @@ -1088,29 +1393,36 @@ function templatePage($data) if (OPEN_SHAARLI || isLoggedIn()) { $jsincludes=''; - $source = serverUrl().$_SERVER['SCRIPT_NAME'].'?ws=tags'; + $source = serverUrl().$_SERVER['SCRIPT_NAME']; $jsincludes_bottom = << + + $('#lf_tags').autocomplete({source:'{$source}?ws=tags',minLength:1}); + $('#searchtags').autocomplete({source:'{$source}?ws=tags',minLength:1}); + $('#fromtag').autocomplete({source:'{$source}?ws=singletag',minLength:1}); +}); + JS; } - $feedurl=htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME'].'?do=rss'); + $feedurl=htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME']); + if (!empty($_GET['searchtags'])) $feedurl.='&searchtags='.$_GET['searchtags']; + elseif (!empty($_GET['searchterm'])) $feedurl.='&searchterm='.$_GET['searchterm']; + + $title = htmlspecialchars( $GLOBALS['title'] ); echo << -{$open}Shaarli - Let's shaare your links... +{$title} {$jsincludes} - +{$newversion} {$data['body']} @@ -1131,39 +1443,104 @@ function install() if (!empty($_POST['setlogin']) && !empty($_POST['setpassword'])) { - $tz=(empty($_POST['settimezone']) ? 'UTC':$_POST['settimezone']); + $tz = 'UTC'; + if (!empty($_POST['continent']) && !empty($_POST['city'])) + if (isTZvalid($_POST['continent'],$_POST['city'])) + $tz = $_POST['continent'].'/'.$_POST['city']; + $GLOBALS['timezone'] = $tz; // Everything is ok, let's create config file. - $salt=sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless. - $hash = sha1($_POST['setpassword'].$_POST['setlogin'].$salt); - $config=''; - if (!file_put_contents(CONFIG_FILE,$config) || strcmp(file_get_contents(CONFIG_FILE),$config)!=0) - { - echo ''; - exit; - } + $GLOBALS['login'] = $_POST['setlogin']; + $GLOBALS['salt'] = sha1(uniqid('',true).'_'.mt_rand()); // Salt renders rainbow-tables attacks useless. + $GLOBALS['hash'] = sha1($_POST['setpassword'].$GLOBALS['login'].$GLOBALS['salt']); + $GLOBALS['title'] = (empty($_POST['title']) ? 'Shared links on '.htmlspecialchars(serverUrl().$_SERVER['SCRIPT_NAME']) : $_POST['title'] ); + writeConfig(); echo ''; exit; - } - // Display config form: - $timezoneselect=''; - if (function_exists('timezone_identifiers_list')) // because of old php version (5.1) which can be found on free.fr - { - $timezones=''; - foreach(timezone_identifiers_list() as $tz) $timezones.='\n"; - $timezoneselect='Timezone:

    '; } + + // Display config form: + list($timezone_form,$timezone_js) = templateTZform(); + $timezone_html=''; if ($timezone_form!='') $timezone_html='Timezone:'.$timezone_form.''; echo <<Shaarli - Configuration -

    Shaarli - Shaare your links...

    -It looks like it's the first time you run Shaarli. Please chose a login/password and a timezone:
    -
    -Login:

    Password:

    -{$timezoneselect} -
    +Shaarli - Configuration${timezone_js} +

    Shaarli - Shaare your links...

    +It looks like it's the first time you run Shaarli. Please configure it:
    +
    + + + +{$timezone_html} + + +
    Login:
    Password:
    Page title:
    +
    HTML; exit; } +// Generates the timezone selection form and javascript. +// Input: (optional) current timezone (can be 'UTC/UTC'). It will be pre-selected. +// Output: array(html,js) +// Example: list($htmlform,$js) = templateTZform('Europe/Paris'); // Europe/Paris pre-selected. +// Returns array('','') if server does not support timezones list. (eg. php 5.1 on free.fr) +function templateTZform($ptz=false) +{ + if (function_exists('timezone_identifiers_list')) // because of old php version (5.1) which can be found on free.fr + { + // Try to split the provided timezone. + if ($ptz==false) { $l=timezone_identifiers_list(); $ptz=$l[0]; } + $spos=strpos($ptz,'/'); $pcontinent=substr($ptz,0,$spos); $pcity=substr($ptz,$spos+1); + + // Display config form: + $timezone_form = ''; + $timezone_js = ''; + // The list is in the forme "Europe/Paris", "America/Argentina/Buenos_Aires"... + // We split the list in continents/cities. + $continents = array(); + $cities = array(); + foreach(timezone_identifiers_list() as $tz) + { + if ($tz=='UTC') $tz='UTC/UTC'; + $spos = strpos($tz,'/'); + if ($spos) + { + $continent=substr($tz,0,$spos); $city=substr($tz,$spos+1); + $continents[$continent]=1; + if (!isset($cities[$continent])) $cities[$continent]=array(); + $cities[$continent].=''; + } + } + $continents_html = ''; + $continents = array_keys($continents); + foreach($continents as $continent) + $continents_html.=''; + $cities_html = $cities[$pcontinent]; + $timezone_form = "Continent:

    "; + $timezone_form .= "City:

    "; + $timezone_js = "" ; + return array($timezone_form,$timezone_js); + } + return array('',''); +} + +// Tells if a timezone is valid or not. +// If not valid, returns false. +// If system does not support timezone list, returns false. +function isTZvalid($continent,$city) +{ + $tz = $continent.'/'.$city; + if (function_exists('timezone_identifiers_list')) // because of old php version (5.1) which can be found on free.fr + { + if (in_array($tz, timezone_identifiers_list())) // it's a valid timezone ? + return true; + } + return false; +} + + // Webservices (for use with jQuery/jQueryUI) // eg. index.php?ws=tags&term=minecr function processWS() @@ -1173,21 +1550,157 @@ function processWS() global $LINKSDB; header('Content-Type: application/json; charset=utf-8'); - // Search in tags + // Search in tags (case insentitive, cumulative search) if ($_GET['ws']=='tags') { - $tags=explode(' ',$term); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d") + $tags=explode(' ',str_replace(',',' ',$term)); $last = array_pop($tags); // Get the last term ("a b c d" ==> "a b c", "d") $addtags=''; if ($tags) $addtags=implode(' ',$tags).' '; // We will pre-pend previous tags $suggested=array(); /* To speed up things, we store list of tags in session */ if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags(); foreach($_SESSION['tags'] as $key=>$value) { - if (startsWith($key,$last,$case=false)) $suggested[$addtags.$key.' ']=0; + if (startsWith($key,$last,$case=false) && !in_array($key,$tags)) $suggested[$addtags.$key.' ']=0;//FIXME } echo json_encode(array_keys($suggested)); exit; } + + // Search a single tag (case sentitive, single tag search) + if ($_GET['ws']=='singletag') + { + /* To speed up things, we store list of tags in session */ + if (empty($_SESSION['tags'])) $_SESSION['tags'] = $LINKSDB->allTags(); + foreach($_SESSION['tags'] as $key=>$value) + { + if (startsWith($key,$term,$case=true)) $suggested[$key]=0; + } + echo json_encode(array_keys($suggested)); + exit; + } +} + +// Re-write configuration file according to globals. +// Requires some $GLOBALS to be set (login,hash,salt,title). +// If the config file cannot be saved, an error message is dislayed and the user is redirected to "Tools" menu. +// (otherwise, the function simply returns.) +function writeConfig() +{ + if (is_file(CONFIG_FILE) && !isLoggedIn()) die('You are not authorized to alter config.'); // Only logged in user can alter config. + $config=''; + if (!file_put_contents(CONFIG_FILE,$config) || strcmp(file_get_contents(CONFIG_FILE),$config)!=0) + { + echo ''; + exit; + } +} + +/* Because some f*cking services like Flickr require an extra HTTP request to get the thumbnail URL, + I have deported the thumbnail URL code generation here, otherwise this would slow down page generation. + The following function takes the URL a link (eg. a flickr page) and return the proper thumbnail. + This function is called by passing the url: + http://mywebsite.com/shaarli/?do=genthumbnail&hmac=[HMAC]&url=[URL] + [URL] is the URL of the link (eg. a flickr page) + [HMAC] is the signature for the [URL] (so that these URL cannot be forged). + The function below will fetch the image from the webservice and store it in the cache. +*/ +function genThumbnail() +{ + // Make sure the parameters in the URL were generated by us. + $sign = hash_hmac('sha256', $_GET['url'], $GLOBALS['salt']); + if ($sign!=$_GET['hmac']) die('Naughty boy !'); + + // Let's see if we don't already have the image for this URL in the cache. + $thumbname=hash('sha1',$_GET['url']).'.jpg'; + if (is_file(CACHEDIR.'/'.$thumbname)) + { // We have the thumbnail, just serve it: + header('Content-Type: image/jpeg'); + echo file_get_contents(CACHEDIR.'/'.$thumbname); + return; + } + // We may also serve a blank image (if service did not respond) + $blankname=hash('sha1',$_GET['url']).'.gif'; + if (is_file(CACHEDIR.'/'.$blankname)) + { + header('Content-Type: image/gif'); + echo file_get_contents(CACHEDIR.'/'.$blankname); + return; + } + + // Otherwise, generate the thumbnail. + $url = $_GET['url']; + $domain = parse_url($url,PHP_URL_HOST); + + if ($domain=='flickr.com' || endsWith($domain,'.flickr.com')) + { + // WTF ? I need a flickr API key to get a fucking thumbnail ? No way. + // I'll extract the thumbnail URL myself. First, we have to get the flickr HTML page. + // All images in Flickr are in the form: + // http://farm[farm].static.flickr.com/[server]/[id]_[secret]_[size].jpg + // Example: http://farm7.static.flickr.com/6205/6088513739_fc158467fe_z.jpg + // We want the 240x120 format, which is _m.jpg. + // We search for the first image in the page which does not have the _s size, + // when use the _m to get the thumbnail. + + // Is this a link to an image, or to a flickr page ? + $imageurl=''; + logm('url: '.$url); + if (endswith(parse_url($url,PHP_URL_PATH),'.jpg')) + { // This is a direct link to an image. eg. http://farm1.static.flickr.com/5/5921913_ac83ed27bd_o.jpg + preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)\w.jpg!',$url,$matches); + if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg'; + } + else // this is a flickr page (html) + { + list($httpstatus,$headers,$data) = getHTTP($url,20); // Get the flickr html page. + if (strpos($httpstatus,'200 OK')) + { + preg_match('!(http://farm\d+.static.flickr.com/\d+/\d+_\w+_)[^s].jpg!',$data,$matches); + if (!empty($matches[1])) $imageurl=$matches[1].'m.jpg'; + } + } + if ($imageurl!='') + { // Let's download the image. + list($httpstatus,$headers,$data) = getHTTP($imageurl,10); // Image is 240x120, so 10 seconds to download should be enough. + if (strpos($httpstatus,'200 OK')) + { + file_put_contents(CACHEDIR.'/'.$thumbname,$data); // Save image to cache. + header('Content-Type: image/jpeg'); + echo $data; + return; + } + } + else logm('unkown flickr url: '.$url); + } + + if ($domain=='vimeo.com' ) + { + // This is more complex: we have to perform a HTTP request, then parse the result. + // Maybe we should deport this to javascript ? Example: http://stackoverflow.com/questions/1361149/get-img-thumbnails-from-vimeo/4285098#4285098 + $vid = substr(parse_url($url,PHP_URL_PATH),1); + list($httpstatus,$headers,$data) = getHTTP('http://vimeo.com/api/v2/video/'.htmlspecialchars($vid).'.php',5); + if (strpos($httpstatus,'200 OK')) + { + $t = unserialize($data); + $imageurl = $t[0]['thumbnail_medium']; + // Then we download the image and serve it to our client. + list($httpstatus,$headers,$data) = getHTTP($imageurl,10); + if (strpos($httpstatus,'200 OK')) + { + file_put_contents(CACHEDIR.'/'.$thumbname,$data); // Save image to cache. + header('Content-Type: image/jpeg'); + echo $data; + return; + } + } + } + + // Otherwise, return an empty image (8x8 transparent gif) + $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7'); + file_put_contents(CACHEDIR.'/'.$blankname,$blankgif); // Also put something in cache so that this URL is not requested twice. + header('Content-Type: image/gif'); + echo $blankgif; } // Invalidate caches when the database is changed or the user logs out. @@ -1197,9 +1710,11 @@ function invalidateCaches() unset($_SESSION['tags']); } +if (startswith($_SERVER["QUERY_STRING"],'do=genthumbnail')) { genThumbnail(); exit; } // Thumbnail generation/cache does not need the link database. $LINKSDB=new linkdb(isLoggedIn() || OPEN_SHAARLI); // Read links from database (and filter private links if used it not logged in). if (startswith($_SERVER["QUERY_STRING"],'ws=')) { processWS(); exit; } // Webservices (for jQuery/jQueryUI) if (!isset($_SESSION['LINKS_PER_PAGE'])) $_SESSION['LINKS_PER_PAGE']=LINKS_PER_PAGE; if (startswith($_SERVER["QUERY_STRING"],'do=rss')) { showRSS(); exit; } +if (startswith($_SERVER["QUERY_STRING"],'do=atom')) { showATOM(); exit; } renderPage(); ?> \ No newline at end of file