Page MenuHomeCode

No OneTemporary

This document is not UTF8. It was detected as ISO-8859-1 (Latin 1) and converted to UTF8 for display.
diff --git a/api.php b/api.php
index 9939d59..9db34d4 100644
--- a/api.php
+++ b/api.php
@@ -1,307 +1,319 @@
-<?php
-
-/*
- * Zed
- * (c) 2010, Dereckson, some rights reserved
- * Released under BSD license
- *
- * API entry point
- *
- */
-
-//API Preferences
-define('URL', 'http://' . $_SERVER['HTTP_HOST'] . '/index.php');
-
-//Pluton library
-require_once('includes/core.php');
-require_once('includes/config.php');
-
-//API libs
-require_once('includes/api/api_helpers.php');
-require_once('includes/api/cerbere.php');
-
-//Use our URL controller method if you want to mod_rewrite the API
-$url = explode('/', substr($_SERVER['PATH_INFO'], 1));
-
-switch ($module = $url[0]) {
-/* -------------------------------------------------------------
- Site API
-
- /time
- /location
- /perso (disabled)
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
-
- case '':
- //Nothing to do
- //TODO: offer documentation instead
- die();
-
- case 'time':
- //Hypership time
- api_output(get_hypership_time(), "time");
- break;
-
- case 'location':
- //Checks creditentials
- cerbere();
- //Gets location info
- require_once("includes/geo/location.php");
- $location = new GeoLocation($url[1], $url[2]);
- api_output($location, "location");
- break;
-
- //case 'perso':
- // //Checks creditentials
- // cerbere();
- // //Gets perso info
- // require_once("includes/objects/perso.php");
- // $perso = new Perso($url[1]);
- // api_output($perso, "perso");
- // break;
-
-/* -------------------------------------------------------------
- Ship API
-
- /authenticate
- /appauthenticate
- /appauthenticated
- /move
- /land
- /flyout
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
-
- case 'ship':
- //Ship API
-
- //Gets ship from Ship API key (distinct of regular API keys)
- require_once('includes/objects/ship.php');
- $ship = Ship::from_api_key($_REQUEST['key']) or cerbere_die("Invalid ship API key");
-
- switch ($command = $url[1]) {
- case '':
- //Nothing to do
- //TODO: offer documentation instead
- die();
-
- case 'authenticate':
- //TODO: web authenticate
- break;
-
- case 'appauthenticate':
- //Allows desktop application to authenticate an user
- $tmp_session_id = $url[2] or cerbere_die("/appauthenticate/ must be followed by any session identifier");
- if ($_REQUEST['name']) {
- //Perso will be offered auth invite at next login.
- //Handy for devices like PDA, where it's not easy to auth.
- $perso = new Perso($_REQUEST['name']);
- if ($perso->lastError) {
- cerbere_die($perso->lastError);
- }
- if (!$ship->is_perso_authenticated($perso->id)) {
- $ship->request_perso_authenticate($perso->id);
- }
- $ship->request_perso_confirm_session($tmp_session_id, $perso->id);
- } else {
- //Delivers an URL. App have to redirects user to this URL
- //launching a browser or printing the link.
- $ship_code = $ship->get_code();
- registry_set("api.ship.session.$ship_code.$tmp_session_id", -1);
- $url = get_server_url() . get_url() . "?action=api.ship.appauthenticate&session_id=" . $tmp_session_id;
- api_output($url, "URL");
- }
- break;
-
- case 'appauthenticated':
- //Checks the user authentication
- $tmp_session_id = $url[2] or cerbere_die("/appauthenticated/ must be followed by any session identifier you used in /appauthenticate");
- $perso_id = $ship->get_perso_from_session($tmp_session_id);
- if (!$isPersoAuth = $ship->is_perso_authenticated($perso_id)) {
- //Global auth not ok/revoked.
- $auth->status = -1;
- } else {
- $perso = Perso::get($perso_id);
- $auth->status = 1;
- $auth->perso->id = $perso->id;
- $auth->perso->nickname = $perso->nickname;
- $auth->perso->name = $perso->name;
- //$auth->perso->location = $perso->location;
- //Is the perso on board? Yes if its global location is S...
- $auth->perso->onBoard = (
- $perso->location_global[0] == 'S' &&
- substr($perso->location_global, 1, 5) == $ship->id
- );
- if ($auth->perso->onBoard) {
- //If so, give local location
- $auth->perso->location_local = $perso->location_local;
- }
- }
- api_output($auth, "auth");
- break;
-
- case 'move':
- //Moves the ship to a new location, given absolute coordinates
- //TODO: handle relative moves
- if (count($url) < 2) cerbere_die("/move/ must be followed by a location expression");
-
- //Gets location class
- //It's allow: (1) to normalize locations between formats
- // (2) to ensure the syntax
- //==> if the ship want to communicate free forms coordinates, must be added on GeoLocation a free format
- try {
- $location = new GeoLocation($url[2]);
- } catch (Exception $ex) {
- $reply->success = 0;
- $reply->error = $ex->getMessage();
- api_output($reply, "move");
- break;
- }
-
- $ship->location_global = $location->global;
- $ship->save_to_database();
-
- $reply->success = 1;
- $reply->location = $ship->location;
- api_output($reply, "move");
- break;
-
- case 'land':
- case 'flyin':
- //Flies in
- try {
- $location = new GeoLocation($location);
- } catch (Exception $ex) {
- $reply->success = 0;
- $reply->error = $ex->getMessage();
- api_output($reply, "land");
- break;
- }
-
- break;
-
- case 'flyout':
- //Flies out
-
- break;
-
- }
- break;
-
-/* -------------------------------------------------------------
- Application API
-
- /checkuserkey
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
-
- case 'app':
- //Application API
- require_once("includes/objects/application.php");
- $app = Application::from_api_key($_REQUEST['key']) or cerbere_die("Invalid application API key");
-
- switch ($command = $url[1]) {
- case '':
- //Nothing to do
- //TODO: offer documentation instead
- die();
-
- case 'checkuserkey':
- if (count($url) < 2) cerbere_die("/checkuserkey/ must be followed by an user key");
- $reply = (boolean)$app->get_perso_id($url[2]);
- api_output($reply, "check");
- break;
-
- case 'pushuserdata':
- if (count($url) < 3) cerbere_die("/pushuserdata/ must be followed by an user key");
- $perso_id = $app->get_perso_id($url[2]) or cerbere_die("Invalid application user key");
- //then, falls to 'pushdata'
-
- case 'pushdata':
- $data_id = $_REQUEST['data'] ? $_REQUEST['data'] : new_guid();
- //Gets data
- switch ($mode = $_REQUEST['mode']) {
- case '':
- cerbere_die("Add in your data posted or in the URL mode=file to read data from the file posted (one file per api call) or mode=request to read data from \$_REQUEST['data'].");
-
- case 'request':
- $data = $_REQUEST['data'];
- $format = "raw";
- break;
-
- case 'file':
- $file = $_FILES['datafile']['tmp_name'] or cerbere_die("File is missing");
- if (!is_uploaded_file($file)) cerbere_die("Invalid form request");
- $data = "";
- if (preg_match('/\.tar$/', $file)) {
- $format = "tar";
- $data = file_get_contents($file);
- } elseif (preg_match('/\.tar\.bz2$/', $file)) {
- $format = "tar";
- } elseif (preg_match('/\.bz2$/', $file)) {
- $format = "raw";
- } else {
- $format = "raw";
- $data = file_get_contents($file);
- }
- if ($data === "") {
- //.bz2
- $bz = bzopen($file, "r") or cerbere_die("Couldn't open $file");
- while (!feof($bz)) {
- $data .= bzread($bz, BUFFER_SIZE);
- }
- bzclose($bz);
- }
- unlink($file);
- break;
-
- default:
- cerbere_die("Invalid mode. Expected: file, request");
- }
-
- //Saves data
- global $db;
- $data_id = $db->sql_escape($data_id);
- $data = $db->sql_escape($data);
- $perso_id = $perso_id ? $perso_id : 'NULL';
- $sql = "REPLACE INTO applications_data (application_id, data_id, data_content, data_format, perso_id) VALUES ('$app->id', '$data_id', '$data', '$format', $perso_id)";
- if (!$db->sql_query($sql))
- message_die(SQL_ERROR, "Can't save data", '', __LINE__, __FILE__, $sql);
- //cerbere_die("Can't save data");
-
- //Returns
- api_output($data_id);
- break;
-
- case 'getuserdata':
- // /api.php/getuserdata/data_id/perso_key
- // /api.php/getdata/data_id
- if (count($url) < 3) cerbere_die("/getuserdata/ must be followed by an user key");
- $perso_id = $app->get_perso_id($url[2]) or cerbere_die("Invalid application user key");
- //then, falls to 'getdata'
-
- case 'getdata':
- if (count($url) < 2) cerbere_die('/' + $url[0] + '/ must be followed by the data ID');
- if (!$perso_id) $perso_id = 'NULL';
- $data_id = $db->sql_escape($url[1]);
- $sql = "SELECT data_content FROM applications_data WHERE application_id = '$app->id' AND data_id = '$data_id' AND perso_id = $perso_id";
- if (!$result = $db->sql_query($sql)) {
- message_die(SQL_ERROR, "Unable to query the table", '', __LINE__, __FILE__, $sql);
- }
- while ($row = $db->sql_fetchrow($result)) {
-
- }
- break;
-
- default:
- echo "Unknown module:";
- dprint_r($url);
- break;
- }
- break;
-
- default:
- echo "Unknown module:";
- dprint_r($url);
- break;
-}
-
-?>
+<?php
+
+/**
+ * API entry point
+ *
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2010, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * @package Zed
+ * @subpackage EntryPoints
+ * @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 Consider to output documentation on / and /ship queries
+ */
+
+
+//API Preferences
+define('URL', 'http://' . $_SERVER['HTTP_HOST'] . '/index.php');
+
+//Pluton library
+require_once('includes/core.php');
+require_once('includes/config.php');
+
+//API libs
+require_once('includes/api/api_helpers.php');
+require_once('includes/api/cerbere.php');
+
+//Use our URL controller method if you want to mod_rewrite the API
+$url = explode('/', substr($_SERVER['PATH_INFO'], 1));
+
+switch ($module = $url[0]) {
+/* -------------------------------------------------------------
+ Site API
+
+ /time
+ /location
+ /perso (disabled)
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
+
+ case '':
+ //Nothing to do
+ //TODO: offer documentation instead
+ die();
+
+ case 'time':
+ //Hypership time
+ api_output(get_hypership_time(), "time");
+ break;
+
+ case 'location':
+ //Checks creditentials
+ cerbere();
+ //Gets location info
+ require_once("includes/geo/location.php");
+ $location = new GeoLocation($url[1], $url[2]);
+ api_output($location, "location");
+ break;
+
+ //case 'perso':
+ // //Checks creditentials
+ // cerbere();
+ // //Gets perso info
+ // require_once("includes/objects/perso.php");
+ // $perso = new Perso($url[1]);
+ // api_output($perso, "perso");
+ // break;
+
+/* -------------------------------------------------------------
+ Ship API
+
+ /authenticate
+ /appauthenticate
+ /appauthenticated
+ /move
+ /land
+ /flyout
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
+
+ case 'ship':
+ //Ship API
+
+ //Gets ship from Ship API key (distinct of regular API keys)
+ require_once('includes/objects/ship.php');
+ $ship = Ship::from_api_key($_REQUEST['key']) or cerbere_die("Invalid ship API key");
+
+ switch ($command = $url[1]) {
+ case '':
+ //Nothing to do
+ //TODO: offer documentation instead
+ die();
+
+ case 'authenticate':
+ //TODO: web authenticate
+ break;
+
+ case 'appauthenticate':
+ //Allows desktop application to authenticate an user
+ $tmp_session_id = $url[2] or cerbere_die("/appauthenticate/ must be followed by any session identifier");
+ if ($_REQUEST['name']) {
+ //Perso will be offered auth invite at next login.
+ //Handy for devices like PDA, where it's not easy to auth.
+ $perso = new Perso($_REQUEST['name']);
+ if ($perso->lastError) {
+ cerbere_die($perso->lastError);
+ }
+ if (!$ship->is_perso_authenticated($perso->id)) {
+ $ship->request_perso_authenticate($perso->id);
+ }
+ $ship->request_perso_confirm_session($tmp_session_id, $perso->id);
+ } else {
+ //Delivers an URL. App have to redirects user to this URL
+ //launching a browser or printing the link.
+ $ship_code = $ship->get_code();
+ registry_set("api.ship.session.$ship_code.$tmp_session_id", -1);
+ $url = get_server_url() . get_url() . "?action=api.ship.appauthenticate&session_id=" . $tmp_session_id;
+ api_output($url, "URL");
+ }
+ break;
+
+ case 'appauthenticated':
+ //Checks the user authentication
+ $tmp_session_id = $url[2] or cerbere_die("/appauthenticated/ must be followed by any session identifier you used in /appauthenticate");
+ $perso_id = $ship->get_perso_from_session($tmp_session_id);
+ if (!$isPersoAuth = $ship->is_perso_authenticated($perso_id)) {
+ //Global auth not ok/revoked.
+ $auth->status = -1;
+ } else {
+ $perso = Perso::get($perso_id);
+ $auth->status = 1;
+ $auth->perso->id = $perso->id;
+ $auth->perso->nickname = $perso->nickname;
+ $auth->perso->name = $perso->name;
+ //$auth->perso->location = $perso->location;
+ //Is the perso on board? Yes if its global location is S...
+ $auth->perso->onBoard = (
+ $perso->location_global[0] == 'S' &&
+ substr($perso->location_global, 1, 5) == $ship->id
+ );
+ if ($auth->perso->onBoard) {
+ //If so, give local location
+ $auth->perso->location_local = $perso->location_local;
+ }
+ }
+ api_output($auth, "auth");
+ break;
+
+ case 'move':
+ //Moves the ship to a new location, given absolute coordinates
+ //TODO: handle relative moves
+ if (count($url) < 2) cerbere_die("/move/ must be followed by a location expression");
+
+ //Gets location class
+ //It's allow: (1) to normalize locations between formats
+ // (2) to ensure the syntax
+ //==> if the ship want to communicate free forms coordinates, must be added on GeoLocation a free format
+ try {
+ $location = new GeoLocation($url[2]);
+ } catch (Exception $ex) {
+ $reply->success = 0;
+ $reply->error = $ex->getMessage();
+ api_output($reply, "move");
+ break;
+ }
+
+ $ship->location_global = $location->global;
+ $ship->save_to_database();
+
+ $reply->success = 1;
+ $reply->location = $ship->location;
+ api_output($reply, "move");
+ break;
+
+ case 'land':
+ case 'flyin':
+ //Flies in
+ try {
+ $location = new GeoLocation($location);
+ } catch (Exception $ex) {
+ $reply->success = 0;
+ $reply->error = $ex->getMessage();
+ api_output($reply, "land");
+ break;
+ }
+
+ break;
+
+ case 'flyout':
+ //Flies out
+
+ break;
+
+ }
+ break;
+
+/* -------------------------------------------------------------
+ Application API
+
+ /checkuserkey
+ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
+
+ case 'app':
+ //Application API
+ require_once("includes/objects/application.php");
+ $app = Application::from_api_key($_REQUEST['key']) or cerbere_die("Invalid application API key");
+
+ switch ($command = $url[1]) {
+ case '':
+ //Nothing to do
+ //TODO: offer documentation instead
+ die();
+
+ case 'checkuserkey':
+ if (count($url) < 2) cerbere_die("/checkuserkey/ must be followed by an user key");
+ $reply = (boolean)$app->get_perso_id($url[2]);
+ api_output($reply, "check");
+ break;
+
+ case 'pushuserdata':
+ if (count($url) < 3) cerbere_die("/pushuserdata/ must be followed by an user key");
+ $perso_id = $app->get_perso_id($url[2]) or cerbere_die("Invalid application user key");
+ //then, falls to 'pushdata'
+
+ case 'pushdata':
+ $data_id = $_REQUEST['data'] ? $_REQUEST['data'] : new_guid();
+ //Gets data
+ switch ($mode = $_REQUEST['mode']) {
+ case '':
+ cerbere_die("Add in your data posted or in the URL mode=file to read data from the file posted (one file per api call) or mode=request to read data from \$_REQUEST['data'].");
+
+ case 'request':
+ $data = $_REQUEST['data'];
+ $format = "raw";
+ break;
+
+ case 'file':
+ $file = $_FILES['datafile']['tmp_name'] or cerbere_die("File is missing");
+ if (!is_uploaded_file($file)) cerbere_die("Invalid form request");
+ $data = "";
+ if (preg_match('/\.tar$/', $file)) {
+ $format = "tar";
+ $data = file_get_contents($file);
+ } elseif (preg_match('/\.tar\.bz2$/', $file)) {
+ $format = "tar";
+ } elseif (preg_match('/\.bz2$/', $file)) {
+ $format = "raw";
+ } else {
+ $format = "raw";
+ $data = file_get_contents($file);
+ }
+ if ($data === "") {
+ //.bz2
+ $bz = bzopen($file, "r") or cerbere_die("Couldn't open $file");
+ while (!feof($bz)) {
+ $data .= bzread($bz, BUFFER_SIZE);
+ }
+ bzclose($bz);
+ }
+ unlink($file);
+ break;
+
+ default:
+ cerbere_die("Invalid mode. Expected: file, request");
+ }
+
+ //Saves data
+ global $db;
+ $data_id = $db->sql_escape($data_id);
+ $data = $db->sql_escape($data);
+ $perso_id = $perso_id ? $perso_id : 'NULL';
+ $sql = "REPLACE INTO applications_data (application_id, data_id, data_content, data_format, perso_id) VALUES ('$app->id', '$data_id', '$data', '$format', $perso_id)";
+ if (!$db->sql_query($sql))
+ message_die(SQL_ERROR, "Can't save data", '', __LINE__, __FILE__, $sql);
+ //cerbere_die("Can't save data");
+
+ //Returns
+ api_output($data_id);
+ break;
+
+ case 'getuserdata':
+ // /api.php/getuserdata/data_id/perso_key
+ // /api.php/getdata/data_id
+ if (count($url) < 3) cerbere_die("/getuserdata/ must be followed by an user key");
+ $perso_id = $app->get_perso_id($url[2]) or cerbere_die("Invalid application user key");
+ //then, falls to 'getdata'
+
+ case 'getdata':
+ if (count($url) < 2) cerbere_die('/' + $url[0] + '/ must be followed by the data ID');
+ if (!$perso_id) $perso_id = 'NULL';
+ $data_id = $db->sql_escape($url[1]);
+ $sql = "SELECT data_content FROM applications_data WHERE application_id = '$app->id' AND data_id = '$data_id' AND perso_id = $perso_id";
+ if (!$result = $db->sql_query($sql)) {
+ message_die(SQL_ERROR, "Unable to query the table", '', __LINE__, __FILE__, $sql);
+ }
+ while ($row = $db->sql_fetchrow($result)) {
+
+ }
+ break;
+
+ default:
+ echo "Unknown module:";
+ dprint_r($url);
+ break;
+ }
+ break;
+
+ default:
+ echo "Unknown module:";
+ dprint_r($url);
+ break;
+}
+
+?>
diff --git a/apps/HelloWorldWebService.php b/apps/HelloWorldWebService.php
index 0cafca4..474548e 100644
--- a/apps/HelloWorldWebService.php
+++ b/apps/HelloWorldWebService.php
@@ -1,5 +1,27 @@
-<?php
- die('<a href="/">Go to homepage</a>');
- $client = new SoapClient("http://localhost:49319/Service1.asmx?WSDL");
- echo $client->HelloWorld()->HelloWorldResult
+<?php
+
+/**
+ * Hello World webservice client
+ *
+ * This file allows to see if the SOAP server is operationnal.
+ *
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2010, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * @package Zed
+ * @subpackage Pazaak
+ * @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
+ */
+
+$client = new SoapClient("http://10.0.0.4:49319/Service1.asmx?WSDL");
+echo $client->HelloWorld()->HelloWorldResult;
+
?>
\ No newline at end of file
diff --git a/apps/pazaak/debug.php b/apps/pazaak/debug.php
index 8a822b5..68257e1 100644
--- a/apps/pazaak/debug.php
+++ b/apps/pazaak/debug.php
@@ -1,37 +1,63 @@
<?php
- function dprint_r ($var) {
- echo '<div class="debugCode"><pre>';
- print_r($var);
- echo '</pre></div>';
- }
-
- $client = new SoapClient('http://localhost:49319/PazaakService.asmx?WSDL');
- $game = $client->QuickQuickStart()->QuickQuickStartResult;
-
- echo "<h1>Game $game->GUID</h1>";
- echo "<h2>Table</h2>";
- $cards = $game->PlayerTable->string;
- if (is_array($cards)) {
- echo "<table><tr>";
- foreach ($cards as $card)
- echo "<td>$card</td>";
- echo "</tr></table>";
- } else {
- echo "<p>$cards</p>";
- }
- echo "<h2>Your hand</h2>";
-
- $cards = $game->PlayerHand->string;
- if (count($cards)) {
- echo "<table><tr>";
- foreach ($cards as $card)
- echo "<td>$card</td>";
- echo "</tr></table>";
- } else {
- echo "<p>-</p>";
- }
-
- echo "<h2>Debug</h2>";
- dprint_r($game);
+
+/**
+ * Pazaak webservice client, debug console
+ *
+ * This is a sandbox to test the Pazaak web service.
+ *
+ * 2010-07-20: Pazaak will be noted as a deprecated project at 2010-09-15.
+ *
+ * @package Zed
+ * @subpackage Pazaak
+ * @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
+ */
+
+/**
+ * Prints human-readable information about a variable (like the print_r command),
+ * enclosed in <div class="debugCode"><pre></pre></div> tags,
+ * to have a preformatted HTML output.
+ *
+ * @param mixed The expression to be printed
+ */
+function dprint_r ($expression) {
+ echo '<div class="debugCode"><pre>';
+ print_r($expression);
+ echo '</pre></div>';
+}
+
+$client = new SoapClient('http://10.0.0.4:49319/PazaakService.asmx?WSDL');
+$game = $client->QuickQuickStart()->QuickQuickStartResult;
+
+echo "<h1>Game $game->GUID</h1>";
+echo "<h2>Table</h2>";
+$cards = $game->PlayerTable->string;
+if (is_array($cards)) {
+ echo "<table><tr>";
+ foreach ($cards as $card)
+ echo "<td>$card</td>";
+ echo "</tr></table>";
+} else {
+ echo "<p>$cards</p>";
+}
+echo "<h2>Your hand</h2>";
+
+$cards = $game->PlayerHand->string;
+if (count($cards)) {
+ echo "<table><tr>";
+ foreach ($cards as $card)
+ echo "<td>$card</td>";
+ echo "</tr></table>";
+} else {
+ echo "<p>-</p>";
+}
+
+echo "<h2>Debug</h2>";
+dprint_r($game);
?>
\ No newline at end of file
diff --git a/cron.php b/cron.php
index 3ee5bc8..776c200 100644
--- a/cron.php
+++ b/cron.php
@@ -1,41 +1,57 @@
-<?php
-
-/*
- * Zed
- * (c) 2010, Dereckson, some rights reserved
- * Released under BSD license
- *
- * Cron
- */
-
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Initialization
-///
-
-//Pluton library
-include('includes/core.php');
-
-//Debug mode?
-$debug = false;
-
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Daily tasks
-///
-
-//Orders perso table by nickname.
-//Rationale: prints an ordered perso select list, help for new persos, printed at end
-$queries[] = "ALTER TABLE " . TABLE_PERSOS . " ORDER BY perso_nickname";
-
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Executes tasks
-///
-
-foreach ($queries as $query) {
- if (!$db->sql_query($sql) && $debug)
- message_die(SQL_ERROR, "Can't execute query", '', __LINE__, __FILE__, $sql);
-}
-
+<?php
+
+/**
+ * Cron
+ *
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2010, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * This file contains tasks to execute periodically.
+ * When editing this file, ensure it works from the command line, so it's
+ * possible to run it from a crontab calling PHP CLI.
+ *
+ * @package Zed
+ * @subpackage Utilities
+ * @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 Adds some periodicity (e.g. hourly, daily, monthly)
+ */
+
+////////////////////////////////////////////////////////////////////////////////
+///
+/// Initialization
+///
+
+//Pluton library
+include('includes/core.php');
+
+//Debug mode?
+$debug = false;
+
+////////////////////////////////////////////////////////////////////////////////
+///
+/// Daily tasks
+///
+
+//Orders perso table by nickname.
+//Rationale: prints an ordered perso select list, help for new persos, printed at end
+$queries[] = "ALTER TABLE " . TABLE_PERSOS . " ORDER BY perso_nickname";
+
+////////////////////////////////////////////////////////////////////////////////
+///
+/// Executes tasks
+///
+
+foreach ($queries as $query) {
+ if (!$db->sql_query($sql) && $debug)
+ message_die(SQL_ERROR, "Can't execute query", '', __LINE__, __FILE__, $sql);
+}
+
?>
\ No newline at end of file
diff --git a/do.php b/do.php
index cbb49ea..6b82483 100644
--- a/do.php
+++ b/do.php
@@ -1,255 +1,293 @@
-<?php
-
-/*
- * Zed
- * (c) 2010, Dereckson, some rights reserved
- * Released under BSD license
- *
- * AJAX callbacks
- *
- * As main controller could potentially be interrupted (e.g. if site.requests
- * flag is at 1, user is redirected to controllers/userrequest.php), all AJAX
- * queries should be handled by this script and not directly by the controllers.
- *
- * Standard return values:
- * -7 user is logged but perso isn't selected
- * -9 user is not logged
- *
- */
-
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Initialization
-///
-
-//Standard return values
-define('USER_NOT_LOGGED', -9);
-define('PERSO_NOT_SELECTED', -7);
-
-//Pluton library
-include('includes/core.php');
-
-//Session
-$IP = encode_ip($_SERVER["REMOTE_ADDR"]);
-require_once('includes/story/story.php'); //this class can be stored in session
-session_start();
-$_SESSION[ID] = session_id();
-session_update(); //updates or creates the session
-
-include("includes/login.php"); //login/logout
-$CurrentUser = get_logged_user(); //Gets current user infos
-
-//Gets current perso
-require_once('includes/objects/perso.php');
-if ($perso_id = $CurrentUser->session['perso_id']) {
- $CurrentPerso = new Perso($perso_id);
-}
-
-//Requires user and perso
-if ($CurrentUser->id < 1000) {
- echo USER_NOT_LOGGED;
- exit;
-}
-if (!$CurrentPerso) {
- echo PERSO_NOT_SELECTED;
- exit;
-}
-
-//Loads Smarty (as it handles l10n, it will be used by lang_get)
-require('includes/Smarty/Smarty.class.php');
-$smarty = new Smarty();
-$current_dir = dirname(__FILE__);
-$smarty->template_dir = $current_dir . '/skins/zed';
-$smarty->compile_dir = $current_dir . '/cache/compiled';
-$smarty->cache_dir = $current_dir . '/cache';
-$smarty->config_dir = $current_dir;
-
-//Loads language files
-initialize_lang();
-lang_load('core.conf');
-
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Actions definitions
-///
-
-/*
- * Actions class
- * Each method is called by first part of your URL, other parts are arguments
- * e.g. /do.php/validate_quux_request/52 = Actions::validate_quux_request(52);
- *
- * You can also use $_GET, $_POST or better $_REQUEST.
- *
- * Don't echo the value but return it, so we can in the future implement custom
- * formats like api_output();
- */
-
-class Actions {
- /*
- * Checks the arguments hash
- * @param Array $args the arguments, the last being the hash
- */
- static private function is_hash_valid ($args) {
- global $Config;
- return array_pop($args) == md5($_SESSION['ID'] . $Config['SecretKey'] . implode('', $args));
- }
-
- /*
- * Handles a allow/deny perso request
- * @param string $request_flag the request flag to clear
- * @param string $store 'perso' or 'registry'
- * @param string $key the perso flag or registry key
- * @param string $value the value to store
- * @param string $hash the security hash
- * @return boolean true if the request is valid and have been processed ; otherwise, false.
- */
- static function perso_request ($request_flag, $store, $key, $value, $hash) {
- global $CurrentPerso;
-
- //Ensures we've the correct amount of arguments
- if (func_num_args() < 4) return false;
-
- //Checks hash
- $args = func_get_args();
- if (!self::is_hash_valid($args)) {
- return false;
- }
-
- //Sets flag
- switch ($store) {
- case 'perso':
- $CurrentPerso->set_flag($key, $value);
- break;
-
- case 'registry':
- registry_set($key, $value);
- break;
-
- default:
- //Unknown storage location
- return false;
- }
-
- //Clears request flag
- if ((string)$request_flag !== "0") {
- $CurrentPerso->delete_flag($request_flag);
- }
-
- return true;
- }
-
- /*
- * Sets current perso's local location
- * @param string $location_local the local location
- * @return GeoLocation the current perso's GeoLocation object
- *
- * We don't require a security hash. If the users want to play with it, no problem.
- * You generally moves inside a global location as you wish.
- * So, if you write a story capturing a perso, use flags to handle this escape!
- */
- static function set_local_location ($location_local) {
- global $CurrentPerso;
-
- //Ensures we've the correct amount of arguments
- if (func_num_args() < 1) return null;
-
- //Moves current perso to specified location
- $CurrentPerso->move_to(null, $location_local);
-
- //Returns GeoLocation relevant instance
- return $CurrentPerso->location;
- }
-
- /*
- * Handles upload content form
- * @return string new content path
- */
- static function upload_content () {
- global $CurrentPerso, $CurrentUser;
- require_once('includes/objects/content.php');
- //Initializes a new content instance
- $content = new Content();
-
- //Reads form
- $content->load_from_form();
-
- //Sets current user/perso parameters
- $content->user_id = $CurrentUser->id;
- $content->perso_id = $CurrentPerso->id;
- $content->location_global = $CurrentPerso->location_global;
-
- //Saves file
- if ($content->handle_uploaded_file($_FILES['artwork'])) {
- $content->save_to_database();
- $content->generate_thumbnail();
- return true;
- }
-
- return false;
- }
- /*
- *
- * @return Array content files
- */
- static function get_content ($location_global) {
- //Ensures we've the correct amount of arguments
- if (func_num_args() < 1) return null;
-
- //Checks hash
- $args = func_get_args();
- if (!self::is_hash_valid($args)) {
- return false;
- }
-
- require_once('includes/objects/content.php');
- return Content::get_local_content($location_global, $_GET['location_local']);
- }
-}
-
-////////////////////////////////////////////////////////////////////////////////
-///
-/// Handles request
-///
-
-//You really should use $_SERVER['PATH_INFO']
-//i.e. calling /do.php/your request without any mod rewrite intervention
-//
-//If you choose otherwise, uncomment and tweak one of the following lines:
-//$Config['SiteURL'] = 'http://yourserver/zed/do.php';
-//$Config['SiteURL'] = get_server_url() . '/do.php';
-$args = get_current_url_fragments();
-
-$method = array_shift($args);
-
-if ($_REQUEST['debug']) {
- //Debug version
- //Most of E_STRICT errors are evaluated at the compile time thus such errors
- //are not reported
- ini_set('display_errors', 'stderr');
- error_reporting(-1);
- if (method_exists('Actions', $method)) {
- $result = call_user_func_array(array('Actions', $method), $args);
- echo json_encode($result);
- } else {
- echo "<p>Method doesn't exist: $method</p>";
- }
-
- if (array_key_exists('redirectTo', $_REQUEST)) {
- //If user JS disabled, you can add ?redirectTo= followed by an URL
- echo "<p>Instead to print a callback value, redirects to <a href=\"$_REQUEST[redirectTo]\">$_REQUEST[redirectTo]</a></p>";
- }
-} else {
- //Prod version doesn't prints warning <== silence operator
- if (method_exists('Actions', $method)) {
- $result = @call_user_func_array(array('Actions', $method), $args);
-
- if (array_key_exists('redirectTo', $_REQUEST)) {
- //If user JS disabled, you can add ?redirectTo= followed by an URL
- header("location: " . $_REQUEST['redirectTo']);
- } else {
- echo json_encode($result);
- }
- }
-}
-
+<?php
+
+/**
+ * AJAX callbacks
+ *
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2010, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * As main controller could potentially be interrupted (e.g. if site.requests
+ * flag is at 1, user is redirected to controllers/userrequest.php), all AJAX
+ * queries should be handled by this script and not directly by the controllers.
+ *
+ * Standard return values:
+ * -7 user is logged but perso isn't selected,
+ * -9 user is not logged.
+ *
+ * @package Zed
+ * @subpackage EntryPoints
+ * @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
+ */
+
+////////////////////////////////////////////////////////////////////////////////
+///
+/// Constants
+///
+
+//We define one negative number constant by standard erroneous return value.
+
+/**
+ * Magic number which indicates the user is not logged in.
+ */
+define('USER_NOT_LOGGED', -9);
+
+/**
+ * Magic number which indicates the user is logged in, but haven't selected its perso.
+ */
+define('PERSO_NOT_SELECTED', -7);
+
+////////////////////////////////////////////////////////////////////////////////
+///
+/// Initialization
+///
+
+//Pluton library
+include('includes/core.php');
+
+//Session
+$IP = encode_ip($_SERVER["REMOTE_ADDR"]);
+require_once('includes/story/story.php'); //this class can be stored in session
+session_start();
+$_SESSION[ID] = session_id();
+session_update(); //updates or creates the session
+
+include("includes/login.php"); //login/logout
+$CurrentUser = get_logged_user(); //Gets current user infos
+
+//Gets current perso
+require_once('includes/objects/perso.php');
+if ($perso_id = $CurrentUser->session['perso_id']) {
+ $CurrentPerso = new Perso($perso_id);
+}
+
+//Requires user and perso
+if ($CurrentUser->id < 1000) {
+ echo USER_NOT_LOGGED;
+ exit;
+}
+if (!$CurrentPerso) {
+ echo PERSO_NOT_SELECTED;
+ exit;
+}
+
+//Loads Smarty (as it handles l10n, it will be used by lang_get)
+require('includes/Smarty/Smarty.class.php');
+$smarty = new Smarty();
+$current_dir = dirname(__FILE__);
+$smarty->template_dir = $current_dir . '/skins/zed';
+$smarty->compile_dir = $current_dir . '/cache/compiled';
+$smarty->cache_dir = $current_dir . '/cache';
+$smarty->config_dir = $current_dir;
+
+//Loads language files
+initialize_lang();
+lang_load('core.conf');
+
+////////////////////////////////////////////////////////////////////////////////
+///
+/// Actions definitions
+///
+
+/**
+ * Actions class
+ *
+ * Each method is called by first part of your URL, other parts are arguments
+ * e.g. /do.php/validate_quux_request/52 = Actions::validate_quux_request(52);
+ *
+ * You can also use $_GET, $_POST or better $_REQUEST.
+ *
+ * Don't echo the value but return it, so we can in the future implement custom
+ * formats like api_output();
+ */
+
+class Actions {
+ /**
+ * Checks the arguments hash and determines wheter it is valid.
+ *
+ * @param Array $args the arguments, the last being the hash
+ * @return boolean true if the hash is valid ; otherwise, false.
+ */
+ static private function is_hash_valid ($args) {
+ global $Config;
+ return array_pop($args) == md5($_SESSION['ID'] . $Config['SecretKey'] . implode('', $args));
+ }
+
+ /**
+ * Handles a allow/deny perso request.
+ *
+ * @param string $request_flag the request flag to clear
+ * @param string $store 'perso' or 'registry'
+ * @param string $key the perso flag or registry key
+ * @param string $value the value to store
+ * @param string $hash the security hash
+ * @return boolean true if the request is valid and have been processed ; otherwise, false.
+ */
+ static function perso_request ($request_flag, $store, $key, $value, $hash) {
+ global $CurrentPerso;
+
+ //Ensures we've the correct amount of arguments
+ if (func_num_args() < 4) return false;
+
+ //Checks hash
+ $args = func_get_args();
+ if (!self::is_hash_valid($args)) {
+ return false;
+ }
+
+ //Sets flag
+ switch ($store) {
+ case 'perso':
+ $CurrentPerso->set_flag($key, $value);
+ break;
+
+ case 'registry':
+ registry_set($key, $value);
+ break;
+
+ default:
+ //Unknown storage location
+ return false;
+ }
+
+ //Clears request flag
+ if ((string)$request_flag !== "0") {
+ $CurrentPerso->delete_flag($request_flag);
+ }
+
+ return true;
+ }
+
+ /**
+ * Sets current perso's local location.
+ *
+ * We don't require a security hash. If the users want to play with it, no problem.
+ * You generally moves inside a global location as you wish.
+ * So, if you write a story capturing a perso, use flags to handle this escape!
+ *
+ * @param string $location_local the local location
+ * @return GeoLocation the current perso's GeoLocation object
+ */
+ static function set_local_location ($location_local) {
+ global $CurrentPerso;
+
+ //Ensures we've the correct amount of arguments
+ if (func_num_args() < 1) return null;
+
+ //Moves current perso to specified location
+ $CurrentPerso->move_to(null, $location_local);
+
+ //Returns GeoLocation relevant instance
+ return $CurrentPerso->location;
+ }
+
+ /**
+ * Handles upload content form.
+ *
+ * @return string new content path
+ */
+ static function upload_content () {
+ global $CurrentPerso, $CurrentUser;
+ require_once('includes/objects/content.php');
+ //Initializes a new content instance
+ $content = new Content();
+
+ //Reads form
+ $content->load_from_form();
+
+ //Sets current user/perso parameters
+ $content->user_id = $CurrentUser->id;
+ $content->perso_id = $CurrentPerso->id;
+ $content->location_global = $CurrentPerso->location_global;
+
+ //Saves file
+ if ($content->handle_uploaded_file($_FILES['artwork'])) {
+ $content->save_to_database();
+ $content->generate_thumbnail();
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * Gets multimedia content for the specified location
+ *
+ * @param string $location_global The global location (local is to specified in ?location_local parameter)
+ * @return Array an array of Content instances
+ */
+ static function get_content ($location_global) {
+ //Ensures we've the correct amount of arguments
+ if (func_num_args() < 1) return null;
+
+ //Checks hash
+ $args = func_get_args();
+ if (!self::is_hash_valid($args)) {
+ return false;
+ }
+
+ //Checks local location is specified somewhere (usually in $_GET)
+ if (!array_key_exists('location_local', $_REQUEST)) {
+ return false;
+ }
+
+ //Gets content
+ require_once('includes/objects/content.php');
+ return Content::get_local_content($location_global, $_REQUEST['location_local']);
+ }
+}
+
+////////////////////////////////////////////////////////////////////////////////
+///
+/// Handles request
+///
+
+//You really should use $_SERVER['PATH_INFO']
+//i.e. calling /do.php/your request without any mod rewrite intervention
+//
+//If you choose otherwise, uncomment and tweak one of the following lines:
+//$Config['SiteURL'] = 'http://yourserver/zed/do.php';
+//$Config['SiteURL'] = get_server_url() . '/do.php';
+$args = get_current_url_fragments();
+
+$method = array_shift($args);
+
+if ($_REQUEST['debug']) {
+ //Debug version
+ //Most of E_STRICT errors are evaluated at the compile time thus such errors
+ //are not reported
+ ini_set('display_errors', 'stderr');
+ error_reporting(-1);
+ if (method_exists('Actions', $method)) {
+ $result = call_user_func_array(array('Actions', $method), $args);
+ echo json_encode($result);
+ } else {
+ echo "<p>Method doesn't exist: $method</p>";
+ }
+
+ if (array_key_exists('redirectTo', $_REQUEST)) {
+ //If user JS disabled, you can add ?redirectTo= followed by an URL
+ echo "<p>Instead to print a callback value, redirects to <a href=\"$_REQUEST[redirectTo]\">$_REQUEST[redirectTo]</a></p>";
+ }
+} else {
+ //Prod version doesn't prints warning <== silence operator
+ if (method_exists('Actions', $method)) {
+ $result = @call_user_func_array(array('Actions', $method), $args);
+
+ if (array_key_exists('redirectTo', $_REQUEST)) {
+ //If user JS disabled, you can add ?redirectTo= followed by an URL
+ header("location: " . $_REQUEST['redirectTo']);
+ } else {
+ echo json_encode($result);
+ }
+ }
+}
+
?>
\ No newline at end of file
diff --git a/includes/core.php b/includes/core.php
index 7662ab4..7bdc9c5 100644
--- a/includes/core.php
+++ b/includes/core.php
@@ -1,549 +1,573 @@
<?php
-/*
- * Zed
- * (c) 2010, Dereckson, some rights reserved
- * Released under BSD license
+/**
+ * Core: helper methods and main libraries loader
*
- * Core
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2010, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * @package Zed
+ * @subpackage Pluton
+ * @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
*/
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Configures PHP and loads site-wide used libraries ///
/// ///
////////////////////////////////////////////////////////////////////////////////
//No register globals
ini_set('register_globals', 'off');
error_reporting(E_ALL & ~E_NOTICE);
//Load libraries
include_once("config.php"); //Site config
include_once("error.php"); //Error management
include_once("mysql.php"); //MySQL layer
include_once("sessions.php"); //Sessions handler
include_once("autoload.php"); //__autoload()
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Information helper methods ///
/// ///
////////////////////////////////////////////////////////////////////////////////
-//Gets username from specified user_id
-function get_name ($id) {
+/**
+ * Gets the nickname from the specified perso
+ *
+ * @param integer $perso_id The specified perso's ID
+ * @return string The perso's nickname
+ */
+function get_name ($perso_id) {
global $db;
- $id = $db->sql_escape($id);
- $sql = 'SELECT perso_nickname FROM '. TABLE_PERSOS . " WHERE perso_id = '$id'";
+ $perso_id = $db->sql_escape($perso_id);
+ $sql = 'SELECT perso_nickname FROM '. TABLE_PERSOS . " WHERE perso_id = '$perso_id'";
if (!$result = $db->sql_query($sql)) message_die(SQL_ERROR, "Can't query persos table.", '', __LINE__, __FILE__, $sql);
$row = $db->sql_fetchrow($result);
return $row['perso_nickname'];
}
//Gets user_id from specified username
function get_userid ($username) {
global $db;
$username = $db->sql_escape($username);
$sql = 'SELECT user_id FROM '. TABLE_USERS . " WHERE username LIKE '$username'";
if (!$result = $db->sql_query($sql)) message_die(SQL_ERROR, "Can't query users table.", '', __LINE__, __FILE__, $sql);
$row = $db->sql_fetchrow($result);
return $row['user_id'];
}
function registry_get ($key) {
global $db;
$key = $db->sql_escape($key);
$sql = "SELECT registry_value FROM " . TABLE_REGISTRY . " WHERE registry_key = '$key'";
if (!$result = $db->sql_query($sql)) message_die(SQL_ERROR, "Can't read registry.", '', __LINE__, __FILE__, $sql);
$row = $db->sql_fetchrow($result);
return $row['registry_value'];
}
function registry_set ($key, $value) {
global $db;
$key = $db->sql_escape($key);
$value = $db->sql_escape($value);
$sql = "REPLACE INTO " . TABLE_REGISTRY . " (registry_key, registry_value) VALUES ('$key', '$value')";
if (!$db->sql_query($sql))
message_die(SQL_ERROR, "Can't update registry", '', __LINE__, __FILE__, $sql);
}
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Misc helper methods ///
/// ///
////////////////////////////////////////////////////////////////////////////////
/*
* Generates a random string
* @author Pierre Habart <p.habart@ifrance.com>
*
* @param string $format The format e.g. AAA111
* @return string a random string
*/
function genereString ($format) {
mt_srand((double)microtime()*1000000);
$str_to_return="";
$t_alphabet=explode(",","A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z");
$t_number=explode(",","1,2,3,4,5,6,7,8,9,0");
for ($i=0;$i<strlen($format);$i++)
{
if (preg_match("/^[a-zA-Z]/",$format[$i]))
{
$add=$t_alphabet[mt_rand() % sizeof($t_alphabet)];
if (preg_match("/^[a-z]/",$format[$i]))
$add=strtolower($add);
}
elseif(preg_match("/^[0-9]/",$format[$i]))
$add=$t_number[mt_rand() % sizeof($t_number)];
else $add="?";
$str_to_return.=$add;
}
return $str_to_return;
}
function generer_hexa($longueur) {
mt_srand((double)microtime()*1000000);
$str_to_return="";
$t_number=explode(",","1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F");
for ($i = 0 ; $i < $longueur ; $i++) {
$str_to_return .= $t_number[mt_rand() % sizeof($t_number)];
}
return $str_to_return;
}
//Plural management
function s ($amount) {
if ($amount > 1) return "s";
}
function x ($amount) {
if ($amount > 1) return "x";
}
//Debug
-function dprint_r ($mixed) {
- echo "<pre>", print_r($mixed, true), "</pre>";
+/**
+ * Prints human-readable information about a variable (like the print_r command),
+ * enclosed in <pre></pre> tags, to have a preformatted HTML output.
+ *
+ * @param mixed The expression to be printed
+ */
+function dprint_r ($expression) {
+ echo '<pre>';
+ print_r($expression);
+ echo '</pre>';
}
//GUID
function new_guid() {
$characters = explode(",","a,b,c,d,e,f,0,1,2,3,4,5,6,7,8,9");
$guid = "";
for ($i = 0 ; $i < 36 ; $i++) {
if ($i == 8 || $i == 13 || $i == 18 || $i == 23) {
$guid .= "-";
} else {
$guid .= $characters[mt_rand() % sizeof($characters)];
}
}
return $guid;
}
function is_guid ($expression) {
//We avoid regexp to speed up the check
//A guid is a 36 characters string
if (strlen($expression) != 36) return false;
$expression = strtolower($expression);
for ($i = 0 ; $i < 36 ; $i++) {
if ($i == 8 || $i == 13 || $i == 18 || $i == 23) {
//with dashes
if ($expression[$i] != "-") return false;
} else {
//and numbers
if (!is_numeric($expression[$i]) && $expression[$i] != 'a' && $expression[$i] != 'b' && $expression[$i] != 'c' && $expression[$i] != 'd' && $expression[$i] != 'e' && $expression[$i] != 'f' ) return false;
}
}
return true;
}
/*
* Gets file extension
* @param string $file the file to get the extension
*/
function get_extension ($file) {
$dotPosition = strrpos($file, ".");
return substr($file, $dotPosition + 1);
}
/*
* Determines if a string starts with specified substring
* @param string $haystack the string to check
* @param string $needle the substring to determines if it's the start
* @param boolean $case_sensitive determines if the search must be case sensitive
* @return boolean true if $haystack starts with $needle ; otherwise, false.
*/
function string_starts_with ($haystack, $needle, $case_sensitive = true) {
if (!$case_sensitive) {
$haystack = strtoupper($haystack);
$needle = strtoupper($needle);
}
if ($haystack == $needle) return true;
return strpos($haystack, $needle) === 0;
}
/*
* Inserts a message into the supralog
* @param string $category the entry category
* @param string $message the message to log
* @param string $source the entry source.
*/
function supralog ($category, $message, $source = null) {
global $db, $CurrentUser, $CurrentPerso;
$category = $db->sql_query_express($category);
$message = $db->sql_query_express($message);
$source = $db->sql_query_express($source ? $source : $_SERVER['SERVER_ADDR']);
$ip = $_SERVER['REMOTE_ADDR'];
$sql = "INSERT INTO " . TABLE_LOG .
" (entry_ip, user_id, perso_id, entry_category, entry_message, entry_source) VALUES
('$ip', $CurrentUser->id, $CurrentPerso->id, '$category', '$message', '$source')";
if ( !($result = $db->sql_query($sql)) )
message_die(SQL_ERROR, "Can't log this entry.", '', __LINE__, __FILE__, $sql);
}
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Localization (l10n) ///
/// ///
////////////////////////////////////////////////////////////////////////////////
/*
* Defines LANG constant to lang to print
*/
function initialize_lang () {
//If $_SESSION['lang'] doesn't exist yet, find a common language
if (!array_key_exists('lang', $_SESSION)) {
$lang = find_lang();
$_SESSION['lang'] = $lang ? $lang : '-';
}
if ($_SESSION['lang'] != '-')
define('LANG', $_SESSION['lang']);
}
/*
* Gets a common lang spoken by the site and the user
* @return string the language
*/
function find_lang () {
if (file_exists('lang') && is_dir('lang')) {
//Gets lang/ subdirectories: this is the list of available languages
$handle = opendir('lang');
while ($file = readdir($handle)) {
if ($file != '.' && $file != '..' && is_dir("lang/$file")) {
$langs[] = $file;
}
}
//The array $langs contains now the language available.
//Gets the langs the user should want:
if (!$userlangs = get_http_accept_languages())
return;
//Gets the intersection between the both languages arrays
//If it matches, returns first result
$intersect = array_intersect($userlangs, $langs);
if (count($intersect)) {
return $intersect[0];
}
//Now it's okay with Opera and Firefox but Internet Explorer will
//by default return en-US and not en or fr-BE and not fr, so second pass
foreach ($userlangs as $userlang) {
$lang = explode('-', $userlang);
if (count($lang) > 1)
$userlangs2[] = $lang[0];
}
$intersect = array_intersect($userlangs2, $langs);
if (count($intersect)) {
return $intersect[0];
}
}
}
/*
* Returns the languages accepted by the browser, by order of priority
* @return Array a array of languages string
*/
function get_http_accept_languages () {
//What language to print is sent by browser in HTTP_ACCEPT_LANGUAGE var.
//This will be something like en,fr;q=0.8,fr-fr;q=0.5,en-us;q=0.3
if (!array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
return null;
}
$http_accept_language = explode(',', $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
foreach ($http_accept_language as $language) {
$userlang = explode(';q=', $language);
if (count($userlang) == 1) {
$userlangs[] = array(1, $language);
} else {
$userlangs[] = array($userlang[1], $userlang[0]);
}
}
rsort($userlangs);
foreach ($userlangs as $userlang) {
$result[] = $userlang[1];
}
return $result;
}
/*
* Loads specified language Smarty configuration file
*
* @param string $file the file to load
* @param mixed $sections array of section names, single section or null
*/
function lang_load ($file, $sections = null) {
global $smarty;
//Loads English file as fallback if some parameters are missing
if (file_exists("lang/en/$file"))
$smarty->config_load("lang/en/$file", $sections);
//Loads wanted file (if it exists and a language have been defined)
if (defined('LANG') && LANG != 'en' && file_exists('lang/' . LANG . '/' . $file))
$smarty->config_load('lang/' . LANG . '/' . $file, $sections);
}
/*
* Gets a specified language expression defined in configuration file
*
* @param string $key the configuration key matching the value to get
* @return string The value in the configuration file
*/
function lang_get ($key) {
global $smarty;
$smartyConfValue = $smarty->config_vars[$key];
return $smartyConfValue ? $smartyConfValue : "#$key#";
}
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Zed date and time helper methods ///
/// ///
////////////////////////////////////////////////////////////////////////////////
/*
* Converts a YYYYMMDD or YYYY-MM-DD timestamp to unixtime
*/
function to_unixtime ($timestamp) {
switch (strlen($timestamp)) {
case 8:
//YYYYMMDD
return mktime(0, 0, 0, substr($timestamp, 4, 2), substr($timestamp, 6, 2), substr($timestamp, 0, 4));
case 10:
//YYYY-MM-DD
return mktime(0, 0, 0, substr($timestamp, 5, 2), substr($timestamp, 8, 2), substr($timestamp, 0, 4));
default:
throw new Exception("timestamp is not a valid YYYYMMDD or YYYY-MM-DD timestamp: $timestamp");
}
}
/*
* Converts a unixtime to the YYYYMMDD or YYYY-MM-DD timestamp format
*
* @param int $unixtime the time to convert
* @param int $format 8 or 10. If 8 (default), will output YYYYMMDD. If 10, YYYY-MM-DD.
*/
function to_timestamp ($unixtime = null, $format = 8) {
//If no parameter is specified (or null, or false), current time is used
//==== allows to_timestamp(0) to return correct 1970-1-1 value.
if ($unixtime === null || $unixtime === false) $unixtime = time();
switch ($format) {
case 8:
//YYYYMMDD
return date('Ymd', $unixtime);
case 10:
//YYYY-MM-DD
return date('Y-m-d', $unixtime);
default:
throw new Exception("format must be 8 (YYYYMMDD) or 10 (YYYY-MM-DD) and not $format.");
}
}
/*
* Converts a unixtime to the Hypership time format.
*/
function get_hypership_time ($unixtime = null) {
//If unixtime is not specified, it's now
if ($unixtime === null) $unixtime = time();
//Hypership time is a count of days since launch @ 2010-07-03 00:00:00
//Followed by a fraction of the current day /1000, like the internet time
//but in UTC timezone and not Switzerland CET/CEST.
//We don't need to use floor(), as we output the result at int, truncating
//automatically decimal values instead of round it (like in C).
$seconds = $unixtime - 1278115200;
$days = $seconds / 86400;
$fraction = (abs($seconds) % 86400) / 86.4;
return sprintf("%d.%03d", $days, $fraction);
}
////////////////////////////////////////////////////////////////////////////////
/// ///
/// URL helpers functions ///
/// ///
////////////////////////////////////////////////////////////////////////////////
-/*
+/**
* Gets URL
* @return string URL
*/
function get_url () {
global $Config;
if (func_num_args() > 0) {
$pieces = func_get_args();
return $Config['BaseURL'] . '/' . implode('/', $pieces);
} elseif ($Config['BaseURL'] == "" || $Config['BaseURL'] == "/index.php") {
return "/";
} else {
return $Config['BaseURL'];
}
}
/*
* Gets page URL
* @return string URL
*/
function get_page_url () {
$url = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];
if (substr($url, -10) == "/index.php") {
return substr($url, 0, -9);
}
return $url;
}
/*
* Gets server URL
* @todo find a way to detect https:// on non standard port
* @return string the server URL
*/
function get_server_url () {
switch ($port = $_SERVER['SERVER_PORT']) {
case '80':
return "http://$_SERVER[SERVER_NAME]";
case '443':
return "https://$_SERVER[SERVER_NAME]";
default:
return "http://$_SERVER[SERVER_NAME]:$_SERVER[SERVER_PORT]";
}
}
/*
* Gets $_SERVER['PATH_INFO'] or computes the equivalent if not defined.
* @return string the relevant URL part
*/
function get_current_url () {
global $Config;
//Gets relevant URL part from relevant $_SERVER variables
if (array_key_exists('PATH_INFO', $_SERVER)) {
//Without mod_rewrite, and url like /index.php/controller
//we use PATH_INFO. It's the easiest case.
return $_SERVER["PATH_INFO"];
}
//In other cases, we'll need to get the relevant part of the URL
$current_url = get_server_url() . $_SERVER['REQUEST_URI'];
//Relevant URL part starts after the site URL
$len = strlen($Config['SiteURL']);
//We need to assert it's the correct site
if (substr($current_url, 0, $len) != $Config['SiteURL']) {
dieprint_r(GENERAL_ERROR, "Edit includes/config.php and specify the correct site URL<br /><strong>Current value:</strong> $Config[SiteURL]<br /><strong>Expected value:</strong> a string starting by " . get_server_url(), "Setup");
}
if (array_key_exists('REDIRECT_URL', $_SERVER)) {
//With mod_rewrite, we can use REDIRECT_URL
//We takes the end of the URL, ie *FROM* $len position
return substr(get_server_url() . $_SERVER["REDIRECT_URL"], $len);
}
//Last possibility: use REQUEST_URI, but remove QUERY_STRING
//If you need to edit here, use $_SERVER['REQUEST_URI']
//but you need to discard $_SERVER['QUERY_STRING']
//We takes the end of the URL, ie *FROM* $len position
$url = substr(get_server_url() . $_SERVER["REQUEST_URI"], $len);
//But if there are a query string (?action=... we need to discard it)
if ($_SERVER['QUERY_STRING']) {
return substr($url, 0, strlen($url) - strlen($_SERVER['QUERY_STRING']) - 1);
}
return $url;
}
/*
* Gets an array of url fragments to be processed by controller
*/
function get_current_url_fragments () {
$url_source = get_current_url();
if ($url_source == '/index.php') return array();
return explode('/', substr($url_source, 1));
}
////////////////////////////////////////////////////////////////////////////////
/// ///
/// URL xmlHttpRequest helpers functions ///
/// ///
////////////////////////////////////////////////////////////////////////////////
/*
* Gets an hash value to check the integrity of URLs in /do.php calls
* @param Array $args the args to compute the hash
* @return the hash paramater for your xmlHttpRequest url
*/
function get_xhr_hash ($args) {
global $Config;
array_shift($args);
return md5($_SESSION['ID'] . $Config['SecretKey'] . implode('', $args));
}
/*
* Gets the URL to call do.php, the xmlHttpRequest controller
* @return string the xmlHttpRequest url, with an integrity hash
*/
function get_xhr_hashed_url () {
global $Config;
$args = func_get_args();
$args[] = get_xhr_hash($args);
return $Config['DoURL'] . '/' . implode('/', $args);
}
/*
* Gets the URL to call do.php, the xmlHttpRequest controller
* @return string the xmlHttpRequest url
*/
function get_xhr_url () {
global $Config;
$args = func_get_args();
return $Config['DoURL'] . '/' .implode('/', $args);
}
?>
diff --git a/index.php b/index.php
index b1a105a..864bfd7 100644
--- a/index.php
+++ b/index.php
@@ -1,217 +1,230 @@
<?php
-/*
- * Zed
- * (c) 2010, Dereckson, some rights reserved
- * Released under BSD license
- *
+/**
* Application entry point
+ *
+ * Zed. The immensity of stars. The HyperShip. The people.
+ *
+ * (c) 2010, Dereckson, some rights reserved.
+ * Released under BSD license.
+ *
+ * @package Zed
+ * @subpackage EntryPoints
+ * @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 Consider to split the different tasks (especially
+ * perso select/create into several files)
*/
////////////////////////////////////////////////////////////////////////////////
///
/// Initialization
///
//Pluton library
include('includes/core.php');
//Session
$IP = encode_ip($_SERVER["REMOTE_ADDR"]);
require_once('includes/story/story.php'); //this class can be stored in session
session_start();
$_SESSION[ID] = session_id();
session_update(); //updates or creates the session
include("includes/login.php"); //login/logout
$CurrentUser = get_logged_user(); //Gets current user infos
//Gets current perso
require_once('includes/objects/perso.php');
if ($perso_id = $CurrentUser->session['perso_id']) {
$CurrentPerso = new Perso($perso_id);
}
//Skin and accent to load
define('THEME', $CurrentUser->session['Skin']);
define('ACCENT', $CurrentUser->session['Skin_accent']);
//Loads Smarty
require('includes/Smarty/Smarty.class.php');
$smarty = new Smarty();
$current_dir = dirname(__FILE__);
$smarty->template_dir = $current_dir . '/skins/' . THEME;
$smarty->compile_dir = $current_dir . '/cache/compiled';
$smarty->cache_dir = $current_dir . '/cache';
$smarty->config_dir = $current_dir;
$smarty->config_vars['StaticContentURL'] = $Config['StaticContentURL'];
//Loads language files
initialize_lang();
lang_load('core.conf');
//Gets URL
$url = get_current_url_fragments();
//If the user isn't logged in (is anonymous), prints login/invite page & dies.
if ($CurrentUser->id < 1000) {
include('controllers/anonymous.php');
exit;
}
////////////////////////////////////////////////////////////////////////////////
///
/// Perso selector
///
//Handles form
if ($_POST['form'] == 'perso.create') {
$perso = new Perso();
$perso->load_from_form();
$perso->user_id = $CurrentUser->id;
//Validates forms
if (!$perso->name) $errors[] = lang_get("NoFullnameSpecified");
if (!$perso->race) {
$errors[] = lang_get("NoRaceSpecified");
$perso->race = "being";
}
if (!$perso->sex) $errors[] = lang_get("NoSexSpecified");
if (!$perso->nickname) {
$errors[] = lang_get("NoNicknameSpecified");
} else if (!Perso::is_available_nickname($perso->nickname)) {
$errors[] = lang_get("UnavailableNickname");
}
//Save or prints again forms
if (!$errors) {
//Saves perso, logs in
$perso->save_to_database();
$smarty->assign('NOTIFY', lang_get('NewCharacterCreated'));
$CurrentPerso = $perso;
set_info('perso_id', $perso->id);
$CurrentPerso->set_flag("site.lastlogin", $_SERVER['REQUEST_TIME']);
//Notifies inviter
require_once('includes/objects/message.php');
require_once('includes/objects/invite.php');
$message = new Message();
$message->from = 0;
$message->to = invite::who_invited($perso->id);
$message->text = sprintf(
lang_get('InvitePersoCreated'),
$perso->name,
get_server_url() . get_url('who', $perso->nickname)
);
$message->send();
} else {
$smarty->assign('WAP', join("<br />", $errors));
$smarty->assign('perso', $perso);
}
}
if ($_GET['action'] == 'perso.logout' && $CurrentPerso != null) {
//User wants to change perso
$CurrentPerso->on_logout();
$CurrentPerso = null;
} elseif ($_GET['action'] == 'perso.select') {
//User have selected a perso
$CurrentPerso = new Perso($_GET['perso_id']);
if ($CurrentPerso->user_id != $CurrentUser->id) {
//Hack
message_die(HACK_ERROR, "This isn't your perso.");
}
$CurrentPerso->on_select();
}
if (!$CurrentPerso) {
switch ($count = Perso::get_persos_count($CurrentUser->id)) {
case 0:
//User have to create a perso
$smarty->display("perso_create.tpl");
exit;
case 1:
//Autoselects only perso
$CurrentPerso = Perso::get_first_perso($CurrentUser->id);
$CurrentPerso->on_select();
break;
default:
//User have to pick a perso
$persos = Perso::get_persos($CurrentUser->id);
$smarty->assign("PERSOS", $persos);
$smarty->display("perso_select.tpl");
$_SESSION['UserWithSeveralPersos'] = true;
exit;
}
}
//Assigns current perso object as Smarty variable
$smarty->assign('CurrentPerso', $CurrentPerso);
////////////////////////////////////////////////////////////////////////////////
///
/// Tasks to execute before calling the URL controller:
/// - assert the perso is somewhere
/// - executes the smartline
///
//If the perso location is unknown, ejects it to an asteroid
if (!$CurrentPerso->location_global) {
require_once('includes/geo/place.php');
$smarty->assign('NOTIFY', lang_get('NewLocationNotify'));
$CurrentPerso->move_to(GeoPlace::get_start_location());
}
//SmartLine
include("includes/SmartLine/ZedSmartLine.php");
//Redirects user to user request controller if site.requests flag on
if (defined('PersoSelected') && array_key_exists('site.requests', $CurrentPerso->flags) && $CurrentPerso->flags['site.requests']) {
include('controllers/persorequest.php');
}
////////////////////////////////////////////////////////////////////////////////
///
/// Calls the specific controller to serve the requested page
///
switch ($controller = $url[0]) {
case '':
include('controllers/home.php');
break;
case 'request':
case 'page':
case 'explore':
case 'ship':
case 'settings':
include("controllers/$controller.php");
break;
case 'who':
include('controllers/profile.php'); //Azhàr controller
break;
case 'push':
include('controllers/motd.php'); //Azhàr controller
break;
case 'quux':
//It's like a test/debug console/sandbox, you put what you want into
if (file_exists('dev/quux.php')) {
include('dev/quux.php');
} else {
message_die(GENERAL_ERROR, "Quux lost in Hollywood.", "Nay");
}
break;
default:
//TODO: returns a 404 error
dieprint_r($url, 'Unknown URL');
}
?>
\ No newline at end of file

File Metadata

Mime Type
text/x-diff
Expires
Sat, Nov 23, 09:44 (1 d, 4 h ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
20890
Default Alt Text
(77 KB)

Event Timeline