]> git.immae.eu Git - github/shaarli/Shaarli.git/commitdiff
Merge pull request #87 from LionelMartin/3385af123f6b4dfc59aeaa69f180381307b64368
authorSébastien SAUVAGE <sebsauvage@sebsauvage.net>
Tue, 24 Sep 2013 09:20:06 +0000 (02:20 -0700)
committerSébastien SAUVAGE <sebsauvage@sebsauvage.net>
Tue, 24 Sep 2013 09:20:06 +0000 (02:20 -0700)
Added a json_encode implementation for PHP < 5.2 (free.fr)

1  2 
index.php

diff --combined index.php
index 327109f06a89275f75f1f62660e952460ac9f6b2,eaa7c532862874631eb6e15e15e4844226160050..d9181b650cd0504d978bdb53f6e1eb642d967906
+++ b/index.php
@@@ -41,7 -41,7 +41,7 @@@ define('PHPSUFFIX',' */ ?>'); // Suffi
  // Force cookie path (but do not change lifetime)
  $cookie=session_get_cookie_params();
  $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
 -session_set_cookie_params($cookie['lifetime'],$cookiedir,$_SERVER['SERVER_NAME']); // Set default cookie expiration and path.
 +session_set_cookie_params($cookie['lifetime'],$cookiedir,$_SERVER['HTTP_HOST']); // Set default cookie expiration and path.
  
  // Set session parameters on server side.
  define('INACTIVITY_TIMEOUT',3600); // (in seconds). If the user does not access any page within this time, his/her session is considered expired.
@@@ -89,7 -89,7 +89,7 @@@ if (!is_dir($GLOBALS['config']['DATADIR
  if (!is_dir('tmp')) { mkdir('tmp',0705); chmod('tmp',0705); } // For RainTPL temporary files.
  if (!is_file($GLOBALS['config']['DATADIR'].'/.htaccess')) { file_put_contents($GLOBALS['config']['DATADIR'].'/.htaccess',"Allow from none\nDeny from all\n"); } // Protect data files.
  // Second check to see if Shaarli can write in its directory, because on some hosts is_writable() is not reliable.
 -if (!is_file($GLOBALS['config']['DATADIR'].'/.htaccess')) die('<pre>ERROR: Shaarli does not have the right to write in its own directory ('.realpath(dirname(__FILE__)).').</pre>');
 +if (!is_file($GLOBALS['config']['DATADIR'].'/.htaccess')) die('<pre>ERROR: Shaarli does not have the right to write in its data directory ('.realpath($GLOBALS['config']['DATADIR']).').</pre>');
  if ($GLOBALS['config']['ENABLE_LOCALCACHE'])
  {
      if (!is_dir($GLOBALS['config']['CACHEDIR'])) { mkdir($GLOBALS['config']['CACHEDIR'],0705); chmod($GLOBALS['config']['CACHEDIR'],0705); }
@@@ -400,14 -400,14 +400,14 @@@ if (isset($_POST['login'])
              $_SESSION['expires_on']=time()+$_SESSION['longlastingsession'];  // Set session expiration on server-side.
  
              $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
 -            session_set_cookie_params($_SESSION['longlastingsession'],$cookiedir,$_SERVER['SERVER_NAME']); // Set session cookie expiration on client side
 +            session_set_cookie_params($_SESSION['longlastingsession'],$cookiedir,$_SERVER['HTTP_HOST']); // Set session cookie expiration on client side
              // Note: Never forget the trailing slash on the cookie path !
              session_regenerate_id(true);  // Send cookie with new expiration date to browser.
          }
          else // Standard session expiration (=when browser closes)
          {
              $cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/';
 -            session_set_cookie_params(0,$cookiedir,$_SERVER['SERVER_NAME']); // 0 means "When browser closes"
 +            session_set_cookie_params(0,$cookiedir,$_SERVER['HTTP_HOST']); // 0 means "When browser closes"
              session_regenerate_id(true);
          }
          // Optional redirect after login:
@@@ -439,7 -439,7 +439,7 @@@ function serverUrl(
  {
      $https = (!empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS'])=='on')) || $_SERVER["SERVER_PORT"]=='443'; // HTTPS detection.
      $serverport = ($_SERVER["SERVER_PORT"]=='80' || ($https && $_SERVER["SERVER_PORT"]=='443') ? '' : ':'.$_SERVER["SERVER_PORT"]);
 -    return 'http'.($https?'s':'').'://'.$_SERVER["SERVER_NAME"].$serverport;
 +    return 'http'.($https?'s':'').'://'.$_SERVER['HTTP_HOST'].$serverport;
  }
  
  // Returns the absolute URL of current script, without the query.
@@@ -566,7 -566,7 +566,7 @@@ function getHTTP($url,$timeout=30
  {
      try
      {
 -        $options = array('http'=>array('method'=>'GET','timeout' => $timeout)); // Force network timeout
 +        $options = array('http'=>array('method'=>'GET','timeout' => $timeout, 'user_agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:23.0) Gecko/20100101 Firefox/23.0')); // Force network timeout
          $context = stream_context_create($options);
          $data=file_get_contents($url,false,$context,-1, 4000000); // We download at most 4 Mb from source.
          if (!$data) { return array('HTTP Error',array(),''); }
@@@ -876,7 -876,7 +876,7 @@@ class linkdb implements Iterator, Count
  }
  
  // ------------------------------------------------------------------------------------------
 -// Ouput the last 50 links in RSS 2.0 format.
 +// Ouput the last N links in RSS 2.0 format.
  function showRSS()
  {
      header('Content-Type: application/rss+xml; charset=utf-8');
      if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
      elseif (!empty($_GET['searchtags']))   $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
      else $linksToDisplay = $LINKSDB;
 +    $nblinksToDisplay = !empty($_GET['nb']) ? max($_GET['nb'] + 0, 1) : 50;
  
      $pageaddr=htmlspecialchars(indexUrl());
      echo '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/">';
      }
      $i=0;
      $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; }  // No, I can't use array_keys().
 -    while ($i<50 && $i<count($keys))
 +    while ($i<$nblinksToDisplay && $i<count($keys))
      {
          $link = $linksToDisplay[$keys[$i]];
          $guid = $pageaddr.'?'.smallHash($link['linkdate']);
  }
  
  // ------------------------------------------------------------------------------------------
 -// Ouput the last 50 links in ATOM format.
 +// Ouput the last N links in ATOM format.
  function showATOM()
  {
      header('Content-Type: application/atom+xml; charset=utf-8');
      if (!empty($_GET['searchterm'])) $linksToDisplay = $LINKSDB->filterFulltext($_GET['searchterm']);
      elseif (!empty($_GET['searchtags']))   $linksToDisplay = $LINKSDB->filterTags(trim($_GET['searchtags']));
      else $linksToDisplay = $LINKSDB;
 +    $nblinksToDisplay = !empty($_GET['nb']) ? max($_GET['nb'] + 0, 1) : 50;
  
      $pageaddr=htmlspecialchars(indexUrl());
      $latestDate = '';
      $entries='';
      $i=0;
      $keys=array(); foreach($linksToDisplay as $key=>$value) { $keys[]=$key; }  // No, I can't use array_keys().
 -    while ($i<50 && $i<count($keys))
 +    while ($i<$nblinksToDisplay && $i<count($keys))
      {
          $link = $linksToDisplay[$keys[$i]];
          $guid = $pageaddr.'?'.smallHash($link['linkdate']);
@@@ -1281,7 -1279,7 +1281,7 @@@ function renderPage(
          if (is_numeric($_GET['linksperpage'])) { $_SESSION['LINKS_PER_PAGE']=abs(intval($_GET['linksperpage'])); }
          // Make sure the referer is from Shaarli itself.
          $referer = '?';
 -        if (!empty($_SERVER['HTTP_REFERER']) && strcmp(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_HOST),$_SERVER['SERVER_NAME'])==0)
 +        if (!empty($_SERVER['HTTP_REFERER']) && strcmp(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_HOST),$_SERVER['HTTP_HOST'])==0)
              $referer = $_SERVER['HTTP_REFERER'];
          header('Location: '.$referer);
          exit;
          }
          // Make sure the referer is from Shaarli itself.
          $referer = '?';
 -        if (!empty($_SERVER['HTTP_REFERER']) && strcmp(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_HOST),$_SERVER['SERVER_NAME'])==0)
 +        if (!empty($_SERVER['HTTP_REFERER']) && strcmp(parse_url($_SERVER['HTTP_REFERER'],PHP_URL_HOST),$_SERVER['HTTP_HOST'])==0)
              $referer = $_SERVER['HTTP_REFERER'];
          header('Location: '.$referer);
          exit;
              $link_is_new = true;  // This is a new link
              $linkdate = strval(date('Ymd_His'));
              $title = (empty($_GET['title']) ? '' : $_GET['title'] ); // Get title if it was provided in URL (by the bookmarklet).
 -            $description=''; $tags=''; $private=0;
 +            $description = (empty($_GET['description']) ? '' : $_GET['description'] )."\n"; // Get description if it was provided in URL (by the bookmarklet). [Bronco added that]
 +            $tags = (empty($_GET['tags']) ? '' : $_GET['tags'] ); // Get tags if it was provided in URL
 +            $private = (!empty($_GET['private']) && $_GET['private'] === "1" ? 1 : 0); // Get private if it was provided in URL 
              if (($url!='') && parse_url($url,PHP_URL_SCHEME)=='') $url = 'http://'.$url;
              // If this is an HTTP link, we try go get the page to extact the title (otherwise we will to straight to the edit form.)
              if (empty($title) && parse_url($url,PHP_URL_SCHEME)=='http')
              {
                  list($status,$headers,$data) = getHTTP($url,4); // Short timeout to keep the application responsive.
                  // FIXME: Decode charset according to specified in either 1) HTTP response headers or 2) <head> in html
 -                if (strpos($status,'200 OK')!==false) $title=html_entity_decode(html_extract_title($data),ENT_QUOTES,'UTF-8');
 -
 +                if (strpos($status,'200 OK')!==false)
 +                                       {
 +                        // Look for charset in html header.
 +                                              preg_match('#<meta .*charset=.*>#Usi', $data, $meta);
 + 
 +                                              // If found, extract encoding.
 +                                              if (!empty($meta[0]))
 +                                              {
 +                                                      // Get encoding specified in header.
 +                                                      preg_match('#charset="?(.*)"#si', $meta[0], $enc);
 +                                                      // If charset not found, use utf-8.
 +                                                      $html_charset = (!empty($enc[1])) ? strtolower($enc[1]) : 'utf-8';
 +                                              }
 +                                              else { $html_charset = 'utf-8'; }
 + 
 +                                              // Extract title
 +                                              $title = html_extract_title($data);
 +                                              if (!empty($title))
 +                                              {
 +                                                      // Re-encode title in utf-8 if necessary.
 +                                                      $title = ($html_charset == 'iso-8859-1') ? utf8_encode($title) : $title;
 +                                              }
 +                                      }
              }
              if ($url=='') $url='?'.smallHash($linkdate); // In case of empty URL, this is just a text (with a link that point to itself)
 -            $link = array('linkdate'=>$linkdate,'title'=>$title,'url'=>$url,'description'=>$description,'tags'=>$tags,'private'=>0);
 +            $link = array('linkdate'=>$linkdate,'title'=>$title,'url'=>$url,'description'=>$description,'tags'=>$tags,'private'=>$private);
          }
  
          $PAGE = new pageBuilder;
@@@ -1699,11 -1674,7 +1699,11 @@@ function importFile(
                  {
                      $attr=$m[1]; $value=$m[2];
                      if ($attr=='HREF') $link['url']=html_entity_decode($value,ENT_QUOTES,'UTF-8');
 -                    elseif ($attr=='ADD_DATE') $raw_add_date=intval($value);
 +                    elseif ($attr=='ADD_DATE')
 +                    {
 +                        $raw_add_date=intval($value);
 +                        if ($raw_add_date>30000000000) $raw_add_date/=1000;   //If larger than year 2920, then was likely stored in milliseconds instead of seconds
 +                    }
                      elseif ($attr=='PRIVATE') $link['private']=($value=='0'?0:1);
                      elseif ($attr=='TAGS') $link['tags']=html_entity_decode(str_replace(',',' ',$value),ENT_QUOTES,'UTF-8');
                  }
@@@ -2038,7 -2009,7 +2038,7 @@@ function lazyThumbnail($url,$href=false
  function install()
  {
      // On free.fr host, make sure the /sessions directory exists, otherwise login will not work.
 -    if (endsWith($_SERVER['SERVER_NAME'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
 +    if (endsWith($_SERVER['HTTP_HOST'],'.free.fr') && !is_dir($_SERVER['DOCUMENT_ROOT'].'/sessions')) mkdir($_SERVER['DOCUMENT_ROOT'].'/sessions',0705);
  
  
      // This part makes sure sessions works correctly.
@@@ -2151,7 -2122,42 +2151,42 @@@ function isTZvalid($continent,$city
      }
      return false;
  }
+ if (!function_exists('json_encode')) {
+     function json_encode($data) {
+         switch ($type = gettype($data)) {
+             case 'NULL':
+                 return 'null';
+             case 'boolean':
+                 return ($data ? 'true' : 'false');
+             case 'integer':
+             case 'double':
+             case 'float':
+                 return $data;
+             case 'string':
+                 return '"' . addslashes($data) . '"';
+             case 'object':
+                 $data = get_object_vars($data);
+             case 'array':
+                 $output_index_count = 0;
+                 $output_indexed = array();
+                 $output_associative = array();
+                 foreach ($data as $key => $value) {
+                     $output_indexed[] = json_encode($value);
+                     $output_associative[] = json_encode($key) . ':' . json_encode($value);
+                     if ($output_index_count !== NULL && $output_index_count++ !== $key) {
+                         $output_index_count = NULL;
+                     }
+                 }
+                 if ($output_index_count !== NULL) {
+                     return '[' . implode(',', $output_indexed) . ']';
+                 } else {
+                     return '{' . implode(',', $output_associative) . '}';
+                 }
+             default:
+                 return ''; // Not supported
+         }
+     }
+ }
  
  // Webservices (for use with jQuery/jQueryUI)
  // eg.  index.php?ws=tags&term=minecr