Page MenuHomeCode

No OneTemporary

diff --git a/controllers/anonymous.php b/controllers/anonymous.php
index bbd982c..75ac6a3 100644
--- a/controllers/anonymous.php
+++ b/controllers/anonymous.php
@@ -1,152 +1,152 @@
<?php
/**
* Content for anonymous users
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* This controller handles the pages for not logged in users.
*
* It recognizes the following URLs:
* /tour a redirect to tour.html file, a visite guidée drom Zed ;
* /invite the page to claim the invites.
*
* In all other cases, it prints the login form.
*
* @package Zed
* @subpackage Controllers
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @copyright 2010 Sébastien Santoro aka Dereckson
* @license http://www.opensource.org/licenses/bsd-license.php BSD
* @version 0.1
* @link http://scherzo.dereckson.be/doc/zed
* @link http://zed.dereckson.be/
* @filesource
*/
//
// Prepares the page
//
switch ($url[0]) {
case 'tour':
//The user have forgotten .html, let's redirect him
header('Location: ' . $Config['StaticContentURL'] . '/tour.html');
exit;
case 'invite':
//Invite form
if ($_POST['form'] == 'account.create') {
//User tries to claim its invite to create an account
require_once('includes/objects/invite.php');
require_once('includes/objects/user.php');
//Gets invite
$invite = new Invite($_POST['invite_code']);
if ($invite->lastError != '') {
//Not existant invite.
$smarty->assign('NOTIFY', lang_get("IncorrectInviteCode"));
} elseif ($invite->is_claimed()) {
//The invitation have already claimed by someone else.
$smarty->assign('NOTIFY', lang_get("InviteCodeAlreadyClaimed"));
} else {
//Checks if the given information is correct
//We ignore bad mails. All we really need is a login and a pass.
//We fill our array $errors with all the errors
$errors = array();
if (!$_POST['username']) {
$errors[] = lang_get('MissingUsername');
} elseif (!User::is_available_login($_POST['username'])) {
$errors[] = lang_get('LoginUnavailable');
}
if (User::get_username_from_email($_POST['email']) !== false) {
$errors[] = "There is already an account with this e-mail.";
}
if (!$_POST['passwd']) {
$errors[] = lang_get('MissingPassword');
}
if (count($errors)) {
$smarty->assign('WAP', join('<br />', $errors));
} else {
//Creates account
$user = new User();
$user->regdate = time();
$user->generate_id();
$user->name = $_POST['username'];
$user->active = 1;
$user->email = $_POST['email'];
$user->set_password($_POST['passwd']);
$user->save_to_database();
//Updates invite
$invite->to_user_id = $user->id;
$invite->save_to_database();
//Notifies inviter
require_once('includes/objects/message.php');
$message = new Message();
$message->from = 0;
$message->to = $invite->from_perso_id;
$message->text = sprintf(lang_get('InviteHaveBeenClaimed'), $invite->code);
$message->send();
//Logs in user
login($user->id, $user->name);
//Prints confirm message
$smarty->assign('WAP', lang_get("AccountCreated"));
//Redirects users to homepage
header('refresh: 5; url=' . get_url());
//Calls void controller
$smarty->assign('screen', 'user.create');
define('NO_FOOTER_EXTRA', true);
include("void.php");
exit;
}
}
//Keeps username, email, invite code printed on account create form
$smarty->assign('username', $_POST['username']);
$smarty->assign('invite_code', $_POST['invite_code']);
$smarty->assign('email', $_POST['email']);
}
//If the invite code is specified, checks format
if ($url[1]) {
if (preg_match("/^([A-Z]){3}([0-9]){3}$/i", $url[1])) {
$smarty->assign('invite_code', strtoupper($url[1]));
} else {
$smarty->assign('NOTIFY', lang_get("IncorrectInviteCode"));
}
}
$template = 'account_create.tpl';
break;
default:
//Login form
if (array_key_exists('LastUsername', $_COOKIE))
$smarty->assign('username', $_COOKIE['LastUsername']);
if (array_key_exists('LastOpenID', $_COOKIE))
$smarty->assign('OpenID', $_COOKIE['LastOpenID']);
- $smarty->assign('LoginError', $LoginError);
+ $smarty->assign('LoginError', $loginError);
$template = 'login.tpl';
break;
}
//
// HTML output
//
if ($template) $smarty->display($template);
-?>
\ No newline at end of file
+?>
diff --git a/dev/quux.php b/dev/quux.php
index 68bb15c..526af8b 100644
--- a/dev/quux.php
+++ b/dev/quux.php
@@ -1,138 +1,159 @@
-<?php
-
- require_once('includes/objects/ship.php');
- require_once('includes/objects/port.php');
- require_once('includes/objects/application.php');
- require_once('includes/objects/content.php');
- require_once('includes/objects/message.php');
- require_once('includes/objects/invite.php');
- require_once('includes/cache/cache.php');
-
- include('controllers/header.php');
-
- $case = 'GeoPointPolarZ';
-
- switch ($case) {
- case 'GeoPointPolarZ':
- require_once('includes/geo/pointPolarZ.php');
- echo "<H2>GeoPointPolarZ</H2>";
- $point = GeoPointPolarZ::fromString("(48, 30°, 3)");
- printf("Secteur T%dC%d, zone %d-%d");
- dprint_r($point);
- break;
-
- case 'index_scenes':
- $time[] = microtime();
- require_once('includes/geo/scene.php');
- require_once('includes/geo/sceneindex.php');
- $cache = Cache::load();
- if ($index = $cache->get('GeoSceneIndex')) {
- $index = unserialize($index);
- } else {
- $index = GeoSceneIndex::Load(SCENE_DIR);
- $cache->set('GeoSceneIndex', serialize($index));
- }
- $time[] = microtime();
- echo '<H2>GeoSceneIndex</H2>';
- dprint_r($index);
- echo '<H2>Time (ms)</H2>';
- dprint_r(1000 * ($time[1] - $time[0]));
- dprint_r($time);
- break;
-
- case 'travel':
- require_once('includes/travel/travel.php');
- $travel = Travel::load();
- dieprint_r($travel);
- break;
-
- case 'spherical':
- require_once('includes/geo/galaxy.php');
- echo '<H2>Spherical coordinates test</H2>';
- echo '<table cellpadding=8>';
- echo "<tr><th>Name</th><th>Type</th><th>Cartesian coords</th><th>Spherical I</th><th>Spherical II</th><th>Pencil coordinates</th></tr>";
- $objects = GeoGalaxy::get_coordinates();
- foreach ($objects as $row) {
- echo "<tr><th style='text-align: left'>$row[0]</th><td>$row[1]</td><td>$row[2]</td>";
- $pt = $row[2];
- echo '<td>(', implode(', ', $pt->to_spherical()), ')</td>';
- echo '<td>(', implode(', ', $pt->to_spherical2()), ')</td>';
- $pt->translate(500, 300, 200, 2);
- echo '<td>', $pt, '</td>';
- echo '</tr>';
- }
- echo '</table>';
- break;
-
- case 'travel':
- require_once('includes/travel/travel.php');
- require_once('includes/travel/place.php');
-
- $cache = Cache::load();
- $travel = $cache->get('zed_travel');
- if ($travel == '') {
- $travel_nocached = new Travel();
- $travel_nocached->load_xml("content/travel.xml");
- $cache->set('zed_travel', serialize($travel_nocached));
- } else {
- $travel = unserialize($travel);
- }
- dieprint_r($travel);
- break;
-
- case 'perso.create.notify':
- $testperso = Perso::get(4733);
- $message = new Message();
- $message->from = 0;
- $message->to = invite::who_invited(4733);
- $url = get_server_url() . get_url('who', $testperso->nickname);
- $message->text = sprintf(lang_get('InvitePersoCreated'), $testperso->name, $url);
- $message->send();
- dieprint_r($message);
- break;
-
- case 'pushdata';
- echo '
-<h2>/api.php/app/pushdata</h2>
-<form method="post" action="/api.php/app/pushdata?mode=file&key=37d839ba-f9fc-42ca-a3e8-28053e979b90" enctype="multipart/form-data">
- <input type="file" name="datafile" /><br />
- <input type="submit" value="Send file" />
-</form>
- ';
- break;
-
- case 'thumbnail':
- $content = new Content(1);
- dprint_r($content);
- $content->generate_thumbnail();
- break;
-
- case 'port':
- echo '<h2>Port::from_location test</h2>';
- $locations = array("B00002", "B00002123", "B00001001", "xyz: [800, 42, 220]");
- foreach ($locations as $location) {
- dprint_r(Port::from_location($location));
- }
- break;
-
- case 'ext':
- $file = 'dev/foo.tar';
- echo "<h2>$file</h2>";
- echo "<h3>.tar.bz2</h3>";
- echo ereg('\.tar\.bz2$', $file);
- echo "<h3>.tar</h3>";
- echo ereg('\.tar$', $file);
- break;
-
- case 'app':
- echo Application::from_api_key("37d839ba-f9fc-42ca-a3e8-28053e979b90")->generate_userkey();
- break;
-
- case '':
- dieprint_r("No case currently selected.");
- break;
- }
-
- include('controllers/footer.php');
-
-?>
+<?php
+
+ require_once('includes/objects/ship.php');
+ require_once('includes/objects/port.php');
+ require_once('includes/objects/application.php');
+ require_once('includes/objects/content.php');
+ require_once('includes/objects/message.php');
+ require_once('includes/objects/invite.php');
+ require_once('includes/cache/cache.php');
+
+ include('controllers/header.php');
+
+ $case = 'YubiCloud';
+
+ switch ($case) {
+ case 'YubiCloud':
+ require_once('Auth/Yubico.php');
+ echo '<h2>YubiKey</h2>';
+ if (!array_key_exists('YubiCloud', $Config)) {
+ message_die(GENERAL_ERROR, "YubiCloud authentication not configured. Add \$Config['YubiCloud']['ClientID'] and \$Config['YubiCloud']['SecretKey'] to your config.");
+ }
+ if (!$key = $_GET['OTP']) message_die(GENERAL_ERROR, "Please add in URL ?OTP=, then put your cursor at right of the = and press your YubiKey button");
+ $yubi = new Auth_Yubico($Config['YubiCloud']['ClientID'], $Config['YubiCloud']['SecreyKey']);
+ if (!$data = $yubi->parsePasswordOTP($key)) {
+ message_die(GENERAL_ERROR, "This is not an YubiKey OTP.");
+ }
+ $prefix = $data['prefix'];
+ $auth = $yubi->verify($key);
+ if (@PEAR::isError($auth)) {
+ if ($auth->getMessage() == 'REPLAYED_OTP') message_die("This OTP has already been used.");
+ message_die(HACK_ERROR, "<p>Authentication failed: " . $auth->getMessage() . "</p><p>Debug: " . $yubi->getLastResponse() . "</p>");
+ } else {
+ print "<p>You are authenticated!</p>";
+ }
+ break;
+
+ case 'GeoPointPolarZ':
+ require_once('includes/geo/pointPolarZ.php');
+ echo "<H2>GeoPointPolarZ</H2>";
+ $point = GeoPointPolarZ::fromString("(48, 30°, 3)");
+ printf("Secteur T%dC%d, zone %d-%d");
+ dprint_r($point);
+ break;
+
+ case 'index_scenes':
+ $time[] = microtime();
+ require_once('includes/geo/scene.php');
+ require_once('includes/geo/sceneindex.php');
+ $cache = Cache::load();
+ if ($index = $cache->get('GeoSceneIndex')) {
+ $index = unserialize($index);
+ } else {
+ $index = GeoSceneIndex::Load(SCENE_DIR);
+ $cache->set('GeoSceneIndex', serialize($index));
+ }
+ $time[] = microtime();
+ echo '<H2>GeoSceneIndex</H2>';
+ dprint_r($index);
+ echo '<H2>Time (ms)</H2>';
+ dprint_r(1000 * ($time[1] - $time[0]));
+ dprint_r($time);
+ break;
+
+ case 'travel':
+ require_once('includes/travel/travel.php');
+ $travel = Travel::load();
+ dieprint_r($travel);
+ break;
+
+ case 'spherical':
+ require_once('includes/geo/galaxy.php');
+ echo '<H2>Spherical coordinates test</H2>';
+ echo '<table cellpadding=8>';
+ echo "<tr><th>Name</th><th>Type</th><th>Cartesian coords</th><th>Spherical I</th><th>Spherical II</th><th>Pencil coordinates</th></tr>";
+ $objects = GeoGalaxy::get_coordinates();
+ foreach ($objects as $row) {
+ echo "<tr><th style='text-align: left'>$row[0]</th><td>$row[1]</td><td>$row[2]</td>";
+ $pt = $row[2];
+ echo '<td>(', implode(', ', $pt->to_spherical()), ')</td>';
+ echo '<td>(', implode(', ', $pt->to_spherical2()), ')</td>';
+ $pt->translate(500, 300, 200, 2);
+ echo '<td>', $pt, '</td>';
+ echo '</tr>';
+ }
+ echo '</table>';
+ break;
+
+ case 'travel':
+ require_once('includes/travel/travel.php');
+ require_once('includes/travel/place.php');
+
+ $cache = Cache::load();
+ $travel = $cache->get('zed_travel');
+ if ($travel == '') {
+ $travel_nocached = new Travel();
+ $travel_nocached->load_xml("content/travel.xml");
+ $cache->set('zed_travel', serialize($travel_nocached));
+ } else {
+ $travel = unserialize($travel);
+ }
+ dieprint_r($travel);
+ break;
+
+ case 'perso.create.notify':
+ $testperso = Perso::get(4733);
+ $message = new Message();
+ $message->from = 0;
+ $message->to = invite::who_invited(4733);
+ $url = get_server_url() . get_url('who', $testperso->nickname);
+ $message->text = sprintf(lang_get('InvitePersoCreated'), $testperso->name, $url);
+ $message->send();
+ dieprint_r($message);
+ break;
+
+ case 'pushdata';
+ echo '
+<h2>/api.php/app/pushdata</h2>
+<form method="post" action="/api.php/app/pushdata?mode=file&key=37d839ba-f9fc-42ca-a3e8-28053e979b90" enctype="multipart/form-data">
+ <input type="file" name="datafile" /><br />
+ <input type="submit" value="Send file" />
+</form>
+ ';
+ break;
+
+ case 'thumbnail':
+ $content = new Content(1);
+ dprint_r($content);
+ $content->generate_thumbnail();
+ break;
+
+ case 'port':
+ echo '<h2>Port::from_location test</h2>';
+ $locations = array("B00002", "B00002123", "B00001001", "xyz: [800, 42, 220]");
+ foreach ($locations as $location) {
+ dprint_r(Port::from_location($location));
+ }
+ break;
+
+ case 'ext':
+ $file = 'dev/foo.tar';
+ echo "<h2>$file</h2>";
+ echo "<h3>.tar.bz2</h3>";
+ echo ereg('\.tar\.bz2$', $file);
+ echo "<h3>.tar</h3>";
+ echo ereg('\.tar$', $file);
+ break;
+
+ case 'app':
+ echo Application::from_api_key("37d839ba-f9fc-42ca-a3e8-28053e979b90")->generate_userkey();
+ break;
+
+ case '':
+ dieprint_r("No case currently selected.");
+ break;
+ }
+
+ include('controllers/footer.php');
+
+?>
diff --git a/includes/auth/IAuthentication.php b/includes/auth/IAuthentication.php
new file mode 100644
index 0000000..9b0b07f
--- /dev/null
+++ b/includes/auth/IAuthentication.php
@@ -0,0 +1,55 @@
+<?php
+
+/**
+ * Authentication method interface.
+ *
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2013, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * @package Zed
+ * @subpackage Auth
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @copyright 2013 Sébastien Santoro aka Dereckson
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @link http://scherzo.dereckson.be/doc/zed
+ * @link http://zed.dereckson.be/
+ * @filesource
+ */
+
+/**
+ * Authentication method interface.
+ */
+interface IAuthentication {
+ /**
+ * Determines if an user has been authenticated.
+ *
+ * @return boolean true if the user has successfully been authenticated; otherwise, false.
+ */
+ public function isValid ();
+
+ /**
+ * Gets the last authentication error
+ *
+ * @return string The last authentication error
+ */
+ public function getError();
+
+ /**
+ * Gets the user_id matching the key
+ *
+ * @return int the user ID
+ */
+ public function getUserID ();
+
+ /**
+ * Determines if the next authentication method could be tried if this one failed.
+ *
+ * This allow when a method has failed in such a way the user must be warned to warn it,
+ * returning false.
+ *
+ * @return bool true if authentication can go on to the next method; otherwise, false
+ */
+ public function canTryNextAuthenticationMethod();
+}
diff --git a/includes/auth/UserPasswordAuthentication.php b/includes/auth/UserPasswordAuthentication.php
new file mode 100644
index 0000000..c936e07
--- /dev/null
+++ b/includes/auth/UserPasswordAuthentication.php
@@ -0,0 +1,141 @@
+<?php
+
+/**
+ * User/password authentication class.
+ *
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2013, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * @package Zed
+ * @subpackage Auth
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @copyright 2013 Sébastien Santoro aka Dereckson
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @link http://scherzo.dereckson.be/doc/zed
+ * @link http://zed.dereckson.be/
+ * @filesource
+ */
+
+/**
+ * UserPasswordAuthentication class
+ *
+ * Authenticates a user with an username and a password
+ */
+
+/**
+ * Login/pass authentication
+ */
+class UserPasswordAuthentication implements IAuthentication {
+ /**
+ * The username
+ * @var string
+ */
+ private $username;
+
+ /**
+ * The password in clear text
+ * @var string
+ */
+ private $password;
+
+ /**
+ * The last authentication error
+ * @var string
+ */
+ private $error;
+
+ /**
+ * The user_id matching the username
+ * @var int
+ */
+ private $user_id;
+
+ /**
+ * Indicates if the error MUST be returned to the user
+ * @var string
+ */
+ private $mustThrowError = false;
+
+ /**
+ * Initializes a new instance of the UserPasswordAuthentication class
+ *
+ * @param string $username The username
+ * @param string $passwordThe password
+ */
+ public function __construct ($username, $password) {
+ $this->username = $username;
+ $this->password = $password;
+ }
+
+ /**
+ * Gets the hash of the password
+ *
+ * @param string $password The password in clear text
+ * @return string The hashed password
+ */
+ function getPasswordHash ($password) {
+ return md5($password); //TODO: replace this by a salted MD5 or better, by another algo.
+ }
+
+ /**
+ * Determines if the login/pass is valid
+ *
+ * @return bool true if the login/pass is valid; otherwise, false.
+ */
+ function isValid () {
+ global $db;
+
+ $sql = "SELECT user_password, user_id FROM " . TABLE_USERS . " WHERE username = '$this->username'";
+ if (!$result = $db->sql_query($sql)) {
+ message_die(SQL_ERROR, "Can't query users table.", '', __LINE__, __FILE__, $sql);
+ }
+ if ($row = $db->sql_fetchrow($result)) {
+ $this->user_id = $row['user_id'];
+ if (!$row['user_password']) {
+ $this->error = "This account exists but haven't a password defined. Use OpenID or contact dereckson (at) espace-win.org to fix that.";
+ $mustThrowError = true;
+ } elseif ($row['user_password'] != $this->getPasswordHash($this->password)) {
+ //PASS NOT OK
+ $this->error = "Incorrect password.";
+ } else {
+ return true;
+ }
+ } else {
+ $this->error = "Login not found.";
+ $mustThrowError = true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Gets the last authentication error
+ *
+ * @return string The last error
+ */
+ function getError () {
+ return $this->error;
+ }
+
+ /**
+ * Gets the user_id matching the username
+ * You first need to validate the username, calling the isValid method.
+ *
+ * @return int The user ID
+ */
+ function getUserID () {
+ return $this->user_id;
+ }
+
+ /**
+ * Determines if the next authentication method could be tried if this one failed.
+ *
+ * @return bool true if authentication can go on to the next method; otherwise, false
+ */
+ function canTryNextAuthenticationMethod () {
+ return !$this->mustThrowError;
+ }
+
+}
diff --git a/includes/auth/YubiCloudAuthentication.php b/includes/auth/YubiCloudAuthentication.php
new file mode 100644
index 0000000..56444ef
--- /dev/null
+++ b/includes/auth/YubiCloudAuthentication.php
@@ -0,0 +1,192 @@
+<?php
+
+/**
+ * YubiCloud authentication class.
+ *
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2013, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * @package Zed
+ * @subpackage Auth
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @copyright 2013 Sébastien Santoro aka Dereckson
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @link http://scherzo.dereckson.be/doc/zed
+ * @link http://zed.dereckson.be/
+ * @filesource
+ */
+
+require_once('Auth/Yubico.php');
+
+/**
+ * YubiCloudAuthentication class
+ *
+ * Authenticates a user through YubiCloud
+ */
+class YubiCloudAuthentication implements IAuthentication {
+ /**
+ * The key
+ * @var string
+ */
+ private $key;
+
+ /**
+ * The username who should match the key
+ * @var string
+ */
+ private $username;
+
+ /**
+ * The user_id
+ * @var int
+ */
+ private $user_id;
+
+ /**
+ * Indicates if the error MUST be returned to the user
+ * @var string
+ */
+ private $mustThrowError = false;
+
+ /**
+ * The last validation error
+ * @var string
+ */
+ public $error;
+
+ /**
+ * Initializes a new instance of the key
+ *
+ * @param string $key The key
+ */
+ public function __construct ($key, $username = null) {
+ $this->username = $username;
+ $this->key = $key;
+ }
+
+ /**
+ * Validates the specified key's characters to determine if it looks like an OTP
+ *
+ * @return boolean true if the input seems an OTP key; otherwise, false.
+ */
+ function looksValidOTP () {
+ return preg_match("/^[cbdefghijklnrtuv]{32,48}$/", $this->key);
+ }
+
+ /**
+ * Gets public identity
+ *
+ * @return string Public identity
+ */
+ function getPublicIdentity () {
+ return substr($this->key, 0, 12);
+ }
+
+ /**
+ * Validates an OTP key against the YubiCloud servers
+ *
+ * @return boolean true if the input is a valid OTP key; otherwise, false.
+ */
+ function isValid () {
+ global $Config;
+
+ //No need to lost time to query server if format is incorrect.
+ if (!$this->looksValidOTP()) {
+ $this->error = "Not the expected YubiKey OTP format.";
+ return false;
+ }
+
+ //Query YubiCloud. We stop validation tests if that fails.
+ $yubi = new Auth_Yubico(
+ $Config['YubiCloud']['ClientID'],
+ $Config['YubiCloud']['SecreyKey']
+ );
+ $auth = $yubi->verify($this->key);
+ if (@PEAR::isError($auth)) {
+ $this->error = $auth->getMessage();
+ return false;
+ }
+
+ //Note: We first query the YubiCloud server, then we check if we can use the key
+ // as the key is an OTP (*one time* password), this allow to invalidate it.
+ // If we wouldn't do that, an attacker can reuse this password for another site.
+ if (!$this->computeUserID()) {
+ $this->error = "Valid YubiKey OTP. But the key doesn't match any account.";
+ $this->mustThrowError = true;
+ return false;
+ }
+
+ //Finally, if someone puts also a login, we'll check this user ID match this username
+ if ($this->username) {
+ $user = User::get($this->user_id);
+ if ($this->username != $user->name) {
+ $this->error = "Valid YubiKey OTP but fix or remove your username.";
+ $this->mustThrowError = true;
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ /**
+ * Gets the user_id matching the username
+ *
+ * You first need to validate the username, calling the isValid method.
+ */
+ function computeUserID () {
+ global $db;
+
+ /**
+ * Here a MySQL record for a valid OTP
+ * +---------+-----------+---------------+-----------------+---------+
+ * | auth_id | auth_type | auth_identity | auth_properties | user_id |
+ * +---------+-----------+---------------+-----------------+---------+
+ * | 2 | YubiKey | cccccccccccc | NULL | 1234 |
+ * +---------+-----------+---------------+-----------------+---------+
+ */
+ $authentication_identity = $this->getPublicIdentity();
+ $sql = "SELECT user_id FROM " . TABLE_USERS_AUTH
+ . " WHERE auth_type = 'YubiKey' AND auth_identity = '$authentication_identity'";
+ if (!$result = $db->sql_query($sql)) {
+ message_die(SQL_ERROR, "Can't query users authentication table.", '', __LINE__, __FILE__, $sql);
+ }
+ if ($row = $db->sql_fetchrow($result)) {
+ $this->user_id = $row['user_id'];
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Gets the last authentication error
+ *
+ * @return string The last authentication error
+ */
+ function getError () {
+ return $this->error;
+ }
+
+ /**
+ * Gets the user_id matching the key
+ *
+ * You first need to query the authentication table, calling the computeUserID method.
+ * This is automatically done by IsValid, as we need to validate key matches someone.
+ *
+ * @return int the user ID
+ */
+ function getUserID () {
+ return $this->user_id;
+ }
+
+ /**
+ * Determines if the next authentication method could be tried if this one failed.
+ *
+ * @return bool true if authentication can go on to the next method; otherwise, false
+ */
+ function canTryNextAuthenticationMethod () {
+ return !$this->mustThrowError;
+ }
+}
diff --git a/includes/autoload.php b/includes/autoload.php
index 44d0899..d00f0e6 100755
--- a/includes/autoload.php
+++ b/includes/autoload.php
@@ -1,59 +1,63 @@
<?php
/**
* This magic method is called when a class can't be loaded
*/
function __autoload ($className) {
//Classes
+ $classes['IAuthentication'] = './includes/auth/IAuthentication.php';
+ $classes['UserPasswordAuthentication'] = './includes/auth/UserPasswordAuthentication.php';
+ $classes['YubiCloudAuthentication'] = './includes/auth/YubiCloudAuthentication.php';
+
$classes['Cache'] = './includes/cache/cache.php';
$classes['CacheMemcached'] = './includes/cache/memcached.php';
$classes['CacheVoid'] = './includes/cache/void.php';
$classes['ContentFile'] = './includes/content/file.php';
$classes['ContentLocation'] = './includes/content/location.php';
$classes['ContentZone'] = './includes/content/zone.php';
$classes['GeoBody'] = './includes/geo/body.php';
$classes['GeoGalaxy'] = './includes/geo/galaxy.php';
$classes['GeoLocation'] = './includes/geo/location.php';
$classes['GeoOctocube'] = './includes/geo/octocube.php';
$classes['GeoPlace'] = './includes/geo/place.php';
$classes['GeoPoint3D'] = './includes/geo/point3D.php';
$classes['GeoPointPolarZ'] = './includes/geo/pointPolarZ.php';
$classes['GeoScene'] = './includes/geo/scene.php';
$classes['GeoSceneIndex'] = './includes/geo/sceneindex.php';
$classes['Application'] = './includes/objects/application.php';
$classes['Content'] = './includes/objects/content.php';
$classes['Invite'] = './includes/objects/invite.php';
$classes['Message'] = './includes/objects/message.php';
$classes['MOTD'] = './includes/objects/motd.php';
$classes['Perso'] = './includes/objects/perso.php';
$classes['Port'] = './includes/objects/port.php';
$classes['Profile'] = './includes/objects/profile.php';
$classes['ProfileComment'] = './includes/objects/profilecomment.php';
$classes['ProfilePhoto'] = './includes/objects/profilephoto.php';
$classes['Request'] = './includes/objects/request.php';
$classes['RequestReply'] = './includes/objects/requestreply.php';
$classes['Ship'] = './includes/objects/ship.php';
$classes['User'] = './includes/objects/user.php';
$classes['SettingsPage'] = './includes/settings/page.php';
$classes['Setting'] = './includes/settings/setting.php';
$classes['Settings'] = './includes/settings/settings.php';
$classes['StoryChoice'] = './includes/story/choice.php';
$classes['StoryHook'] = './includes/story/hook.php';
$classes['DemoStoryHook'] = './includes/story/hook_demo.php';
$classes['SpatioportStoryHook'] = './includes/story/hook_spatioport.php';
$classes['StorySection'] = './includes/story/section.php';
$classes['Story'] = './includes/story/story.php';
$classes['TravelPlace'] = './includes/travel/place.php';
$classes['Travel'] = './includes/travel/travel.php';
//Loader
if (array_key_exists($className, $classes)) {
require_once($classes[$className]);
}
}
diff --git a/includes/config.php b/includes/config.php
index 122e9b5..c44e831 100755
--- a/includes/config.php
+++ b/includes/config.php
@@ -1,263 +1,269 @@
-<?php
-
-/**
- * Autogenerable configuration file
- *
- * Zed. The immensity of stars. The HyperShip. The people.
- *
- * (c) 2010, Dereckson, some rights reserved.
- * Released under BSD license.
- *
- * @package Zed
- * @subpackage Keruald
- * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
- * @copyright 2010 Sébastien Santoro aka Dereckson
- * @license http://www.opensource.org/licenses/bsd-license.php BSD
- * @version 0.1
- * @link http://scherzo.dereckson.be/doc/zed
- * @link http://zed.dereckson.be/
- * @filesource
- */
-
-////////////////////////////////////////////////////////////////////////////////
-/// ///
-/// I. SQL configuration ///
-/// ///
-////////////////////////////////////////////////////////////////////////////////
-
-//SQL configuration
-$Config['sql']['product'] = 'MySQL'; //Only MySQL is currently implemented
-$Config['sql']['host'] = 'localhost';
-$Config['sql']['username'] = 'zed';
-$Config['sql']['password'] = 'zed';
-$Config['sql']['database'] = 'zed';
-
-//SQL tables
-$prefix = '';
-define('TABLE_API_KEYS', $prefix . 'api_keys');
-define('TABLE_COMMENTS', $prefix . 'comments');
-define('TABLE_CONTENT_FILES', $prefix . 'content_files');
-define('TABLE_CONTENT_LOCATIONS', $prefix . 'content_locations');
-define('TABLE_CONTENT_ZONES', $prefix . 'content_zones');
-define('TABLE_CONTENT_ZONES_LOCATIONS', $prefix . 'content_zones_locations');
-define('TABLE_LOG', $prefix . 'log');
-define('TABLE_LOG_SMARTLINE', $prefix . 'log_smartline');
-define('TABLE_MESSAGES', $prefix . 'messages');
-define('TABLE_MOTD', $prefix . 'motd');
-define('TABLE_PAGES', $prefix . 'pages');
-define('TABLE_PAGES_EDITS', $prefix . 'pages_edits');
-define('TABLE_PERSOS', $prefix . 'persos');
-define('TABLE_PERSOS_FLAGS', $prefix . 'persos_flags');
-define('TABLE_PERSOS_NOTES', $prefix . 'persos_notes');
-define('TABLE_PORTS', $prefix . 'ports');
-define('TABLE_PROFILES', $prefix . 'profiles');
-define('TABLE_PROFILES_COMMENTS', $prefix . 'profiles_comments');
-define('TABLE_PROFILES_PHOTOS', $prefix . 'profiles_photos');
-define('TABLE_PROFILES_TAGS', $prefix . 'profiles_tags');
-define('TABLE_REGISTRY', $prefix . 'registry');
-define('TABLE_REQUESTS', $prefix . 'requests');
-define('TABLE_REQUESTS_REPLIES', $prefix . 'requests_replies');
-define('TABLE_SESSIONS', $prefix . 'sessions');
-define('TABLE_SHIPS', $prefix . 'ships');
-define('TABLE_USERS', $prefix . 'users');
-define('TABLE_USERS_INVITES', $prefix . 'users_invites');
-define('TABLE_USERS_AUTH', $prefix . 'users_auth');
-
-//Geo tables
-define('TABLE_BODIES', $prefix . 'geo_bodies');
-define('TABLE_LOCATIONS', $prefix . 'geo_locations'); //Well... it's a view
-define('TABLE_PLACES', $prefix . 'geo_places');
-
-////////////////////////////////////////////////////////////////////////////////
-/// ///
-/// II. Site configuration ///
-/// ///
-////////////////////////////////////////////////////////////////////////////////
-
-//Default theme
-$Config['DefaultTheme'] = "Zed";
-
-//Dates
-date_default_timezone_set("UTC");
-
-//Secret key, used for some verification hashes in URLs or forms.
-$Config['SecretKey'] = 'Lorem ipsum dolor';
-
-//When reading files, buffer size
-define('BUFFER_SIZE', 4096);
-
-////////////////////////////////////////////////////////////////////////////////
-/// ///
-/// III. Script URLs ///
-/// ///
-////////////////////////////////////////////////////////////////////////////////
-
-/*
- * Apache httpd, without mod_rewrite:
- *
- * Subdirectory:
- * - $Config['SiteURL'] = 'http://zed.dereckson.be/hypership/index.php';
- * - $Config['BaseURL'] = '/hypership/index.php';
- *
- * Root directory:
- * - $Config['SiteURL'] = 'http://zed.dereckson.be/index.php';
- * - $Config['BaseURL'] = '/index.php';
- *
- * Apache httpd, with mod_rewrite:
- *
- * Subdirectory:
- * - $Config['SiteURL'] = 'http://zed.dereckson.be/hypership';
- * - $Config['BaseURL'] = '/hypership';
- *
- * In .htaccess or your vhost definition:
- * RewriteEngine On
- * RewriteBase /hypership/
- * RewriteCond %{REQUEST_FILENAME} !-f
- * RewriteCond %{REQUEST_FILENAME} !-d
- * RewriteRule . /hypership/index.php [L]
- *
- * Root directory:
- * - $Config['SiteURL'] = 'http://zed.dereckson.be';
- * - $Config['BaseURL'] = '';
- *
- * In .htaccess or your vhost definition:
- * RewriteEngine On
- * RewriteBase /
- * RewriteCond %{REQUEST_FILENAME} !-f
- * RewriteCond %{REQUEST_FILENAME} !-d
- * RewriteRule . /index.php [L]
- *
- * nginx:
- *
- * Use same config.php settings than Apache httpd, with mod_rewrite.
- *
- * In your server block:
- * location / {
- * #Serves static files if they exists, with one month cache
- * if (-f $request_filename) {
- * expires 30d;
- * break;
- * }
- *
- * #Sends all non existing file or directory requests to index.php
- * if (!-e request_filename) {
- * rewrite ^(.+)$ /index.php last;
- * #Or if you use a subdirectory:
- * #rewrite ^(.+)$ /hypership/index.php last;
- * }
- * }
- *
- * location ~ \.php$ {
- * #Your instructions to pass query to your FastCGI process, like:
- * fastcgi_pass 127.0.0.1:9000;
- * fastcgi_param SCRIPT_FILENAME /var/www/zed$fastcgi_script_name;
- * include fastcgi_params;
- * }
- *
- *
- * If you don't want to specify the server domain, you can use get_server_url:
- * $Config['SiteURL'] = get_server_url() . '/hypership';
- * $Config['SiteURL'] = get_server_url();
- *
- *
- *
- * !!! No trailing slash !!!
- *
- */
-
-$Config['SiteURL'] = get_server_url();
-$Config['BaseURL'] = '';
-
-//AJAX callbacks URL
-$Config['DoURL'] = $Config['SiteURL'] . "/do.php";
-
-////////////////////////////////////////////////////////////////////////////////
-/// ///
-/// IV. Static content ///
-/// ///
-////////////////////////////////////////////////////////////////////////////////
-
-//Where the static content is located?
-//Static content = 4 directories: js, css, img and content
-//On default installation, those directories are at site root.
-//To improve site performance, you can use a CDN for that.
-//
-//Recommanded setting: $Config['StaticContentURL'] = $Config['SiteURL'];
-//Or if Zed is the site root: $Config['StaticContentURL'] = '';
-//With CoralCDN: $Config['StaticContentURL'] = . '.nyud.net';
-//
-$Config['StaticContentURL'] = '';
-//$Config['StaticContentURL'] = get_server_url() . '.nyud.net';
-
-//Scenes
-define('SCENE_DIR', 'content/scenes');
-define('SCENE_URL', $Config['StaticContentURL'] . '/' . SCENE_DIR);
-
-//Stories
-define('STORIES_DIR', "content/stories");
-
-//Profile's photos
-define('PHOTOS_DIR', 'content/users/_photos');
-define('PHOTOS_URL', $Config['StaticContentURL'] . '/' . PHOTOS_DIR);
-
-//ImageMagick paths
-//Be careful on Windows platform convert could match the NTFS convert command.
-$Config['ImageMagick']['convert'] = 'convert';
-$Config['ImageMagick']['mogrify'] = 'mogrify';
-$Config['ImageMagick']['composite'] = 'composite';
-$Config['ImageMagick']['identify'] = 'identify';
-
-////////////////////////////////////////////////////////////////////////////////
-/// ///
-/// V. Caching ///
-/// ///
-////////////////////////////////////////////////////////////////////////////////
-
-/*
- * Some data (Smarty, OpenID and sessions) are cached in the cache directory.
- *
- * Security tip: you can move this cache directory outside the webserver tree.
- */
-define('CACHE_DIR', 'cache');
-
-/*
- * Furthermore, you can also enable a cache engine, like memcached, to store
- * data from heavy database queries, or frequently accessed stuff.
- *
- * To use memcached:
- * - $Config['cache']['engine'] = 'memcached';
- * - $Config['cache']['server'] = 'localhost';
- * - $Config['cache']['port'] = 11211;
- *
- * To disable cache:
- * - $Config['cache']['engine'] = 'void';
- * (or don't write nothing at all)
- */
-$Config['cache']['engine'] = 'void';
-
-////////////////////////////////////////////////////////////////////////////////
-/// ///
-/// VI. Sessions ///
-/// ///
-////////////////////////////////////////////////////////////////////////////////
-
-//If you want to use a common table of sessions / user handling
-//with several websites, specify a different resource id for each site.
-$Config['ResourceID'] = 21;
-
-//PHP variables
-ini_set('session.serialize_handler', 'wddx');
-ini_set('session.save_path', CACHE_DIR . '/sessions');
-ini_set('session.gc_maxlifetime', 345600); //4 days, for week-end story pause and continue url
-
-////////////////////////////////////////////////////////////////////////////////
-/// ///
-/// VII. Builder ///
-/// ///
-////////////////////////////////////////////////////////////////////////////////
-
-//Zed can invoke a slighty modified version of HOTGLUE to build zones.
-$Config['builder']['hotglue']['enable'] = true;
-$Config['builder']['hotglue']['URL'] = '/apps/hotglue/index.php';
-
-?>
+<?php
+
+/**
+ * Autogenerable configuration file
+ *
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2010, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * @package Zed
+ * @subpackage Keruald
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @copyright 2010 Sébastien Santoro aka Dereckson
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @version 0.1
+ * @link http://scherzo.dereckson.be/doc/zed
+ * @link http://zed.dereckson.be/
+ * @filesource
+ */
+
+////////////////////////////////////////////////////////////////////////////////
+/// ///
+/// I. SQL configuration ///
+/// ///
+////////////////////////////////////////////////////////////////////////////////
+
+//SQL configuration
+$Config['sql']['product'] = 'MySQL'; //Only MySQL is currently implemented
+$Config['sql']['host'] = 'localhost';
+$Config['sql']['username'] = 'zed';
+$Config['sql']['password'] = 'zed';
+$Config['sql']['database'] = 'zed';
+
+//SQL tables
+$prefix = '';
+define('TABLE_API_KEYS', $prefix . 'api_keys');
+define('TABLE_COMMENTS', $prefix . 'comments');
+define('TABLE_CONTENT_FILES', $prefix . 'content_files');
+define('TABLE_CONTENT_LOCATIONS', $prefix . 'content_locations');
+define('TABLE_CONTENT_ZONES', $prefix . 'content_zones');
+define('TABLE_CONTENT_ZONES_LOCATIONS', $prefix . 'content_zones_locations');
+define('TABLE_LOG', $prefix . 'log');
+define('TABLE_LOG_SMARTLINE', $prefix . 'log_smartline');
+define('TABLE_MESSAGES', $prefix . 'messages');
+define('TABLE_MOTD', $prefix . 'motd');
+define('TABLE_PAGES', $prefix . 'pages');
+define('TABLE_PAGES_EDITS', $prefix . 'pages_edits');
+define('TABLE_PERSOS', $prefix . 'persos');
+define('TABLE_PERSOS_FLAGS', $prefix . 'persos_flags');
+define('TABLE_PERSOS_NOTES', $prefix . 'persos_notes');
+define('TABLE_PORTS', $prefix . 'ports');
+define('TABLE_PROFILES', $prefix . 'profiles');
+define('TABLE_PROFILES_COMMENTS', $prefix . 'profiles_comments');
+define('TABLE_PROFILES_PHOTOS', $prefix . 'profiles_photos');
+define('TABLE_PROFILES_TAGS', $prefix . 'profiles_tags');
+define('TABLE_REGISTRY', $prefix . 'registry');
+define('TABLE_REQUESTS', $prefix . 'requests');
+define('TABLE_REQUESTS_REPLIES', $prefix . 'requests_replies');
+define('TABLE_SESSIONS', $prefix . 'sessions');
+define('TABLE_SHIPS', $prefix . 'ships');
+define('TABLE_USERS', $prefix . 'users');
+define('TABLE_USERS_INVITES', $prefix . 'users_invites');
+define('TABLE_USERS_AUTH', $prefix . 'users_auth');
+
+//Geo tables
+define('TABLE_BODIES', $prefix . 'geo_bodies');
+define('TABLE_LOCATIONS', $prefix . 'geo_locations'); //Well... it's a view
+define('TABLE_PLACES', $prefix . 'geo_places');
+
+////////////////////////////////////////////////////////////////////////////////
+/// ///
+/// II. Site configuration ///
+/// ///
+////////////////////////////////////////////////////////////////////////////////
+
+//Default theme
+$Config['DefaultTheme'] = "Zed";
+
+//Dates
+date_default_timezone_set("UTC");
+
+//Secret key, used for some verification hashes in URLs or forms.
+$Config['SecretKey'] = 'Lorem ipsum dolor';
+
+//When reading files, buffer size
+define('BUFFER_SIZE', 4096);
+
+////////////////////////////////////////////////////////////////////////////////
+/// ///
+/// III. Script URLs ///
+/// ///
+////////////////////////////////////////////////////////////////////////////////
+
+/*
+ * Apache httpd, without mod_rewrite:
+ *
+ * Subdirectory:
+ * - $Config['SiteURL'] = 'http://zed.dereckson.be/hypership/index.php';
+ * - $Config['BaseURL'] = '/hypership/index.php';
+ *
+ * Root directory:
+ * - $Config['SiteURL'] = 'http://zed.dereckson.be/index.php';
+ * - $Config['BaseURL'] = '/index.php';
+ *
+ * Apache httpd, with mod_rewrite:
+ *
+ * Subdirectory:
+ * - $Config['SiteURL'] = 'http://zed.dereckson.be/hypership';
+ * - $Config['BaseURL'] = '/hypership';
+ *
+ * In .htaccess or your vhost definition:
+ * RewriteEngine On
+ * RewriteBase /hypership/
+ * RewriteCond %{REQUEST_FILENAME} !-f
+ * RewriteCond %{REQUEST_FILENAME} !-d
+ * RewriteRule . /hypership/index.php [L]
+ *
+ * Root directory:
+ * - $Config['SiteURL'] = 'http://zed.dereckson.be';
+ * - $Config['BaseURL'] = '';
+ *
+ * In .htaccess or your vhost definition:
+ * RewriteEngine On
+ * RewriteBase /
+ * RewriteCond %{REQUEST_FILENAME} !-f
+ * RewriteCond %{REQUEST_FILENAME} !-d
+ * RewriteRule . /index.php [L]
+ *
+ * nginx:
+ *
+ * Use same config.php settings than Apache httpd, with mod_rewrite.
+ *
+ * In your server block:
+ * location / {
+ * #Serves static files if they exists, with one month cache
+ * if (-f $request_filename) {
+ * expires 30d;
+ * break;
+ * }
+ *
+ * #Sends all non existing file or directory requests to index.php
+ * if (!-e request_filename) {
+ * rewrite ^(.+)$ /index.php last;
+ * #Or if you use a subdirectory:
+ * #rewrite ^(.+)$ /hypership/index.php last;
+ * }
+ * }
+ *
+ * location ~ \.php$ {
+ * #Your instructions to pass query to your FastCGI process, like:
+ * fastcgi_pass 127.0.0.1:9000;
+ * fastcgi_param SCRIPT_FILENAME /var/www/zed$fastcgi_script_name;
+ * include fastcgi_params;
+ * }
+ *
+ *
+ * If you don't want to specify the server domain, you can use get_server_url:
+ * $Config['SiteURL'] = get_server_url() . '/hypership';
+ * $Config['SiteURL'] = get_server_url();
+ *
+ *
+ *
+ * !!! No trailing slash !!!
+ *
+ */
+
+$Config['SiteURL'] = get_server_url();
+$Config['BaseURL'] = '';
+
+//AJAX callbacks URL
+$Config['DoURL'] = $Config['SiteURL'] . "/do.php";
+
+////////////////////////////////////////////////////////////////////////////////
+/// ///
+/// IV. Static content ///
+/// ///
+////////////////////////////////////////////////////////////////////////////////
+
+//Where the static content is located?
+//Static content = 4 directories: js, css, img and content
+//On default installation, those directories are at site root.
+//To improve site performance, you can use a CDN for that.
+//
+//Recommanded setting: $Config['StaticContentURL'] = $Config['SiteURL'];
+//Or if Zed is the site root: $Config['StaticContentURL'] = '';
+//With CoralCDN: $Config['StaticContentURL'] = . '.nyud.net';
+//
+$Config['StaticContentURL'] = '';
+//$Config['StaticContentURL'] = get_server_url() . '.nyud.net';
+
+//Scenes
+define('SCENE_DIR', 'content/scenes');
+define('SCENE_URL', $Config['StaticContentURL'] . '/' . SCENE_DIR);
+
+//Stories
+define('STORIES_DIR', "content/stories");
+
+//Profile's photos
+define('PHOTOS_DIR', 'content/users/_photos');
+define('PHOTOS_URL', $Config['StaticContentURL'] . '/' . PHOTOS_DIR);
+
+//ImageMagick paths
+//Be careful on Windows platform convert could match the NTFS convert command.
+$Config['ImageMagick']['convert'] = 'convert';
+$Config['ImageMagick']['mogrify'] = 'mogrify';
+$Config['ImageMagick']['composite'] = 'composite';
+$Config['ImageMagick']['identify'] = 'identify';
+
+////////////////////////////////////////////////////////////////////////////////
+/// ///
+/// V. Caching ///
+/// ///
+////////////////////////////////////////////////////////////////////////////////
+
+/*
+ * Some data (Smarty, OpenID and sessions) are cached in the cache directory.
+ *
+ * Security tip: you can move this cache directory outside the webserver tree.
+ */
+define('CACHE_DIR', 'cache');
+
+/*
+ * Furthermore, you can also enable a cache engine, like memcached, to store
+ * data from heavy database queries, or frequently accessed stuff.
+ *
+ * To use memcached:
+ * - $Config['cache']['engine'] = 'memcached';
+ * - $Config['cache']['server'] = 'localhost';
+ * - $Config['cache']['port'] = 11211;
+ *
+ * To disable cache:
+ * - $Config['cache']['engine'] = 'void';
+ * (or don't write nothing at all)
+ */
+$Config['cache']['engine'] = 'void';
+
+////////////////////////////////////////////////////////////////////////////////
+/// ///
+/// VI. Sessions and authentication code ///
+/// ///
+////////////////////////////////////////////////////////////////////////////////
+
+//If you want to use a common table of sessions / user handling
+//with several websites, specify a different resource id for each site.
+$Config['ResourceID'] = 21;
+
+//Enable YubiKey authentication
+//API 12940
+//For YubiCloud API key - create yours at https://upgrade.yubico.com/getapikey/
+//$Config['YubiCloud']['ClientID'] = 12345;
+//$Config['YubiCloud']['SecretKey'] = 'Base64SecretKeyHere';
+
+//PHP variables
+ini_set('session.serialize_handler', 'wddx');
+ini_set('session.save_path', CACHE_DIR . '/sessions');
+ini_set('session.gc_maxlifetime', 345600); //4 days, for week-end story pause and continue url
+
+////////////////////////////////////////////////////////////////////////////////
+/// ///
+/// VII. Builder ///
+/// ///
+////////////////////////////////////////////////////////////////////////////////
+
+//Zed can invoke a slighty modified version of HOTGLUE to build zones.
+$Config['builder']['hotglue']['enable'] = true;
+$Config['builder']['hotglue']['URL'] = '/apps/hotglue/index.php';
+
+?>
diff --git a/includes/login.php b/includes/login.php
index a22af6f..83e468d 100755
--- a/includes/login.php
+++ b/includes/login.php
@@ -1,132 +1,148 @@
-<?php
-
-/**
- * Login/logout
- *
- * Zed. The immensity of stars. The HyperShip. The people.
- *
- * (c) 2010, Dereckson, some rights reserved.
- * Released under BSD license.
- *
- * @package Zed
- * @subpackage Keruald
- * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
- * @copyright 2010 Sébastien Santoro aka Dereckson
- * @license http://www.opensource.org/licenses/bsd-license.php BSD
- * @version 0.1
- * @link http://scherzo.dereckson.be/doc/zed
- * @link http://zed.dereckson.be/
- * @filesource
- *
- * @todo reenable OpenID
- * @todo Pick between DumbStore and FileStore and cleans the file accordingly.
- */
-
-require_once('Auth/OpenID/Consumer.php');
-require_once('Auth/OpenID/FileStore.php');
-
-/**
- * Gets an Auth_OpenID_Consumer instance
- *
- * @return Auth_OpenID_Consumer the instance
- */
-function get_openid_consumer () {
- if (!file_exists('/dev/urandom')) {
- //We don't have a reliable source of random numbers
- define('Auth_OpenID_RAND_SOURCE', null);
- }
-
- $fs = new Auth_OpenID_FileStore(CACHE_DIR . '/openid');
- return new Auth_OpenID_Consumer($fs);
-}
-
-/**
- * Logs in the user if the OpenID is recognized.
- * Otherwise, sets an error message.
- *
- * @param string $url The OpenID URL
- */
-function openid_login ($url) {
- global $db, $_SESSION, $LoginError, $LoginSuccessful;
- $url = $db->sql_escape($url);
- $sql = 'SELECT user_id FROM ' . TABLE_USERS_AUTH
- . " WHERE auth_type = 'OpenID' AND auth_identity LIKE '$url'";
- if ($user_id = $db->sql_query_express($sql)) {
- $sql = "UPDATE " . TABLE_SESSIONS . " SET user_id = '$user_id' WHERE session_id LIKE '$_SESSION[ID]'";
- if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Can't update session table", '', __LINE__, __FILE__, $sql);
- $LoginSuccessful = true;
- setcookie("LastOpenID", $url, time() + 2592000);
- header("location: " . get_url());
- } else {
- $LoginError = "Read the source to get an invite.";
- }
-}
-
-$action = isset($_GET['action']) ? $_GET['action'] : '';
-
-if ($action == 'openid.login') {
- //Gets Auth_OpenID_Consumer instance
- $consumer = get_openid_consumer();
-
- //Completes the OpenID transaction
- $reply = $consumer->complete(get_server_url() . $_SERVER['REQUEST_URI']);
- if ($reply->status == Auth_OpenID_SUCCESS) {
- openid_login($reply->endpoint->claimed_id);
- } elseif ($reply->message) {
- //TODO: $reply->message could be rather long and won't fit in the UI
- //space. You can wish to add code to print $LoginError elsewhere if
- //too long.
- $LoginError = "[OpenID] $reply->message";
- } else {
- $LoginError = "[OpenID] $reply->status";
- }
-} elseif (isset($_POST['LogIn'])) {
- //User have filled login form
- if ($_POST['openid']) {
- //Gets Auth_OpenID_Consumer instance
- $consumer = get_openid_consumer();
-
- //Starts the OpenID transaction and redirects user to provider url
- if ($request = $consumer->begin($_POST['openid'])) {
- $url = $request->redirectURL(get_server_url(), "$Config[SiteURL]/?action=openid.login", false);
- header("location: $url");
- $LoginError = '<a href="' . $url . '">Click here to continue login</a>';
- } else {
- $LoginError = 'Invalid OpenID URL.';
- }
- } else {
- //GESTION LOGIN
- $Login = $_POST['username'];
- $sql = "SELECT user_password, user_id FROM " . TABLE_USERS . " WHERE username = '$Login'";
- if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Impossible d'interroger le listing des utilisateurs", '', __LINE__, __FILE__, $sql);
- if ($row = $db->sql_fetchrow($result)) {
- if (!$row['user_password']) {
- $LoginError = "This account exists but haven't a password defined. Use OpenID or contact dereckson (at) espace-win.org to fix that.";
- } elseif ($row['user_password'] != md5($_POST['password'])) {
- //PASS NOT OK
- $LoginError = "Incorrect password.";
- } else {
- login($row[user_id], $Login);
- $LoginSuccessful = true;
- }
- } else {
- //Idiot proof facility
- //Redirects people using login page as invitation claim page
- $code = $db->sql_escape($_POST['password']);
- $sql = "SELECT * FROM " . TABLE_USERS_INVITES . " WHERE invite_code = '$code'";
- if (!$result = $db->sql_query($sql)) {
- message_die(SQL_ERROR, "Can't get invites", '', __LINE__, __FILE__, $sql);
- }
- if ($row = $db->sql_fetchrow($result)) {
- $url = get_url('invite', $_POST['password']);
- header('location: ' . $url);
- }
-
- //Login not found
- $LoginError = "Login not found.";
- }
- }
-} elseif (isset($_POST['LogOut']) || $action == "user.logout") {
- Logout();
-}
-?>
+<?php
+
+/**
+ * Login/logout
+ *
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2010, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * @package Zed
+ * @subpackage Keruald
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @copyright 2010 Sébastien Santoro aka Dereckson
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @version 0.1
+ * @link http://scherzo.dereckson.be/doc/zed
+ * @link http://zed.dereckson.be/
+ * @filesource
+ *
+ * @todo Pick between DumbStore and FileStore and cleans the file accordingly.
+ */
+
+///
+/// OpenID helper code
+///
+
+require_once('Auth/OpenID/Consumer.php');
+require_once('Auth/OpenID/FileStore.php');
+
+/**
+ * Gets an Auth_OpenID_Consumer instance
+ *
+ * @return Auth_OpenID_Consumer the instance
+ */
+function get_openid_consumer () {
+ if (!file_exists('/dev/urandom')) {
+ //We don't have a reliable source of random numbers
+ define('Auth_OpenID_RAND_SOURCE', null);
+ }
+
+ $fs = new Auth_OpenID_FileStore(CACHE_DIR . '/openid');
+ return new Auth_OpenID_Consumer($fs);
+}
+
+/**
+ * Logs in the user if the OpenID is recognized.
+ * Otherwise, sets an error message.
+ *
+ * @param string $url The OpenID URL
+ */
+function openid_login ($url) {
+ global $db, $_SESSION, $LoginError, $LoginSuccessful;
+ $url = $db->sql_escape($url);
+ $sql = 'SELECT user_id FROM ' . TABLE_USERS_AUTH
+ . " WHERE auth_type = 'OpenID' AND auth_identity LIKE '$url'";
+ if ($user_id = $db->sql_query_express($sql)) {
+ $sql = "UPDATE " . TABLE_SESSIONS . " SET user_id = '$user_id' WHERE session_id LIKE '$_SESSION[ID]'";
+ if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Can't update session table", '', __LINE__, __FILE__, $sql);
+ $LoginSuccessful = true;
+ setcookie("LastOpenID", $url, time() + 2592000);
+ header("location: " . get_url());
+ } else {
+ $LoginError = "Read the source to get an invite.";
+ }
+}
+
+///
+/// Login procedural code
+///
+
+$action = isset($_GET['action']) ? $_GET['action'] : '';
+
+if ($action == 'openid.login') {
+ //Gets Auth_OpenID_Consumer instance
+ $consumer = get_openid_consumer();
+
+ //Completes the OpenID transaction
+ $reply = $consumer->complete(get_server_url() . $_SERVER['REQUEST_URI']);
+ if ($reply->status == Auth_OpenID_SUCCESS) {
+ openid_login($reply->endpoint->claimed_id);
+ } elseif ($reply->message) {
+ //TODO: $reply->message could be rather long and won't fit in the UI
+ //space. You can wish to add code to print $LoginError elsewhere if
+ //too long.
+ $LoginError = "[OpenID] $reply->message";
+ } else {
+ $LoginError = "[OpenID] $reply->status";
+ }
+} elseif (isset($_POST['LogIn'])) {
+ //User have filled login form
+ if ($_POST['openid']) {
+ //Gets Auth_OpenID_Consumer instance
+ $consumer = get_openid_consumer();
+
+ //Starts the OpenID transaction and redirects user to provider url
+ if ($request = $consumer->begin($_POST['openid'])) {
+ $url = $request->redirectURL(get_server_url(), "$Config[SiteURL]/?action=openid.login", false);
+ header("location: $url");
+ $LoginError = '<a href="' . $url . '">Click here to continue login</a>';
+ } else {
+ $LoginError = 'Invalid OpenID URL.';
+ }
+ } else {
+ //Login
+
+ //Authentications way, the user/password in last.
+ //OpenID is handled by a separate logic.
+ $Login = $_POST['username'];
+ $authentications = array();
+ if ($useYubiCloud = array_key_exists('YubiCloud', $Config) ) {
+ $authentications[] = new YubiCloudAuthentication($_POST['password'], $Login);
+ }
+ if ($Login) {
+ $authentications[] = new UserPasswordAuthentication($Login, $_POST['password']);
+ }
+
+ $loginSuccessful = false;
+ foreach ($authentications as $authentication) {
+ if ($authentication->isValid()) {
+ $loginSuccessful = true;
+ //Logs in user
+ login($authentication->getUserID(), $Login);
+ } else {
+ $loginError = $authentication->getError();
+ }
+ if (!$authentication->canTryNextAuthenticationMethod()) {
+ break;
+ }
+ }
+
+ //Tests if the password wouldn't match an invite code
+ //If so, redirects people using login page as invitation claim page
+ if (!$LoginSuccessful) {
+ $code = $db->sql_escape($_POST['password']);
+ $sql = "SELECT * FROM " . TABLE_USERS_INVITES . " WHERE invite_code = '$code'";
+ if (!$result = $db->sql_query($sql)) {
+ message_die(SQL_ERROR, "Can't get invites", '', __LINE__, __FILE__, $sql);
+ }
+ if ($row = $db->sql_fetchrow($result)) {
+ $url = get_url('invite', $_POST['password']);
+ header('location: ' . $url);
+ }
+ }
+ }
+} elseif (isset($_POST['LogOut']) || $action == "user.logout") {
+ Logout();
+}
diff --git a/includes/objects/user.php b/includes/objects/user.php
index 093c404..2ff6ae3 100755
--- a/includes/objects/user.php
+++ b/includes/objects/user.php
@@ -1,214 +1,246 @@
<?php
/**
* User class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* [DESIGN BY CONTRACT NOTE] No more than one OpenID per user
*
* @package Zed
* @subpackage Model
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @copyright 2010 Sébastien Santoro aka Dereckson
* @license http://www.opensource.org/licenses/bsd-license.php BSD
* @version 0.1
* @link http://scherzo.dereckson.be/doc/zed
* @link http://zed.dereckson.be/
* @filesource
*/
/**
* User class
*
* This class maps the users and users_openid tables.
*
* It also provides helper methods to check if a login is available,
* or to retrieve a username from e-mail address.
*/
class User {
public $id;
public $name;
public $password;
public $active = 0;
public $actkey;
public $email;
public $regdate;
+ public static $hashtable_id = array();
+ public static $hashtable_name = array();
+
/**
* Initializes a new instance
*
* @param int $id the primary key
*/
function __construct ($id = null) {
if ($id) {
$this->id = $id;
$this->load_from_database();
}
}
+ /**
+ * Initializes a new User instance if needed or get already available one.
+ *
+ * @param mixed $data user ID or name
+ * @return User the user instance
+ */
+ static function get ($data = null) {
+ if ($data) {
+ //Checks in the hashtables if we already have loaded this instance
+ if (is_numeric($data)) {
+ if (array_key_exists($data, User::$hashtable_id)) {
+ return User::$hashtable_id[$data];
+ }
+ } else {
+ if (array_key_exists($data, User::$hashtable_name)) {
+ return User::$hashtable_name[$data];
+ }
+ }
+ }
+
+ $user = new User($data);
+ return $user;
+ }
+
/**
* Loads the object User (ie fill the properties) from the $_POST array
*/
function load_from_form () {
if (array_key_exists('name', $_POST)) $this->name = $_POST['name'];
if (array_key_exists('password', $_POST)) $this->password = $_POST['password'];
if (array_key_exists('active', $_POST)) $this->active = $_POST['active'];
if (array_key_exists('actkey', $_POST)) $this->actkey = $_POST['actkey'];
if (array_key_exists('email', $_POST)) $this->email = $_POST['email'];
if (array_key_exists('regdate', $_POST)) $this->regdate = $_POST['regdate'];
}
/**
* Loads the object User (ie fill the properties) from the database
*/
function load_from_database () {
global $db;
$sql = "SELECT * FROM " . TABLE_USERS . " WHERE user_id = '" . $this->id . "'";
if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Unable to query users", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
$this->lastError = "User unkwown: " . $this->id;
return false;
}
$this->name = $row['username'];
$this->password = $row['user_password'];
$this->active = $row['user_active'];
$this->actkey = $row['user_actkey'];
$this->email = $row['user_email'];
$this->regdate = $row['user_regdate'];
+
+ //Puts object in hashtables
+ Perso::$hashtable_id[$this->id] = $this;
+ Perso::$hashtable_name[$this->name] = $this;
+
return true;
}
/**
* Saves to database
*/
function save_to_database () {
global $db;
$id = $this->id ? "'" . $db->sql_escape($this->id) . "'" : 'NULL';
$name = $db->sql_escape($this->name);
$password = $db->sql_escape($this->password);
$active = $db->sql_escape($this->active);
$actkey = $db->sql_escape($this->actkey);
$email = $db->sql_escape($this->email);
$regdate = $this->regdate ? "'" . $db->sql_escape($this->regdate) . "'" : 'NULL';
//Updates or inserts
$sql = "REPLACE INTO " . TABLE_USERS . " (`user_id`, `username`, `user_password`, `user_active`, `user_actkey`, `user_email`, `user_regdate`) VALUES ($id, '$name', '$password', '$active', '$actkey', '$email', $regdate)";
if (!$db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to save", '', __LINE__, __FILE__, $sql);
}
if (!$id) {
//Gets new record id value
$this->id = $db->sql_nextid();
}
}
/**
* Updates the specified field in the database record
*/
function save_field ($field) {
global $db;
if (!$this->id) {
message_die(GENERAL_ERROR, "You're trying to update a record not yet saved in the database");
}
$id = $db->sql_escape($this->id);
$value = $db->sql_escape($this->$field);
$sql = "UPDATE " . TABLE_USERS . " SET `$field` = '$value' WHERE user_id = '$id'";
if (!$db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to save $field field", '', __LINE__, __FILE__, $sql);
}
}
/**
* Generates a unique user id
*/
function generate_id () {
global $db;
do {
$this->id = rand(2001, 5999);
$sql = "SELECT COUNT(*) FROM " . TABLE_USERS . " WHERE user_id = $this->id LOCK IN SHARE MODE;";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't access users table", '', __LINE__, __FILE__, $sql);
}
$row = $db->sql_fetchrow($result);
} while ($row[0]);
}
/**
* Fills password field with encrypted version of the specified clear password
*
* @param string $newpassword The user's new password
*/
public function set_password ($newpassword) {
$this->password = md5($newpassword);
}
/**
* Deletes OpenID for this user
*/
public function delete_OpenID () {
$this->set_OpenID('');
}
/**
* Sets OpenID for this user
*
* @param string $url OpenID endpoint URL
*/
public function set_OpenID ($url) {
global $db;
if (!$this->id) $this->save_to_database();
$url = $db->sql_escape($url);
$sql = "DELETE FROM " . TABLE_USERS_AUTH . " WHERE auth_type = 'OpenID' AND user_id = $this->id";
if (!$db->sql_query($sql))
message_die(SQL_ERROR, "Can't delete old OpenID", '', __LINE__, __FILE__, $sql);
if ($url != '') {
$sql = "INSERT INTO " . TABLE_USERS_AUTH . " (auth_type, auth_identity, user_id) VALUES ('OpenID', '$url', $this->id)";
if (!$db->sql_query($sql))
message_die(SQL_ERROR, "Can't add new OpenID", '', __LINE__, __FILE__, $sql);
}
}
/**
* Checks if a login is available
*
* @param string $login the login to check
* @return bool true if the specified login is available ; otherwise, false.
*/
public static function is_available_login ($login) {
global $db;
$sql = "SELECT COUNT(*) FROM " . TABLE_USERS . " WHERE username LIKE '$login' LOCK IN SHARE MODE;";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Utilisateurs non parsable", '', __LINE__, __FILE__, $sql);
}
$row = $db->sql_fetchrow($result);
return ($row[0] ? false : true);
}
/**
* Gets username from specified e-mail
*
* @param string $mail the mail to search
* @return string|bool the username matching the mail if found ; otherwise, false.
*/
public static function get_username_from_email ($mail) {
global $db;
$sql = "SELECT username FROM " . TABLE_USERS . " WHERE user_email LIKE '$mail' LOCK IN SHARE MODE;";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Utilisateurs non parsable", '', __LINE__, __FILE__, $sql);
}
if ($row = $db->sql_fetchrow($result)) {
return $row['username'];
}
return false;
}
}
-?>
\ No newline at end of file
+?>
diff --git a/includes/sessions.php b/includes/sessions.php
index 933c075..25b419c 100755
--- a/includes/sessions.php
+++ b/includes/sessions.php
@@ -1,149 +1,151 @@
-<?php
-
-/**
- * Sessions
- *
- * Zed. The immensity of stars. The HyperShip. The people.
- *
- * (c) 2010, Dereckson, some rights reserved.
- * Released under BSD license.
- *
- * This file provides functions to manage sessions. It's not currently properly
- * documented, as it's a temporary old session file, which will be updated soon.
- *
- * @package Zed
- * @subpackage Keruald
- * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
- * @copyright 2010 Sébastien Santoro aka Dereckson
- * @license http://www.opensource.org/licenses/bsd-license.php BSD
- * @version 0.1
- * @link http://scherzo.dereckson.be/doc/zed
- * @link http://zed.dereckson.be/
- * @filesource
- *
- * @todo Replaces this code by the unified Keruald session class.
- */
-
-function decode_ip ($int_ip) {
- $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
- return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
-}
-
-function encode_ip ($dotquad_ip) {
- $ip_sep = explode('.', $dotquad_ip);
- return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
-}
-
-function session_update () {
- global $db, $IP, $Config;
- //Nettoyage de la session
- /* Initialisation */
- $time_online = 5 * 60; // Temps après lequel l'utilisateur n'est plus considéré comme online
- $time_session = 2 * 60 * 60; // Durée de vie de la session
-
- $heureActuelle = time(); //Timestamp UNIX et non MySQL
-
- /* On fait le ménage */
- $sql = "UPDATE " . TABLE_SESSIONS . " SET online=0 WHERE HeureLimite < $heureActuelle";
- if (!$db->sql_query($sql)) message_die(SQL_ERROR, 'Impossible de mettre à jour les sessions (utilisateurs offline)', '', __LINE__, __FILE__, $sql);
-
- $sql = "DELETE FROM " . TABLE_SESSIONS . " WHERE SessionLimite < $heureActuelle";
- if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible d'effacer les sessions expirées", '', __LINE__, __FILE__, $sql);
-
- /* Création / mise à jour de la session utilisateur */
- if (!$_SESSION[ID]) {
- $_SESSION[ID] = md5(generate_random_string("AAAA1234"));
- }
-
- $sql = "SELECT * FROM " . TABLE_SESSIONS . " WHERE session_id LIKE '$_SESSION[ID]'";
- if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Problème critique avec les sessions.", '', __LINE__, __FILE__, $sql);
-
- if ($db->sql_numrows($result) == 0) {
- $sql = "INSERT INTO " . TABLE_SESSIONS . " (IP, session_id, `Where`, HeureLimite, SessionLimite) VALUES ('$IP', '$_SESSION[ID]', $Config[ResourceID], $heureActuelle + $time_online, $heureActuelle + $time_session)";
- if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible de créer une nouvelle session", '', __LINE__, __FILE__, $sql);
- } else {
- $sql = "UPDATE " . TABLE_SESSIONS . " SET online=1, HeureLimite = $heureActuelle + $time_online, SessionLimite= $heureActuelle + $time_session WHERE session_id = '$_SESSION[ID]'";
- if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible de mettre à jour la session", '', __LINE__, __FILE__, $sql);
- }
-}
-
-function nbc () {
-//Renvoi du nombre d'usagers connectés
- global $db, $Config;
- $sql = "SELECT count(*) FROM " . TABLE_SESSIONS . " WHERE online=1 AND `Where` = $Config[ResourceID]";
- if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Impossible d'obtenir le nombre d'utilisateurs connectés sur le site web", '', __LINE__, __FILE__, $sql);
- $row = $db->sql_fetchrow($result);
- return $row[0];
-}
-
-function get_info ($info)
-//Renvoie une variable de la session
-{
- global $db;
- $sql = "SELECT $info FROM " . TABLE_SESSIONS . " WHERE session_id LIKE '$_SESSION[ID]'";
- if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Impossible d'obtenir $info", '', __LINE__, __FILE__, $sql);
- $row = $db->sql_fetchrow($result);
- return $row[$info];
-}
-
-function get_logged_user ()
-//Renvoie toutes les informations d'un utilisateur
-{
- global $db;
- $sql = "SELECT * FROM " . TABLE_SESSIONS . " WHERE session_id LIKE '$_SESSION[ID]'";
- if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Impossible d'obtenir les informations de l'utilisateur", '', __LINE__, __FILE__, $sql);
- $row = $db->sql_fetchrow($result);
-
- require_once('includes/objects/user.php');
- $user = new User($row['user_id']);
-
- $user->session = $row;
-
- return $user;
-}
-
-function set_info ($info, $value)
-//Définit une variable session
-{
- global $db;
- $value = ($value === null) ? 'NULL' : "'" . $db->sql_escape($value) . "'";
- $sql = "UPDATE " . TABLE_SESSIONS . " SET $info = $value WHERE session_id LIKE '$_SESSION[ID]'";
- if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible de définir $info", '', __LINE__, __FILE__, $sql);
-}
-
-/**
- * Destroys $_SESSION array values, help ID
- */
-function clean_session () {
- foreach ($_SESSION as $key => $value) {
- if ($key != 'ID') unset($_SESSION[$key]);
- }
-}
-
-
-/**
- * Logs in user
- */
-
-function login ($user_id, $username) {
- global $db;
- $sql = "UPDATE " . TABLE_SESSIONS . " SET user_id = '$user_id' WHERE session_id LIKE '$_SESSION[ID]'";
- if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible de procéder à la connexion", '', __LINE__, __FILE__, $sql);
-
- //We send a cookie to print automatically the last username on the login
- //page during 30 days.
- setcookie("LastUsername", $username, time() + 2592000);
-}
-
-/**
- * Logs out user
- */
-function logout () {
- //Anonymous user in session table
- global $db;
- $sql = "UPDATE " . TABLE_SESSIONS . " SET user_id = '-1', perso_id = NULL WHERE session_id LIKE '$_SESSION[ID]'";
- if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible de procéder à la déconnexion", '', __LINE__, __FILE__, $sql);
- clean_session();
-}
-
-?>
\ No newline at end of file
+<?php
+
+/**
+ * Sessions
+ *
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2010, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * This file provides functions to manage sessions. It's not currently properly
+ * documented, as it's a temporary old session file, which will be updated soon.
+ *
+ * @package Zed
+ * @subpackage Keruald
+ * @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
+ * @copyright 2010 Sébastien Santoro aka Dereckson
+ * @license http://www.opensource.org/licenses/bsd-license.php BSD
+ * @version 0.1
+ * @link http://scherzo.dereckson.be/doc/zed
+ * @link http://zed.dereckson.be/
+ * @filesource
+ *
+ * @todo Replaces this code by the unified Keruald session class.
+ */
+
+function decode_ip ($int_ip) {
+ $hexipbang = explode('.', chunk_split($int_ip, 2, '.'));
+ return hexdec($hexipbang[0]). '.' . hexdec($hexipbang[1]) . '.' . hexdec($hexipbang[2]) . '.' . hexdec($hexipbang[3]);
+}
+
+function encode_ip ($dotquad_ip) {
+ $ip_sep = explode('.', $dotquad_ip);
+ return sprintf('%02x%02x%02x%02x', $ip_sep[0], $ip_sep[1], $ip_sep[2], $ip_sep[3]);
+}
+
+function session_update () {
+ global $db, $IP, $Config;
+ //Nettoyage de la session
+ /* Initialisation */
+ $time_online = 5 * 60; // Temps après lequel l'utilisateur n'est plus considéré comme online
+ $time_session = 2 * 60 * 60; // Durée de vie de la session
+
+ $heureActuelle = time(); //Timestamp UNIX et non MySQL
+
+ /* On fait le ménage */
+ $sql = "UPDATE " . TABLE_SESSIONS . " SET online=0 WHERE HeureLimite < $heureActuelle";
+ if (!$db->sql_query($sql)) message_die(SQL_ERROR, 'Impossible de mettre à jour les sessions (utilisateurs offline)', '', __LINE__, __FILE__, $sql);
+
+ $sql = "DELETE FROM " . TABLE_SESSIONS . " WHERE SessionLimite < $heureActuelle";
+ if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible d'effacer les sessions expirées", '', __LINE__, __FILE__, $sql);
+
+ /* Création / mise à jour de la session utilisateur */
+ if (!$_SESSION[ID]) {
+ $_SESSION[ID] = md5(generate_random_string("AAAA1234"));
+ }
+
+ $sql = "SELECT * FROM " . TABLE_SESSIONS . " WHERE session_id LIKE '$_SESSION[ID]'";
+ if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Problème critique avec les sessions.", '', __LINE__, __FILE__, $sql);
+
+ if ($db->sql_numrows($result) == 0) {
+ $sql = "INSERT INTO " . TABLE_SESSIONS . " (IP, session_id, `Where`, HeureLimite, SessionLimite) VALUES ('$IP', '$_SESSION[ID]', $Config[ResourceID], $heureActuelle + $time_online, $heureActuelle + $time_session)";
+ if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible de créer une nouvelle session", '', __LINE__, __FILE__, $sql);
+ } else {
+ $sql = "UPDATE " . TABLE_SESSIONS . " SET online=1, HeureLimite = $heureActuelle + $time_online, SessionLimite= $heureActuelle + $time_session WHERE session_id = '$_SESSION[ID]'";
+ if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible de mettre à jour la session", '', __LINE__, __FILE__, $sql);
+ }
+}
+
+function nbc () {
+//Renvoi du nombre d'usagers connectés
+ global $db, $Config;
+ $sql = "SELECT count(*) FROM " . TABLE_SESSIONS . " WHERE online=1 AND `Where` = $Config[ResourceID]";
+ if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Impossible d'obtenir le nombre d'utilisateurs connectés sur le site web", '', __LINE__, __FILE__, $sql);
+ $row = $db->sql_fetchrow($result);
+ return $row[0];
+}
+
+function get_info ($info)
+//Renvoie une variable de la session
+{
+ global $db;
+ $sql = "SELECT $info FROM " . TABLE_SESSIONS . " WHERE session_id LIKE '$_SESSION[ID]'";
+ if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Impossible d'obtenir $info", '', __LINE__, __FILE__, $sql);
+ $row = $db->sql_fetchrow($result);
+ return $row[$info];
+}
+
+function get_logged_user ()
+//Renvoie toutes les informations d'un utilisateur
+{
+ global $db;
+ $sql = "SELECT * FROM " . TABLE_SESSIONS . " WHERE session_id LIKE '$_SESSION[ID]'";
+ if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Impossible d'obtenir les informations de l'utilisateur", '', __LINE__, __FILE__, $sql);
+ $row = $db->sql_fetchrow($result);
+
+ require_once('includes/objects/user.php');
+ $user = User::get($row['user_id']);
+
+ $user->session = $row;
+
+ return $user;
+}
+
+function set_info ($info, $value)
+//Définit une variable session
+{
+ global $db;
+ $value = ($value === null) ? 'NULL' : "'" . $db->sql_escape($value) . "'";
+ $sql = "UPDATE " . TABLE_SESSIONS . " SET $info = $value WHERE session_id LIKE '$_SESSION[ID]'";
+ if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible de définir $info", '', __LINE__, __FILE__, $sql);
+}
+
+/**
+ * Destroys $_SESSION array values, help ID
+ */
+function clean_session () {
+ foreach ($_SESSION as $key => $value) {
+ if ($key != 'ID') unset($_SESSION[$key]);
+ }
+}
+
+
+/**
+ * Logs in user
+ */
+
+function login ($user_id, $username) {
+ global $db;
+ $sql = "UPDATE " . TABLE_SESSIONS . " SET user_id = '$user_id' WHERE session_id LIKE '$_SESSION[ID]'";
+ if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible de procéder à la connexion", '', __LINE__, __FILE__, $sql);
+
+ //We send a cookie to print automatically the last username on the login
+ //page during 30 days.
+ if (username) {
+ setcookie("LastUsername", $username, time() + 2592000);
+ }
+}
+
+/**
+ * Logs out user
+ */
+function logout () {
+ //Anonymous user in session table
+ global $db;
+ $sql = "UPDATE " . TABLE_SESSIONS . " SET user_id = '-1', perso_id = NULL WHERE session_id LIKE '$_SESSION[ID]'";
+ if (!$db->sql_query($sql)) message_die(SQL_ERROR, "Impossible de procéder à la déconnexion", '', __LINE__, __FILE__, $sql);
+ clean_session();
+}
+
+?>

File Metadata

Mime Type
text/x-diff
Expires
Fri, Nov 8, 20:32 (2 w, 6 d ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
20973
Default Alt Text
(83 KB)

Event Timeline