+// 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($GLOBALS['config']['CONFIG_FILE']) && !isLoggedIn()) die('You are not authorized to alter config.'); // Only logged in user can alter config.
+ if (empty($GLOBALS['redirector'])) $GLOBALS['redirector']='';
+ $config='<?php $GLOBALS[\'login\']='.var_export($GLOBALS['login'],true).'; $GLOBALS[\'hash\']='.var_export($GLOBALS['hash'],true).'; $GLOBALS[\'salt\']='.var_export($GLOBALS['salt'],true).'; ';
+ $config .='$GLOBALS[\'timezone\']='.var_export($GLOBALS['timezone'],true).'; date_default_timezone_set('.var_export($GLOBALS['timezone'],true).'); $GLOBALS[\'title\']='.var_export($GLOBALS['title'],true).';';
+ $config .= '$GLOBALS[\'redirector\']='.var_export($GLOBALS['redirector'],true).'; ';
+ $config .= ' ?>';
+ if (!file_put_contents($GLOBALS['config']['CONFIG_FILE'],$config) || strcmp(file_get_contents($GLOBALS['config']['CONFIG_FILE']),$config)!=0)
+ {
+ echo '<script language="JavaScript">alert("Shaarli could not create the config file. Please make sure Shaarli has the right to write in the folder is it installed in.");document.location=\'?\';</script>';
+ 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($GLOBALS['config']['CACHEDIR'].'/'.$thumbname))
+ { // We have the thumbnail, just serve it:
+ header('Content-Type: image/jpeg');
+ echo file_get_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname);
+ return;
+ }
+ // We may also serve a blank image (if service did not respond)
+ $blankname=hash('sha1',$_GET['url']).'.gif';
+ if (is_file($GLOBALS['config']['CACHEDIR'].'/'.$blankname))
+ {
+ header('Content-Type: image/gif');
+ echo file_get_contents($GLOBALS['config']['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='';
+ 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')!==false)
+ {
+ 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')!==false)
+ {
+ file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname,$data); // Save image to cache.
+ header('Content-Type: image/jpeg');
+ echo $data;
+ return;
+ }
+ }
+ }
+
+ elseif ($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')!==false)
+ {
+ $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')!==false)
+ {
+ file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$thumbname,$data); // Save image to cache.
+ header('Content-Type: image/jpeg');
+ echo $data;
+ return;
+ }
+ }
+ }
+
+ elseif ($domain=='ted.com' || endsWith($domain,'.ted.com'))
+ {
+ // The thumbnail for TED talks is located in the <link rel="image_src" [...]> tag on that page
+ // http://www.ted.com/talks/mikko_hypponen_fighting_viruses_defending_the_net.html
+ // <link rel="image_src" href="http://images.ted.com/images/ted/28bced335898ba54d4441809c5b1112ffaf36781_389x292.jpg" />
+ list($httpstatus,$headers,$data) = getHTTP($url,5);
+ if (strpos($httpstatus,'200 OK')!==false)
+ {
+ // Extract the link to the thumbnail
+ preg_match('!link rel="image_src" href="(http://images.ted.com/images/ted/.+_\d+x\d+\.jpg)[^s]!',$data,$matches);
+ if (!empty($matches[1]))
+ { // Let's download the image.
+ $imageurl=$matches[1];
+ list($httpstatus,$headers,$data) = getHTTP($imageurl,20); // No control on image size, so wait long enough.
+ if (strpos($httpstatus,'200 OK')!==false)
+ {
+ $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname;
+ file_put_contents($filepath,$data); // Save image to cache.
+ if (resizeImage($filepath))
+ {
+ header('Content-Type: image/jpeg');
+ echo file_get_contents($filepath);
+ return;
+ }
+ }
+ }
+ }
+ }
+
+ elseif ($domain=='xkcd.com' || endsWith($domain,'.xkcd.com'))
+ {
+ // There is no thumbnail available for xkcd comics, so download the whole image and resize it.
+ // http://xkcd.com/327/
+ // <img src="http://imgs.xkcd.com/comics/exploits_of_a_mom.png" title="<BLABLA>" alt="<BLABLA>" />
+ list($httpstatus,$headers,$data) = getHTTP($url,5);
+ if (strpos($httpstatus,'200 OK')!==false)
+ {
+ // Extract the link to the thumbnail
+ preg_match('!<img src="(http://imgs.xkcd.com/comics/.*)" title="[^s]!',$data,$matches);
+ if (!empty($matches[1]))
+ { // Let's download the image.
+ $imageurl=$matches[1];
+ list($httpstatus,$headers,$data) = getHTTP($imageurl,20); // No control on image size, so wait long enough.
+ if (strpos($httpstatus,'200 OK')!==false)
+ {
+ $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname;
+ file_put_contents($filepath,$data); // Save image to cache.
+ if (resizeImage($filepath))
+ {
+ header('Content-Type: image/jpeg');
+ echo file_get_contents($filepath);
+ return;
+ }
+ }
+ }
+ }
+ }
+
+ else
+ {
+ // For all other domains, we try to download the image and make a thumbnail.
+ list($httpstatus,$headers,$data) = getHTTP($url,30); // We allow 30 seconds max to download (and downloads are limited to 4 Mb)
+ if (strpos($httpstatus,'200 OK')!==false)
+ {
+ $filepath=$GLOBALS['config']['CACHEDIR'].'/'.$thumbname;
+ file_put_contents($filepath,$data); // Save image to cache.
+ if (resizeImage($filepath))
+ {
+ header('Content-Type: image/jpeg');
+ echo file_get_contents($filepath);
+ return;
+ }
+ }
+ }
+
+
+ // Otherwise, return an empty image (8x8 transparent gif)
+ $blankgif = base64_decode('R0lGODlhCAAIAIAAAP///////yH5BAEKAAEALAAAAAAIAAgAAAIHjI+py+1dAAA7');
+ file_put_contents($GLOBALS['config']['CACHEDIR'].'/'.$blankname,$blankgif); // Also put something in cache so that this URL is not requested twice.
+ header('Content-Type: image/gif');
+ echo $blankgif;
+}
+
+// Make a thumbnail of the image (to width: 120 pixels)
+// Returns true if success, false otherwise.
+function resizeImage($filepath)
+{
+ if (!function_exists('imagecreatefromjpeg')) return false; // GD not present: no thumbnail possible.
+
+ // Trick: some stupid people rename GIF as JPEG... or else.
+ // So we really try to open each image type whatever the extension is.
+ $header=file_get_contents($filepath,false,NULL,0,256); // Read first 256 bytes and try to sniff file type.
+ $im=false;
+ $i=strpos($header,'GIF8'); if (($i!==false) && ($i==0)) $im = imagecreatefromgif($filepath); // Well this is crude, but it should be enough.
+ $i=strpos($header,'PNG'); if (($i!==false) && ($i==1)) $im = imagecreatefrompng($filepath);
+ $i=strpos($header,'JFIF'); if ($i!==false) $im = imagecreatefromjpeg($filepath);
+ if (!$im) return false; // Unable to open image (corrupted or not an image)
+ $w = imagesx($im);
+ $h = imagesy($im);
+ $ystart = 0; $yheight=$h;
+ if ($h>$w) { $ystart= ($h/2)-($w/2); $yheight=$w/2; }
+ $nw = 120; // Desired width
+ $nh = min(floor(($h*$nw)/$w),120); // Compute new width/height, but maximum 120 pixels height.
+ // Resize image:
+ $im2 = imagecreatetruecolor($nw,$nh);
+ imagecopyresampled($im2, $im, 0, 0, 0, $ystart, $nw, $nh, $w, $yheight);
+ imageinterlace($im2,true); // For progressive JPEG.
+ $tempname=$filepath.'_TEMP.jpg';
+ imagejpeg($im2, $tempname, 90);
+ imagedestroy($im);
+ imagedestroy($im2);
+ rename($tempname,$filepath); // Overwrite original picture with thumbnail.
+ return true;
+}
+