Index: extensions/FacebookPlug/Server/tags/1.0.0/cancel.php
===================================================================
--- extensions/FacebookPlug/Server/tags/1.0.0/cancel.php	(revision 8485)
+++ extensions/FacebookPlug/Server/tags/1.0.0/cancel.php	(revision 8485)
@@ -0,0 +1,44 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | FacebookPlug - a Piwigo Plugin                                        |
+// | Copyright (C) 2010-2011 Ruben ARNAUD - rub@piwigo.org                 |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+?>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+</head>
+<body>
+  <script type="text/javascript">
+    window.close();
+  </script>
+<!-- google-analytics -->
+<script type="text/javascript">
+  var _gaq = _gaq || [];
+  _gaq.push(['_setAccount', 'UA-2272624-7']);
+  _gaq.push(['_trackPageview']);
+
+  (function() {
+    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
+    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
+  })();
+
+</script>
+<!-- google-analytics -->
+</body>
+</html>
Index: extensions/FacebookPlug/Server/tags/1.0.0/database/database.sql
===================================================================
--- extensions/FacebookPlug/Server/tags/1.0.0/database/database.sql	(revision 8485)
+++ extensions/FacebookPlug/Server/tags/1.0.0/database/database.sql	(revision 8485)
@@ -0,0 +1,17 @@
+--
+-- Structure de la table 'FBP_HISTORY'
+--
+
+CREATE TABLE FBP_HISTORY (
+  ID int(10) unsigned NOT NULL auto_increment,
+  `TIMESTAMP` timestamp NOT NULL default CURRENT_TIMESTAMP,
+  VERSION varchar(5) NOT NULL default '',
+  SCRIPT_NAME varchar(15) NOT NULL default '',
+  IP varchar(15) NOT NULL default '',
+  IMAGE_URL text NOT NULL default '',
+  PICTURE_URL text NOT NULL default '',
+  GALLERY_TITLE text NOT NULL default '',
+  PICTURE_TITLE text NOT NULL default '',
+  PRIMARY KEY  (ID),
+  KEY DATETIME_I1 (`TIMESTAMP`)
+) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
Index: extensions/FacebookPlug/Server/tags/1.0.0/database/index.php
===================================================================
--- extensions/FacebookPlug/Server/tags/1.0.0/database/index.php	(revision 8485)
+++ extensions/FacebookPlug/Server/tags/1.0.0/database/index.php	(revision 8485)
@@ -0,0 +1,27 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | FacebookPlug - a Piwigo Plugin                                        |
+// | Copyright (C) 2010-2011 Ruben ARNAUD - rub@piwigo.org                 |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+// Recursive call
+$url = 'http://www.facebook.com/';
+header( 'Request-URI: '.$url );
+header( 'Content-Location: '.$url );
+header( 'Location: '.$url );
+exit();
+?>
Index: extensions/FacebookPlug/Server/tags/1.0.0/do_upload_photo.php
===================================================================
--- extensions/FacebookPlug/Server/tags/1.0.0/do_upload_photo.php	(revision 8485)
+++ extensions/FacebookPlug/Server/tags/1.0.0/do_upload_photo.php	(revision 8485)
@@ -0,0 +1,91 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | FacebookPlug - a Piwigo Plugin                                        |
+// | Copyright (C) 2010-2011 Ruben ARNAUD - rub@piwigo.org                 |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+define('FACEBOOKPLUG_ROOT_PATH','./');
+
+require_once 'include/common.php';
+
+// Check argument
+!empty($_GET['u']) or die('Missing argument!');
+
+fbp_mkdir($conf['local_upload_dir']);
+
+$image_url = $_GET['u'];
+if (! in_array(strtoupper(pathinfo($image_url, PATHINFO_EXTENSION)), $conf['available_upload_ext']))
+{
+  die($image_url.' is not a uploaded file: incorrect type');
+}
+
+$page_url = @$_GET['pu'];
+$page_title = @$_GET['pt'];
+$gallery_title = @$_GET['gt'];
+
+//~ $local_filename = $conf['local_upload_dir'].'/'.basename($image_url);
+$local_filename = $conf['local_upload_dir'].'/'.md5($image_url.$page_url.$page_title.$gallery_title.$_SERVER['REMOTE_ADDR'].print_r(getdate(), true)).'.'.pathinfo($image_url, PATHINFO_EXTENSION);
+
+// Prevent error for local use, IP are not admitted
+//~ $page_url = str_replace('http://127.0.0.1', 'http://localhost', $page_url);
+
+@unlink($local_filename);
+
+@set_time_limit(0);
+
+if ($handle = @fopen($local_filename, 'wb') and fbp_fetchRemote($image_url, $handle))
+{
+  fclose($handle);
+}
+
+if (is_file($local_filename))
+{
+  try
+  {
+    $facebook->setFileUploadSupport(true);
+    $result = $facebook->api(
+      '/me/photos', 'post',
+      array(
+        'source' => '@'.$local_filename,
+        'message' => $page_title.'
+'.$gallery_title.'
+'. $page_url,
+        ));
+    // Send Result
+    if (isset($result['id']))
+    {
+      echo $result['id'];
+    }
+    else
+    {
+      die($image_url.' not uploaded on Facebook');
+    }
+   }
+   catch (FacebookApiException $e)
+   {
+    die($image_url.' not uploaded on Facebook');
+   }
+  unlink($local_filename);
+}
+else
+{
+  die($image_url.' not uploaded locally');
+}
+
+// Mettre des stats
+
+?>
Index: extensions/FacebookPlug/Server/tags/1.0.0/include/common.php
===================================================================
--- extensions/FacebookPlug/Server/tags/1.0.0/include/common.php	(revision 8485)
+++ extensions/FacebookPlug/Server/tags/1.0.0/include/common.php	(revision 8485)
@@ -0,0 +1,95 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | FacebookPlug - a Piwigo Plugin                                        |
+// | Copyright (C) 2010-2011 Ruben ARNAUD - rub@piwigo.org                 |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+defined('FACEBOOKPLUG_ROOT_PATH') or trigger_error('Hacking attempt!', E_USER_ERROR);
+
+@set_magic_quotes_runtime(false); // Disable magic_quotes_runtime
+
+//
+// addslashes to vars if magic_quotes_gpc is off this is a security
+// precaution to prevent someone trying to break out of a SQL statement.
+//
+if( !@get_magic_quotes_gpc() )
+{
+  function sanitize_mysql_kv(&$v, $k)
+  {
+    $v = addslashes($v);
+  }
+  if( is_array( $_GET ) )
+  {
+    array_walk_recursive( $_GET, 'sanitize_mysql_kv' );
+  }
+  if( is_array( $_POST ) )
+  {
+    array_walk_recursive( $_POST, 'sanitize_mysql_kv' );
+  }
+  if( is_array( $_COOKIE ) )
+  {
+    array_walk_recursive( $_COOKIE, 'sanitize_mysql_kv' );
+  }
+}
+if ( !empty($_SERVER["PATH_INFO"]) )
+{
+  $_SERVER["PATH_INFO"] = addslashes($_SERVER["PATH_INFO"]);
+}
+
+require_once(FACEBOOKPLUG_ROOT_PATH . 'include/constants.php');
+require_once(FACEBOOKPLUG_ROOT_PATH . 'include/constants_secret.php');
+require_once(FACEBOOKPLUG_ROOT_PATH . 'include/facebook.php');
+require_once(FACEBOOKPLUG_ROOT_PATH . 'include/functions.php');
+
+// Main global var
+$conf = array();
+
+// Default config
+include(FACEBOOKPLUG_ROOT_PATH . 'include/config_default.php');
+
+// Log on db
+fbp_db_log();
+
+// Init Facebook
+$facebook = new Facebook(array(
+  'appId'  => FACEBOOK_APP_ID,
+  'secret' => FACEBOOK_SECRET,
+  'cookie' => true, // enable optional cookie support
+));
+
+$session = $facebook->getSession();
+//~ var_dump($session);
+// Session based graph API call.
+if (! $session)
+{
+  // Redirect to facebook page reconnect
+  $url = $facebook->getLoginUrl(
+    array
+    (
+      //ici on demande les permissions email, publication sur le mur, et changement du status
+      //'req_perms' => 'email,publish_stream,status_update',
+      'req_perms' => 'publish_stream',
+      'display' => 'popup',
+      'cancel_url' => 'http://'.$_SERVER['HTTP_HOST'].'/'.FBP_VERSION.'/cancel.php'
+    ));
+  header( 'Request-URI: '.$url );
+  header( 'Content-Location: '.$url );
+  header( 'Location: '.$url );
+  exit();
+}
+
+?>
Index: extensions/FacebookPlug/Server/tags/1.0.0/include/config_default.php
===================================================================
--- extensions/FacebookPlug/Server/tags/1.0.0/include/config_default.php	(revision 8485)
+++ extensions/FacebookPlug/Server/tags/1.0.0/include/config_default.php	(revision 8485)
@@ -0,0 +1,29 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | FacebookPlug - a Piwigo Plugin                                        |
+// | Copyright (C) 2010-2011 Ruben ARNAUD - rub@piwigo.org                 |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+// Temporay upload directory
+//~ $conf['local_upload_dir'] = dirname(dirname(__FILE__)).'/tmp/_upload';
+$conf['local_upload_dir'] = '/web/piwigo/tmp/_upload';
+
+//From http://developers.facebook.com/docs/reference/rest/photos.upload/
+// *GIF *JPG *PNG *PSD *TIFF *JP2 *IFF *WBMP *XBM
+$conf['available_upload_ext'] = array('GIF', 'JPG', 'PNG', 'PSD', 'TIFF', 'JP2', 'IFF', 'WBMP', 'XBM');
+
+?>
Index: extensions/FacebookPlug/Server/tags/1.0.0/include/constants.php
===================================================================
--- extensions/FacebookPlug/Server/tags/1.0.0/include/constants.php	(revision 8485)
+++ extensions/FacebookPlug/Server/tags/1.0.0/include/constants.php	(revision 8485)
@@ -0,0 +1,33 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | FacebookPlug - a Piwigo Plugin                                        |
+// | Copyright (C) 2010-2011 Ruben ARNAUD - rub@piwigo.org                 |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+//This defines ares on constants_secret.php
+//define('FACEBOOK_APP_ID', '***');
+//define('FACEBOOK_SECRET', '***');
+
+//~ define('FBP_BASE', '***');
+//~ define('FBP_USER', '***');
+//~ define('FBP_PASSWORD', '***');
+//~ define('FBP_HOST', '***');
+//This defines ares on constants_secret.php
+
+define('FBP_VERSION', basename(dirname(dirname(__FILE__))));
+
+?>
Index: extensions/FacebookPlug/Server/tags/1.0.0/include/facebook.php
===================================================================
--- extensions/FacebookPlug/Server/tags/1.0.0/include/facebook.php	(revision 8485)
+++ extensions/FacebookPlug/Server/tags/1.0.0/include/facebook.php	(revision 8485)
@@ -0,0 +1,955 @@
+<?php
+
+if (!function_exists('curl_init')) {
+  throw new Exception('Facebook needs the CURL PHP extension.');
+}
+if (!function_exists('json_decode')) {
+  throw new Exception('Facebook needs the JSON PHP extension.');
+}
+
+/**
+ * Thrown when an API call returns an exception.
+ *
+ * @author Naitik Shah <naitik@facebook.com>
+ */
+class FacebookApiException extends Exception
+{
+  /**
+   * The result from the API server that represents the exception information.
+   */
+  protected $result;
+
+  /**
+   * Make a new API Exception with the given result.
+   *
+   * @param Array $result the result from the API server
+   */
+  public function __construct($result) {
+    $this->result = $result;
+
+    $code = isset($result['error_code']) ? $result['error_code'] : 0;
+
+    if (isset($result['error_description'])) {
+      // OAuth 2.0 Draft 10 style
+      $msg = $result['error_description'];
+    } else if (isset($result['error']) && is_array($result['error'])) {
+      // OAuth 2.0 Draft 00 style
+      $msg = $result['error']['message'];
+    } else if (isset($result['error_msg'])) {
+      // Rest server style
+      $msg = $result['error_msg'];
+    } else {
+      $msg = 'Unknown Error. Check getResult()';
+    }
+
+    parent::__construct($msg, $code);
+  }
+
+  /**
+   * Return the associated result object returned by the API server.
+   *
+   * @returns Array the result from the API server
+   */
+  public function getResult() {
+    return $this->result;
+  }
+
+  /**
+   * Returns the associated type for the error. This will default to
+   * 'Exception' when a type is not available.
+   *
+   * @return String
+   */
+  public function getType() {
+    if (isset($this->result['error'])) {
+      $error = $this->result['error'];
+      if (is_string($error)) {
+        // OAuth 2.0 Draft 10 style
+        return $error;
+      } else if (is_array($error)) {
+        // OAuth 2.0 Draft 00 style
+        if (isset($error['type'])) {
+          return $error['type'];
+        }
+      }
+    }
+    return 'Exception';
+  }
+
+  /**
+   * To make debugging easier.
+   *
+   * @returns String the string representation of the error
+   */
+  public function __toString() {
+    $str = $this->getType() . ': ';
+    if ($this->code != 0) {
+      $str .= $this->code . ': ';
+    }
+    return $str . $this->message;
+  }
+}
+
+/**
+ * Provides access to the Facebook Platform.
+ *
+ * @author Naitik Shah <naitik@facebook.com>
+ */
+class Facebook
+{
+  /**
+   * Version.
+   */
+  const VERSION = '2.1.2';
+
+  /**
+   * Default options for curl.
+   */
+  public static $CURL_OPTS = array(
+    CURLOPT_CONNECTTIMEOUT => 10,
+    CURLOPT_RETURNTRANSFER => true,
+    CURLOPT_TIMEOUT        => 60,
+    CURLOPT_USERAGENT      => 'facebook-php-2.0',
+  );
+
+  /**
+   * List of query parameters that get automatically dropped when rebuilding
+   * the current URL.
+   */
+  protected static $DROP_QUERY_PARAMS = array(
+    'session',
+    'signed_request',
+  );
+
+  /**
+   * Maps aliases to Facebook domains.
+   */
+  public static $DOMAIN_MAP = array(
+    'api'      => 'https://api.facebook.com/',
+    'api_read' => 'https://api-read.facebook.com/',
+    'graph'    => 'https://graph.facebook.com/',
+    'www'      => 'https://www.facebook.com/',
+  );
+
+  /**
+   * The Application ID.
+   */
+  protected $appId;
+
+  /**
+   * The Application API Secret.
+   */
+  protected $apiSecret;
+
+  /**
+   * The active user session, if one is available.
+   */
+  protected $session;
+
+  /**
+   * The data from the signed_request token.
+   */
+  protected $signedRequest;
+
+  /**
+   * Indicates that we already loaded the session as best as we could.
+   */
+  protected $sessionLoaded = false;
+
+  /**
+   * Indicates if Cookie support should be enabled.
+   */
+  protected $cookieSupport = false;
+
+  /**
+   * Base domain for the Cookie.
+   */
+  protected $baseDomain = '';
+
+  /**
+   * Indicates if the CURL based @ syntax for file uploads is enabled.
+   */
+  protected $fileUploadSupport = false;
+
+  /**
+   * Initialize a Facebook Application.
+   *
+   * The configuration:
+   * - appId: the application ID
+   * - secret: the application secret
+   * - cookie: (optional) boolean true to enable cookie support
+   * - domain: (optional) domain for the cookie
+   * - fileUpload: (optional) boolean indicating if file uploads are enabled
+   *
+   * @param Array $config the application configuration
+   */
+  public function __construct($config) {
+    $this->setAppId($config['appId']);
+    $this->setApiSecret($config['secret']);
+    if (isset($config['cookie'])) {
+      $this->setCookieSupport($config['cookie']);
+    }
+    if (isset($config['domain'])) {
+      $this->setBaseDomain($config['domain']);
+    }
+    if (isset($config['fileUpload'])) {
+      $this->setFileUploadSupport($config['fileUpload']);
+    }
+  }
+
+  /**
+   * Set the Application ID.
+   *
+   * @param String $appId the Application ID
+   */
+  public function setAppId($appId) {
+    $this->appId = $appId;
+    return $this;
+  }
+
+  /**
+   * Get the Application ID.
+   *
+   * @return String the Application ID
+   */
+  public function getAppId() {
+    return $this->appId;
+  }
+
+  /**
+   * Set the API Secret.
+   *
+   * @param String $appId the API Secret
+   */
+  public function setApiSecret($apiSecret) {
+    $this->apiSecret = $apiSecret;
+    return $this;
+  }
+
+  /**
+   * Get the API Secret.
+   *
+   * @return String the API Secret
+   */
+  public function getApiSecret() {
+    return $this->apiSecret;
+  }
+
+  /**
+   * Set the Cookie Support status.
+   *
+   * @param Boolean $cookieSupport the Cookie Support status
+   */
+  public function setCookieSupport($cookieSupport) {
+    $this->cookieSupport = $cookieSupport;
+    return $this;
+  }
+
+  /**
+   * Get the Cookie Support status.
+   *
+   * @return Boolean the Cookie Support status
+   */
+  public function useCookieSupport() {
+    return $this->cookieSupport;
+  }
+
+  /**
+   * Set the base domain for the Cookie.
+   *
+   * @param String $domain the base domain
+   */
+  public function setBaseDomain($domain) {
+    $this->baseDomain = $domain;
+    return $this;
+  }
+
+  /**
+   * Get the base domain for the Cookie.
+   *
+   * @return String the base domain
+   */
+  public function getBaseDomain() {
+    return $this->baseDomain;
+  }
+
+  /**
+   * Set the file upload support status.
+   *
+   * @param String $domain the base domain
+   */
+  public function setFileUploadSupport($fileUploadSupport) {
+    $this->fileUploadSupport = $fileUploadSupport;
+    return $this;
+  }
+
+  /**
+   * Get the file upload support status.
+   *
+   * @return String the base domain
+   */
+  public function useFileUploadSupport() {
+    return $this->fileUploadSupport;
+  }
+
+  /**
+   * Get the data from a signed_request token
+   *
+   * @return String the base domain
+   */
+  public function getSignedRequest() {
+    if (!$this->signedRequest) {
+      if (isset($_REQUEST['signed_request'])) {
+        $this->signedRequest = $this->parseSignedRequest(
+          $_REQUEST['signed_request']);
+      }
+    }
+    return $this->signedRequest;
+  }
+
+  /**
+   * Set the Session.
+   *
+   * @param Array $session the session
+   * @param Boolean $write_cookie indicate if a cookie should be written. this
+   * value is ignored if cookie support has been disabled.
+   */
+  public function setSession($session=null, $write_cookie=true) {
+    $session = $this->validateSessionObject($session);
+    $this->sessionLoaded = true;
+    $this->session = $session;
+    if ($write_cookie) {
+      $this->setCookieFromSession($session);
+    }
+    return $this;
+  }
+
+  /**
+   * Get the session object. This will automatically look for a signed session
+   * sent via the signed_request, Cookie or Query Parameters if needed.
+   *
+   * @return Array the session
+   */
+  public function getSession() {
+    if (!$this->sessionLoaded) {
+      $session = null;
+      $write_cookie = true;
+
+      // try loading session from signed_request in $_REQUEST
+      $signedRequest = $this->getSignedRequest();
+      if ($signedRequest) {
+        // sig is good, use the signedRequest
+        $session = $this->createSessionFromSignedRequest($signedRequest);
+      }
+
+      // try loading session from $_REQUEST
+      if (!$session && isset($_REQUEST['session'])) {
+        $session = json_decode(
+          get_magic_quotes_gpc()
+            ? stripslashes($_REQUEST['session'])
+            : $_REQUEST['session'],
+          true
+        );
+        $session = $this->validateSessionObject($session);
+      }
+
+      // try loading session from cookie if necessary
+      if (!$session && $this->useCookieSupport()) {
+        $cookieName = $this->getSessionCookieName();
+        if (isset($_COOKIE[$cookieName])) {
+          $session = array();
+          parse_str(trim(
+            get_magic_quotes_gpc()
+              ? stripslashes($_COOKIE[$cookieName])
+              : $_COOKIE[$cookieName],
+            '"'
+          ), $session);
+          $session = $this->validateSessionObject($session);
+          // write only if we need to delete a invalid session cookie
+          $write_cookie = empty($session);
+        }
+      }
+
+      $this->setSession($session, $write_cookie);
+    }
+
+    return $this->session;
+  }
+
+  /**
+   * Get the UID from the session.
+   *
+   * @return String the UID if available
+   */
+  public function getUser() {
+    $session = $this->getSession();
+    return $session ? $session['uid'] : null;
+  }
+
+  /**
+   * Gets a OAuth access token.
+   *
+   * @return String the access token
+   */
+  public function getAccessToken() {
+    $session = $this->getSession();
+    // either user session signed, or app signed
+    if ($session) {
+      return $session['access_token'];
+    } else {
+      return $this->getAppId() .'|'. $this->getApiSecret();
+    }
+  }
+
+  /**
+   * Get a Login URL for use with redirects. By default, full page redirect is
+   * assumed. If you are using the generated URL with a window.open() call in
+   * JavaScript, you can pass in display=popup as part of the $params.
+   *
+   * The parameters:
+   * - next: the url to go to after a successful login
+   * - cancel_url: the url to go to after the user cancels
+   * - req_perms: comma separated list of requested extended perms
+   * - display: can be "page" (default, full page) or "popup"
+   *
+   * @param Array $params provide custom parameters
+   * @return String the URL for the login flow
+   */
+  public function getLoginUrl($params=array()) {
+    $currentUrl = $this->getCurrentUrl();
+    return $this->getUrl(
+      'www',
+      'login.php',
+      array_merge(array(
+        'api_key'         => $this->getAppId(),
+        'cancel_url'      => $currentUrl,
+        'display'         => 'page',
+        'fbconnect'       => 1,
+        'next'            => $currentUrl,
+        'return_session'  => 1,
+        'session_version' => 3,
+        'v'               => '1.0',
+      ), $params)
+    );
+  }
+
+  /**
+   * Get a Logout URL suitable for use with redirects.
+   *
+   * The parameters:
+   * - next: the url to go to after a successful logout
+   *
+   * @param Array $params provide custom parameters
+   * @return String the URL for the logout flow
+   */
+  public function getLogoutUrl($params=array()) {
+    return $this->getUrl(
+      'www',
+      'logout.php',
+      array_merge(array(
+        'next'         => $this->getCurrentUrl(),
+        'access_token' => $this->getAccessToken(),
+      ), $params)
+    );
+  }
+
+  /**
+   * Get a login status URL to fetch the status from facebook.
+   *
+   * The parameters:
+   * - ok_session: the URL to go to if a session is found
+   * - no_session: the URL to go to if the user is not connected
+   * - no_user: the URL to go to if the user is not signed into facebook
+   *
+   * @param Array $params provide custom parameters
+   * @return String the URL for the logout flow
+   */
+  public function getLoginStatusUrl($params=array()) {
+    return $this->getUrl(
+      'www',
+      'extern/login_status.php',
+      array_merge(array(
+        'api_key'         => $this->getAppId(),
+        'no_session'      => $this->getCurrentUrl(),
+        'no_user'         => $this->getCurrentUrl(),
+        'ok_session'      => $this->getCurrentUrl(),
+        'session_version' => 3,
+      ), $params)
+    );
+  }
+
+  /**
+   * Make an API call.
+   *
+   * @param Array $params the API call parameters
+   * @return the decoded response
+   */
+  public function api(/* polymorphic */) {
+    $args = func_get_args();
+    if (is_array($args[0])) {
+      return $this->_restserver($args[0]);
+    } else {
+      return call_user_func_array(array($this, '_graph'), $args);
+    }
+  }
+
+  /**
+   * Invoke the old restserver.php endpoint.
+   *
+   * @param Array $params method call object
+   * @return the decoded response object
+   * @throws FacebookApiException
+   */
+  protected function _restserver($params) {
+    // generic application level parameters
+    $params['api_key'] = $this->getAppId();
+    $params['format'] = 'json-strings';
+
+    $result = json_decode($this->_oauthRequest(
+      $this->getApiUrl($params['method']),
+      $params
+    ), true);
+
+    // results are returned, errors are thrown
+    if (is_array($result) && isset($result['error_code'])) {
+      throw new FacebookApiException($result);
+    }
+    return $result;
+  }
+
+  /**
+   * Invoke the Graph API.
+   *
+   * @param String $path the path (required)
+   * @param String $method the http method (default 'GET')
+   * @param Array $params the query/post data
+   * @return the decoded response object
+   * @throws FacebookApiException
+   */
+  protected function _graph($path, $method='GET', $params=array()) {
+    if (is_array($method) && empty($params)) {
+      $params = $method;
+      $method = 'GET';
+    }
+    $params['method'] = $method; // method override as we always do a POST
+
+    $result = json_decode($this->_oauthRequest(
+      $this->getUrl('graph', $path),
+      $params
+    ), true);
+
+    // results are returned, errors are thrown
+    if (is_array($result) && isset($result['error'])) {
+      $e = new FacebookApiException($result);
+      switch ($e->getType()) {
+        // OAuth 2.0 Draft 00 style
+        case 'OAuthException':
+        // OAuth 2.0 Draft 10 style
+        case 'invalid_token':
+          $this->setSession(null);
+      }
+      throw $e;
+    }
+    return $result;
+  }
+
+  /**
+   * Make a OAuth Request
+   *
+   * @param String $path the path (required)
+   * @param Array $params the query/post data
+   * @return the decoded response object
+   * @throws FacebookApiException
+   */
+  protected function _oauthRequest($url, $params) {
+    if (!isset($params['access_token'])) {
+      $params['access_token'] = $this->getAccessToken();
+    }
+
+    // json_encode all params values that are not strings
+    foreach ($params as $key => $value) {
+      if (!is_string($value)) {
+        $params[$key] = json_encode($value);
+      }
+    }
+    return $this->makeRequest($url, $params);
+  }
+
+  /**
+   * Makes an HTTP request. This method can be overriden by subclasses if
+   * developers want to do fancier things or use something other than curl to
+   * make the request.
+   *
+   * @param String $url the URL to make the request to
+   * @param Array $params the parameters to use for the POST body
+   * @param CurlHandler $ch optional initialized curl handle
+   * @return String the response text
+   */
+  protected function makeRequest($url, $params, $ch=null) {
+    if (!$ch) {
+      $ch = curl_init();
+    }
+
+    $opts = self::$CURL_OPTS;
+    if ($this->useFileUploadSupport()) {
+      $opts[CURLOPT_POSTFIELDS] = $params;
+    } else {
+      $opts[CURLOPT_POSTFIELDS] = http_build_query($params, null, '&');
+    }
+    $opts[CURLOPT_URL] = $url;
+
+    // disable the 'Expect: 100-continue' behaviour. This causes CURL to wait
+    // for 2 seconds if the server does not support this header.
+    if (isset($opts[CURLOPT_HTTPHEADER])) {
+      $existing_headers = $opts[CURLOPT_HTTPHEADER];
+      $existing_headers[] = 'Expect:';
+      $opts[CURLOPT_HTTPHEADER] = $existing_headers;
+    } else {
+      $opts[CURLOPT_HTTPHEADER] = array('Expect:');
+    }
+
+    curl_setopt_array($ch, $opts);
+    $result = curl_exec($ch);
+    if ($result === false) {
+      $e = new FacebookApiException(array(
+        'error_code' => curl_errno($ch),
+        'error'      => array(
+          'message' => curl_error($ch),
+          'type'    => 'CurlException',
+        ),
+      ));
+      curl_close($ch);
+      throw $e;
+    }
+    curl_close($ch);
+    return $result;
+  }
+
+  /**
+   * The name of the Cookie that contains the session.
+   *
+   * @return String the cookie name
+   */
+  protected function getSessionCookieName() {
+    return 'fbs_' . $this->getAppId();
+  }
+
+  /**
+   * Set a JS Cookie based on the _passed in_ session. It does not use the
+   * currently stored session -- you need to explicitly pass it in.
+   *
+   * @param Array $session the session to use for setting the cookie
+   */
+  protected function setCookieFromSession($session=null) {
+    if (!$this->useCookieSupport()) {
+      return;
+    }
+
+    $cookieName = $this->getSessionCookieName();
+    $value = 'deleted';
+    $expires = time() - 3600;
+    $domain = $this->getBaseDomain();
+    if ($session) {
+      $value = '"' . http_build_query($session, null, '&') . '"';
+      if (isset($session['base_domain'])) {
+        $domain = $session['base_domain'];
+      }
+      $expires = $session['expires'];
+    }
+
+    // prepend dot if a domain is found
+    if ($domain) {
+      $domain = '.' . $domain;
+    }
+
+    // if an existing cookie is not set, we dont need to delete it
+    if ($value == 'deleted' && empty($_COOKIE[$cookieName])) {
+      return;
+    }
+
+    if (headers_sent()) {
+      self::errorLog('Could not set cookie. Headers already sent.');
+
+    // ignore for code coverage as we will never be able to setcookie in a CLI
+    // environment
+    // @codeCoverageIgnoreStart
+    } else {
+      setcookie($cookieName, $value, $expires, '/', $domain);
+    }
+    // @codeCoverageIgnoreEnd
+  }
+
+  /**
+   * Validates a session_version=3 style session object.
+   *
+   * @param Array $session the session object
+   * @return Array the session object if it validates, null otherwise
+   */
+  protected function validateSessionObject($session) {
+    // make sure some essential fields exist
+    if (is_array($session) &&
+        isset($session['uid']) &&
+        isset($session['access_token']) &&
+        isset($session['sig'])) {
+      // validate the signature
+      $session_without_sig = $session;
+      unset($session_without_sig['sig']);
+      $expected_sig = self::generateSignature(
+        $session_without_sig,
+        $this->getApiSecret()
+      );
+      if ($session['sig'] != $expected_sig) {
+        self::errorLog('Got invalid session signature in cookie.');
+        $session = null;
+      }
+      // check expiry time
+    } else {
+      $session = null;
+    }
+    return $session;
+  }
+
+  /**
+   * Returns something that looks like our JS session object from the
+   * signed token's data
+   *
+   * TODO: Nuke this once the login flow uses OAuth2
+   *
+   * @param Array the output of getSignedRequest
+   * @return Array Something that will work as a session
+   */
+  protected function createSessionFromSignedRequest($data) {
+    if (!isset($data['oauth_token'])) {
+      return null;
+    }
+
+    $session = array(
+      'uid'          => $data['user_id'],
+      'access_token' => $data['oauth_token'],
+      'expires'      => $data['expires'],
+    );
+
+    // put a real sig, so that validateSignature works
+    $session['sig'] = self::generateSignature(
+      $session,
+      $this->getApiSecret()
+    );
+
+    return $session;
+  }
+
+  /**
+   * Parses a signed_request and validates the signature.
+   * Then saves it in $this->signed_data
+   *
+   * @param String A signed token
+   * @param Boolean Should we remove the parts of the payload that
+   *                are used by the algorithm?
+   * @return Array the payload inside it or null if the sig is wrong
+   */
+  protected function parseSignedRequest($signed_request) {
+    list($encoded_sig, $payload) = explode('.', $signed_request, 2);
+
+    // decode the data
+    $sig = self::base64UrlDecode($encoded_sig);
+    $data = json_decode(self::base64UrlDecode($payload), true);
+
+    if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
+      self::errorLog('Unknown algorithm. Expected HMAC-SHA256');
+      return null;
+    }
+
+    // check sig
+    $expected_sig = hash_hmac('sha256', $payload,
+                              $this->getApiSecret(), $raw = true);
+    if ($sig !== $expected_sig) {
+      self::errorLog('Bad Signed JSON signature!');
+      return null;
+    }
+
+    return $data;
+  }
+
+  /**
+   * Build the URL for api given parameters.
+   *
+   * @param $method String the method name.
+   * @return String the URL for the given parameters
+   */
+  protected function getApiUrl($method) {
+    static $READ_ONLY_CALLS =
+      array('admin.getallocation' => 1,
+            'admin.getappproperties' => 1,
+            'admin.getbannedusers' => 1,
+            'admin.getlivestreamvialink' => 1,
+            'admin.getmetrics' => 1,
+            'admin.getrestrictioninfo' => 1,
+            'application.getpublicinfo' => 1,
+            'auth.getapppublickey' => 1,
+            'auth.getsession' => 1,
+            'auth.getsignedpublicsessiondata' => 1,
+            'comments.get' => 1,
+            'connect.getunconnectedfriendscount' => 1,
+            'dashboard.getactivity' => 1,
+            'dashboard.getcount' => 1,
+            'dashboard.getglobalnews' => 1,
+            'dashboard.getnews' => 1,
+            'dashboard.multigetcount' => 1,
+            'dashboard.multigetnews' => 1,
+            'data.getcookies' => 1,
+            'events.get' => 1,
+            'events.getmembers' => 1,
+            'fbml.getcustomtags' => 1,
+            'feed.getappfriendstories' => 1,
+            'feed.getregisteredtemplatebundlebyid' => 1,
+            'feed.getregisteredtemplatebundles' => 1,
+            'fql.multiquery' => 1,
+            'fql.query' => 1,
+            'friends.arefriends' => 1,
+            'friends.get' => 1,
+            'friends.getappusers' => 1,
+            'friends.getlists' => 1,
+            'friends.getmutualfriends' => 1,
+            'gifts.get' => 1,
+            'groups.get' => 1,
+            'groups.getmembers' => 1,
+            'intl.gettranslations' => 1,
+            'links.get' => 1,
+            'notes.get' => 1,
+            'notifications.get' => 1,
+            'pages.getinfo' => 1,
+            'pages.isadmin' => 1,
+            'pages.isappadded' => 1,
+            'pages.isfan' => 1,
+            'permissions.checkavailableapiaccess' => 1,
+            'permissions.checkgrantedapiaccess' => 1,
+            'photos.get' => 1,
+            'photos.getalbums' => 1,
+            'photos.gettags' => 1,
+            'profile.getinfo' => 1,
+            'profile.getinfooptions' => 1,
+            'stream.get' => 1,
+            'stream.getcomments' => 1,
+            'stream.getfilters' => 1,
+            'users.getinfo' => 1,
+            'users.getloggedinuser' => 1,
+            'users.getstandardinfo' => 1,
+            'users.hasapppermission' => 1,
+            'users.isappuser' => 1,
+            'users.isverified' => 1,
+            'video.getuploadlimits' => 1);
+    $name = 'api';
+    if (isset($READ_ONLY_CALLS[strtolower($method)])) {
+      $name = 'api_read';
+    }
+    return self::getUrl($name, 'restserver.php');
+  }
+
+  /**
+   * Build the URL for given domain alias, path and parameters.
+   *
+   * @param $name String the name of the domain
+   * @param $path String optional path (without a leading slash)
+   * @param $params Array optional query parameters
+   * @return String the URL for the given parameters
+   */
+  protected function getUrl($name, $path='', $params=array()) {
+    $url = self::$DOMAIN_MAP[$name];
+    if ($path) {
+      if ($path[0] === '/') {
+        $path = substr($path, 1);
+      }
+      $url .= $path;
+    }
+    if ($params) {
+      $url .= '?' . http_build_query($params, null, '&');
+    }
+    return $url;
+  }
+
+  /**
+   * Returns the Current URL, stripping it of known FB parameters that should
+   * not persist.
+   *
+   * @return String the current URL
+   */
+  protected function getCurrentUrl() {
+    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on'
+      ? 'https://'
+      : 'http://';
+    $currentUrl = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
+    $parts = parse_url($currentUrl);
+
+    // drop known fb params
+    $query = '';
+    if (!empty($parts['query'])) {
+      $params = array();
+      parse_str($parts['query'], $params);
+      foreach(self::$DROP_QUERY_PARAMS as $key) {
+        unset($params[$key]);
+      }
+      if (!empty($params)) {
+        $query = '?' . http_build_query($params, null, '&');
+      }
+    }
+
+    // use port if non default
+    $port =
+      isset($parts['port']) &&
+      (($protocol === 'http://' && $parts['port'] !== 80) ||
+       ($protocol === 'https://' && $parts['port'] !== 443))
+      ? ':' . $parts['port'] : '';
+
+    // rebuild
+    return $protocol . $parts['host'] . $port . $parts['path'] . $query;
+  }
+
+  /**
+   * Generate a signature for the given params and secret.
+   *
+   * @param Array $params the parameters to sign
+   * @param String $secret the secret to sign with
+   * @return String the generated signature
+   */
+  protected static function generateSignature($params, $secret) {
+    // work with sorted data
+    ksort($params);
+
+    // generate the base string
+    $base_string = '';
+    foreach($params as $key => $value) {
+      $base_string .= $key . '=' . $value;
+    }
+    $base_string .= $secret;
+
+    return md5($base_string);
+  }
+
+  /**
+   * Prints to the error log if you aren't in command line mode.
+   *
+   * @param String log message
+   */
+  protected static function errorLog($msg) {
+    // disable error log if we are running in a CLI environment
+    // @codeCoverageIgnoreStart
+    if (php_sapi_name() != 'cli') {
+      error_log($msg);
+    }
+    // uncomment this if you want to see the errors on the page
+    // print 'error_log: '.$msg."\n";
+    // @codeCoverageIgnoreEnd
+  }
+
+  /**
+   * Base64 encoding that doesn't need to be urlencode()ed.
+   * Exactly the same as base64_encode except it uses
+   *   - instead of +
+   *   _ instead of /
+   *
+   * @param String base64UrlEncodeded string
+   */
+  protected static function base64UrlDecode($input) {
+    return base64_decode(strtr($input, '-_', '+/'));
+  }
+}
Index: extensions/FacebookPlug/Server/tags/1.0.0/include/functions.php
===================================================================
--- extensions/FacebookPlug/Server/tags/1.0.0/include/functions.php	(revision 8485)
+++ extensions/FacebookPlug/Server/tags/1.0.0/include/functions.php	(revision 8485)
@@ -0,0 +1,260 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | FacebookPlug - a Piwigo Plugin                                        |
+// | Copyright (C) 2010-2011 Ruben ARNAUD - rub@piwigo.org                 |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+defined('FACEBOOKPLUG_ROOT_PATH') or trigger_error('Hacking attempt!', E_USER_ERROR);
+
+function fbp_mkdir($dir)
+{
+  if ( !is_dir($dir) )
+  {
+    if (substr(PHP_OS, 0, 3) == 'WIN')
+    {
+      $dir = str_replace('/', DIRECTORY_SEPARATOR, $dir);
+    }
+    $umask = umask(0);
+    $mkd = @mkdir($dir, 0755, true);
+    umask($umask);
+  }
+}
+
+// Copy from Piwigo application
+// get_extension returns the part of the string after the last "."
+function fbp_get_extension( $filename )
+{
+  return substr( strrchr( $filename, '.' ), 1, strlen ( $filename ) );
+}
+
+// Copy from Piwigo application
+function fbp_url_is_remote($url)
+{
+  if ( strncmp($url, 'http://', 7)==0
+    or strncmp($url, 'https://', 8)==0 )
+  {
+    return true;
+  }
+  return false;
+}
+
+/**
+ * Retrieve data from external URL
+ * Copy from Piwigo application
+ *
+ * @param string $src: URL
+ * @param global $dest: can be a file ressource or string
+ * @return bool
+ */
+function fbp_fetchRemote($src, &$dest, $user_agent='Piwigo', $step=0)
+{
+  // Try to retrieve data from local file?
+  if (!fbp_url_is_remote($src))
+  {
+    $content = @file_get_contents($src);
+    if ($content !== false)
+    {
+      is_resource($dest) ? @fwrite($dest, $content) : $dest = $content;
+      return true;
+    }
+    else
+    {
+      return false;
+    }
+  }
+
+  // After 3 redirections, return false
+  if ($step > 3) return false;
+
+  // Initialize $dest
+  is_resource($dest) or $dest = '';
+
+  // Try curl to read remote file
+  if (function_exists('curl_init'))
+  {
+    $ch = @curl_init();
+    @curl_setopt($ch, CURLOPT_URL, $src);
+    @curl_setopt($ch, CURLOPT_HEADER, 1);
+    @curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
+    @curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
+    $content = @curl_exec($ch);
+    $header_length = @curl_getinfo($ch, CURLINFO_HEADER_SIZE);
+    $status = @curl_getinfo($ch, CURLINFO_HTTP_CODE);
+    @curl_close($ch);
+    if ($content !== false and $status >= 200 and $status < 400)
+    {
+      if (preg_match('/Location:\s+?(.+)/', substr($content, 0, $header_length), $m))
+      {
+        return fbp_fetchRemote($m[1], $dest, $user_agent, $step+1);
+      }
+      $content = substr($content, $header_length);
+      is_resource($dest) ? @fwrite($dest, $content) : $dest = $content;
+      return true;
+    }
+  }
+
+  // Try file_get_contents to read remote file
+  if (ini_get('allow_url_fopen'))
+  {
+    $content = @file_get_contents($src);
+    if ($content !== false)
+    {
+      is_resource($dest) ? @fwrite($dest, $content) : $dest = $content;
+      return true;
+    }
+  }
+
+  // Try fsockopen to read remote file
+  $src = parse_url($src);
+  $host = $src['host'];
+  $path = isset($src['path']) ? $src['path'] : '/';
+  $path .= isset($src['query']) ? '?'.$src['query'] : '';
+
+  if (($s = @fsockopen($host,80,$errno,$errstr,5)) === false)
+  {
+    return false;
+  }
+
+  fwrite($s,
+    "GET ".$path." HTTP/1.0\r\n"
+    ."Host: ".$host."\r\n"
+    ."User-Agent: ".$user_agent."\r\n"
+    ."Accept: */*\r\n"
+    ."\r\n"
+  );
+
+  $i = 0;
+  $in_content = false;
+  while (!feof($s))
+  {
+    $line = fgets($s);
+
+    if (rtrim($line,"\r\n") == '' && !$in_content)
+    {
+      $in_content = true;
+      $i++;
+      continue;
+    }
+    if ($i == 0)
+    {
+      if (!preg_match('/HTTP\/(\\d\\.\\d)\\s*(\\d+)\\s*(.*)/',rtrim($line,"\r\n"), $m))
+      {
+        fclose($s);
+        return false;
+      }
+      $status = (integer) $m[2];
+      if ($status < 200 || $status >= 400)
+      {
+        fclose($s);
+        return false;
+      }
+    }
+    if (!$in_content)
+    {
+      if (preg_match('/Location:\s+?(.+)$/',rtrim($line,"\r\n"),$m))
+      {
+        fclose($s);
+        return fbp_fetchRemote(trim($m[1]),$dest,$user_agent,$step+1);
+      }
+      $i++;
+      continue;
+    }
+    is_resource($dest) ? @fwrite($dest, $line) : $dest .= $line;
+    $i++;
+  }
+  fclose($s);
+  return true;
+}
+
+/**
+ * Return basename of the current script
+ * Copy from Piwigo application
+ * Lower case convertion is applied on return value
+ * Return value is without file extention ".php"
+ *
+ * @param void
+ *
+ * @return script basename
+ */
+function fbp_script_basename()
+{
+  global $conf;
+
+  foreach (array('SCRIPT_NAME', 'SCRIPT_FILENAME', 'PHP_SELF') as $value)
+  {
+    if (!empty($_SERVER[$value]))
+    {
+      $filename = strtolower($_SERVER[$value]);
+      $basename = basename($filename, '.php');
+      if (!empty($basename))
+      {
+        return $basename;
+      }
+    }
+  }
+  return '';
+}
+
+function  fbp_db_query($query)
+{
+  $result = mysql_query($query);
+  if (!$result)
+  {
+    die('Invalid query: [mysql error '.mysql_errno().'] '.mysql_error()."\n".$query);
+  }
+}
+
+function fbp_db_log()
+{  
+  $link = @mysql_connect(FBP_HOST, FBP_USER, FBP_PASSWORD);
+  if (!$link)
+  {
+    die("Can't connect to server");
+  }
+  if (!mysql_select_db(FBP_BASE, $link))
+  {
+    die('Connection to server succeed, but it was impossible to connect to database');
+  }
+
+  fbp_db_query('set names "utf8"');
+
+  fbp_db_query("
+insert into
+  FBP_HISTORY
+(
+  VERSION,
+  SCRIPT_NAME,
+  IP,
+  IMAGE_URL,
+  PICTURE_URL,
+  GALLERY_TITLE,
+  PICTURE_TITLE
+)
+values
+(
+  '".mysql_real_escape_string(FBP_VERSION)."',
+  '".mysql_real_escape_string(fbp_script_basename())."',
+  '".mysql_real_escape_string($_SERVER['REMOTE_ADDR'])."',
+  '".mysql_real_escape_string(@$_GET['u'])."',
+  '".mysql_real_escape_string(@$_GET['pu'])."',
+  '".mysql_real_escape_string(@$_GET['gt'])."',
+  '".mysql_real_escape_string(@$_GET['pt'])."'
+);
+");
+}
+
+?>
Index: extensions/FacebookPlug/Server/tags/1.0.0/index.php
===================================================================
--- extensions/FacebookPlug/Server/tags/1.0.0/index.php	(revision 8485)
+++ extensions/FacebookPlug/Server/tags/1.0.0/index.php	(revision 8485)
@@ -0,0 +1,27 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | FacebookPlug - a Piwigo Plugin                                        |
+// | Copyright (C) 2010-2011 Ruben ARNAUD - rub@piwigo.org                 |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+// Recursive call
+$url = 'http://www.facebook.com/';
+header( 'Request-URI: '.$url );
+header( 'Content-Location: '.$url );
+header( 'Location: '.$url );
+exit();
+?>
Index: extensions/FacebookPlug/Server/tags/1.0.0/upload_photo.php
===================================================================
--- extensions/FacebookPlug/Server/tags/1.0.0/upload_photo.php	(revision 8485)
+++ extensions/FacebookPlug/Server/tags/1.0.0/upload_photo.php	(revision 8485)
@@ -0,0 +1,91 @@
+<?php
+// +-----------------------------------------------------------------------+
+// | FacebookPlug - a Piwigo Plugin                                        |
+// | Copyright (C) 2010-2011 Ruben ARNAUD - rub@piwigo.org                 |
+// +-----------------------------------------------------------------------+
+// | This program is free software; you can redistribute it and/or modify  |
+// | it under the terms of the GNU General Public License as published by  |
+// | the Free Software Foundation                                          |
+// |                                                                       |
+// | This program is distributed in the hope that it will be useful, but   |
+// | WITHOUT ANY WARRANTY; without even the implied warranty of            |
+// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU      |
+// | General Public License for more details.                              |
+// |                                                                       |
+// | You should have received a copy of the GNU General Public License     |
+// | along with this program; if not, write to the Free Software           |
+// | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, |
+// | USA.                                                                  |
+// +-----------------------------------------------------------------------+
+
+define('FACEBOOKPLUG_ROOT_PATH','./');
+
+require_once 'include/common.php';
+
+?>
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
+<html>
+<head>
+  <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
+</head>
+<body>
+  <center>
+    <div id="loading"><img src="./image/image_85486.gif" alt="Loading"></div>
+    <div id="infos">
+      <img src="./image/infos.png" alt="Infos">
+      <a id ="info_a" href="" onclick="window.open(this.href); return false;">
+        <img src="<?php echo addslashes($_GET['u']) ?>" alt="Image" style="height:50px">
+      </a>
+    </div>
+    <div id="errors">
+        <img src="./image/errors.png" alt="Error">
+        <textearea id="error_result"></textearea>
+    </div>
+  </center>
+ 
+  <script type="text/javascript">
+    $(document).ready(function () {
+      $("#errors").hide();
+      $("#infos").hide();
+      $.get(
+      './do_upload_photo.php',
+      {u:"<?php echo addslashes($_GET['u']) ?>", pu: "<?php echo addslashes($_GET['pu']) ?>", pt: "<?php echo addslashes($_GET['pt']) ?>", gt: "<?php echo addslashes($_GET['gt']) ?>"},
+      function(data) {
+        $("#loading").hide();
+        is_ok = ! isNaN(data);
+        if (is_ok)
+        {
+          div_id = "#infos";
+          fb_photo_page = 'http://www.facebook.com/photo.php?fbid='+data;
+          $('#info_a').attr('href', fb_photo_page);
+        }
+        else
+        {
+          div_id = "#errors";
+          $('#error_result').html(data);
+        }
+        $(div_id).show();
+        $(div_id).fadeOut(3000, function ()
+          {
+            if (is_ok) { window.open(fb_photo_page); }
+            window.close();
+          });
+      });
+  });
+  </script>
+<!-- google-analytics -->
+<script type="text/javascript">
+  var _gaq = _gaq || [];
+  _gaq.push(['_setAccount', 'UA-2272624-7']);
+  _gaq.push(['_trackPageview']);
+
+  (function() {
+    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
+    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
+    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
+  })();
+
+</script>
+<!-- google-analytics -->
+</body>
+</html>
