Page MenuHomeCode

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
This document is not UTF8. It was detected as ISO-8859-1 (Latin 1) and converted to UTF8 for display.
diff --git a/README b/README
index 6f04dc6..52033de 100644
--- a/README
+++ b/README
@@ -1,164 +1,164 @@
ZzzzzzZ zz
Z z z The spatial gallery / social network / lounge
z z (c) 2010, Dereckson, some rights reserved.
z zzzzz zzzzz
z z z z z 0.1 alpha technical preview
z zzzzzzz z z
z z z z Last update hypership time: 5.096
z Z z z z z
ZzzzzzZ zzzzz zzzzzz
=========
INSTALL
=========
- * Zed is a PHP 5.3 application.
+ * Zed is a PHP 5.4 application.
* You can import dev/schema-mysql.sql as original SQL schema
* The configuration file is includes/config.php
* Files are cached in 3 directories of the cache folder, sets appropriate
write permissions to:
compiled openid sessions
* Zed needs but doesn't include in its code the Janrain OpenID PHP libraries:
http://www.janrain.com/openid-enabled - http://github.com/openid/php-openid
Put the Auth folder somewhere in your include_dir path.
bcmath and GMP php extensions are recommended (required?) for OpenID.
Our dev environment outputs a white page without error if GMP isn't here.
If you don't wish to enable OpenID, replace your includes/login.php by
http://hg.dereckson.be/zed/src/0ffd1b08f33c/includes/login.php
* Another used PHP extension is the WDDX one, to store session information in
a human-readable format, easier to debug.
If you don't want that, comment the following line from includes/config.php:
ini_set('session.serialize_handler', 'wddx');
=========
UPGRADE
=========
* For our main prod install, we use a script exporting last repo revision with
hg archive and applying a patch to config.php.
===========
LOCATIONS
===========
* Global location is a 9 letters code
<B,S> <body or spaceship id> <place where you are in this body/spaceship>
zerofilled 5 digits zerofilled 3 digits
You can also find 6 digits expressions e.g. B00001 is the hypership
* Local location varies of the place.
- On hypership core (B00001002): Sector C<0-8> Level <z> Zone <x-y>
- 0 is the gravity center
- 1-8 the 8 cubes surrounding it: 1-4 below, 5-8 above
- On the ship tower (B00001001): Sector T<z> Couloir <1-6>
- z is the level
- couloir depends of your x, y position (polar coordinates could help)
=================
HYPERSHIP TIME?
=================
* The amount of days since hypership launch, July 3rd 2010 00:00 UTC
* So the decimal part is like internet time, but in GMT and not CET/CEST
===============
SIDE PROJECTS
===============
* A pazaak game, to have something to play
* Will be an Arzakon client
=================
I WANT TO HELP!
=================
* You can create new SmartLine commands
* You can translate it in a new language
Start point: http://zed.dereckson.be/lang/en/core.conf
* You can code a bit of adventure, places description, stuff to do
as long you don't transform it in ogame clone (we're building a community
who want or don't want to play, but not a mechanic game)
and as long no money is involved (if you ask why, read Iain M. Banks novels)
in the hypership (in far asteroids, orbitals, planets you do what you want)
============
KNOWN BUGS
============
* Javascript get_hypership_time will returns 5.94 instead 5.094
Some %03d to add in /js/misc.js
* The floater rendering adds a black line under Opera
dojox.layout.floatingPane bug, need to check with last dojo version
* API /location query will break indent on location->body->location
beautify XML code to improve
* do.php allows any local location move, discarding FrL status
* The upload artwork dojo form can't be closed under Opera
=======================
API - General methods
=======================
* /api.php/time
Returns hypership time
Public access
* /api.php/perso/<perso_id>
Returns perso object
Created only to test extensively recursivity of api xml output
It's disabled since 10.811 on zed.dereckson.be, if you need an alternative,
open a bug report with the fields you need. Ship API should be able to manage
inventory if user is on. Ship API must also be able to get/set custom flags.
Requires a key
* /api.php/location/<location code or name>
Returns location object
Tip: to get the full name, use string eg /api.php/location/Zeta?format=string
Requires a key
* GET/POST API parameters
- key
API key, ask it at zed at dereckson be, object [DEV] api key request
- format
- preview print_r representation, so you've an idea of the object
- json json_encode() output
- php serialize() output
- wddx WDDX were an early universal serialization attempt
- xml XML document
- string output "as is" (or if it's an object, calls __toString())
============
API - Ship
=============
* /api.php/ship/authenticate/<perso nickname>
=================
ACKNOWLEDGEMENT
=================
Elfix, to have let me figure a regexp correction, instead to throw away regexp
validation for places local location.
diff --git a/controllers/anonymous.php b/controllers/anonymous.php
index 955fb15..27812c9 100644
--- a/controllers/anonymous.php
+++ b/controllers/anonymous.php
@@ -1,154 +1,154 @@
<?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 from 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 existing 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();
+ $errors = [];
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 host
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);
$template = 'login.tpl';
break;
}
//
// HTML output
//
if ($template) {
$smarty->display($template);
}
diff --git a/controllers/persorequest.php b/controllers/persorequest.php
index d5c3f2d..3b0caa3 100644
--- a/controllers/persorequest.php
+++ b/controllers/persorequest.php
@@ -1,166 +1,166 @@
<?php
/**
* Persos' requests
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* This controller handle the /requests URL.
*
* It can also be called with the requests SmartLine command.
*
* It allows to prints a content page.
*
* This controllers uses the persorequests.tpl view.
*
* This controller offer AJAX capabilities but degrades gracefully in JS.
*
* @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
*
* @todo Document the request system in the API documentation
*/
///
/// Helper class and method
///
/**
* A perso request
*/
class PersoRequest {
public $message;
public $requestFlag;
public $flag;
public $store = 'perso';
public $value_allow = 1;
public $value_deny = 0;
/**
* Initialises a perso request
*
* @param string $requestFlag the request's flag
* @param string $message the message to print
* @param string $message the flag to set, according the request approve/denial
*/
function __construct ($requestFlag, $message, $flag) {
$this->requestFlag = $requestFlag;
$this->message = $message;
$this->flag = $flag;
}
}
/**
* Gets request allow URL
*
* @param PersoRequest $request the perso request to confirm
* @return string the URL to allow the request
*/
function get_request_allow_url ($request) {
return get_request_url($request->requestFlag, $request->store, $request->flag, $request->value_allow);
}
/**
* Gets request deny URL
*
* @param PersoRequest $request the perso request to confirm
* @return string the URL to deny the request
*/
function get_request_deny_url ($request) {
return get_request_url($request->requestFlag, $request->store, $request->flag, $request->value_deny);
}
/**
* Gets request URL
*
* @param string $store 'perso' or 'registry'
* @param string $key the perso flag or registry key
* @param string $value the value to store
* @return the request URL
*/
function get_request_url ($requestFlag, $store, $key, $value) {
global $Config;
$hash = md5($_SESSION['ID'] . $Config['SecretKey'] . $requestFlag . $store . $key . $value);
return "$Config[DoURL]/perso_request/$requestFlag/$store/$key/$value/$hash";
}
///
/// Get requests
///
//Loads perso request language file
lang_load('persorequest.conf');
//The array request will be passed to Smarty and will contain PersoRequest items.
-$requests = array();
+$requests = [];
foreach ($CurrentPerso->flags as $flag => $value) {
if ($value && substr($flag, 0, 8) == "request.") {
if (string_starts_with($flag, 'request.api.ship.auth.')) {
//Gets ship
require_once('include/objects/ship.php');
$ship_code = substr($flag, 22);
$ship = Ship::get($ship_code);
//Adds request
$message = sprintf(lang_get('RequestShipAPIAuthenticate'), $ship->name);
$requests[] = new PersoRequest($flag, $message, substr($flag, 8));
} elseif (string_starts_with($flag, 'request.api.ship.session.')) {
//Gets ship
require_once('include/objects/ship.php');
$ship_code = substr($flag, 25, 6);
$ship = Ship::get($ship_code);
//Adds request
$message = sprintf(lang_get('RequestShipAPISessionConfirm'), $ship->name);
$request = new PersoRequest($flag, $message, substr($flag, 8));
$request->value_allow = $CurrentPerso->id;
$request->value_deny = -1;
$request->store = 'registry';
$requests[] = $request;
} else {
message_die(GENERAL_ERROR, "Unknown request flag: $flag. Please report this bug.");
}
}
}
///
/// Requests handling
///
if (count($requests) == 0) {
//If site.requests flag is at 1 but we don't have request, ignore processing
$CurrentPerso->set_flag('site.requests', 0);
//We don't die, so next controller takes relay
} else {
///
/// HTML output
///
//Serves header
define('DOJO', true);
$smarty->assign('PAGE_TITLE', lang_get('PersoRequests'));
include('header.php');
//Serves content
$smarty->assign('requests', $requests);
$smarty->display('persorequests.tpl');
//Serves footer
$smarty->assign("screen", "Perso requests");
include('footer.php');
//Dies
exit;
}
diff --git a/controllers/profile.php b/controllers/profile.php
index 6dd1e7a..d0826db 100644
--- a/controllers/profile.php
+++ b/controllers/profile.php
@@ -1,344 +1,344 @@
<?php
/**
* User profile
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* This is a controller allowing user profile view and edit.
*
* It handles the following URLs:
* /who/<perso nickname> views the nickname's profile,
* /who/random views a random profile,
* /who/edit/profile edits its profile
* /who/edit/account edits its account (disabled on Zed, cf. settings),
* /who/edit/photo(s) manages its profile's photos,
* /who/edit/photo/edit/<photo id> edits a photo properties,
* /who/edit/photo/delete/<photo id> deletes a photo,
* /who/edit/photo/avatar/<photo id> promotes a photo to avatar.
*
* The following views are used:
* profile.tpl,
* profile_edit.tpl,
* user_account.tpl,
* profile_photo.tpl,
* profile_photo_edit.tpl.
*
* The following models are used:
* Profile,
* ProfilePhoto,
* ProfileComment.
*
* The view profile_tags.tpl is indirectly used by the Profile model.
*
* This code is maintained in // with Azhàr.
*
* @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
*/
//Loads language file
lang_load('profile.conf');
//Gets perso nickname from URL
$who = $url[1];
switch ($who) {
case 'edit':
$mode = 'edit';
$who = $CurrentPerso->nickname;
break;
case 'random':
$mode = 'view';
$who = $db->sql_query_express("SELECT perso_id FROM " . TABLE_PROFILES . " ORDER BY rand() LIMIT 1");
break;
default:
$mode = 'view';
}
if (!$who) {
message_die(GENERAL_ERROR, "Who?", "URL error");
}
//Libs
require_once('includes/objects/profile.php');
require_once('includes/objects/profilecomment.php');
require_once('includes/objects/profilephoto.php');
//Gets perso information
require_once('includes/objects/perso.php');
$perso = Perso::get($who);
if ($perso->lastError) {
message_die(GENERAL_ERROR, $perso->lastError, "Error");
}
$smarty->assign('perso', $perso);
//Gets profile
$profile = new Profile($perso->id);
//Handles form
if ($_POST['EditProfile']) {
$profile->load_from_form();
$profile->updated = time();
$profile->save_to_database();
$mode = 'view';
} elseif ($_POST['UserAccount']) {
$smarty->assign('WAP', "This form have been deprecated. You can write instead settings in the SmartLine");
} elseif ($_POST['message_type'] == 'private_message') {
//Sends a message
require_once('includes/objects/message.php');
$msg = new Message();
$msg->from = $CurrentPerso->id;
$msg->to = $perso->id;
$msg->text = $_POST['message'];
$msg->send();
if ($msg->from == $msg->to) {
$smarty->assign('NOTIFY', lang_get('MessageSentSelf'));
} else {
$smarty->assign('NOTIFY', lang_get('MessageSent'));
}
} elseif ($_POST['message_type'] == 'profile_comment') {
//New profile comment
$comment = new ProfileComment();
$comment->author = $CurrentPerso->id;
$comment->perso_id = $perso->id;
$comment->text = $_POST['message'];
$comment->publish();
$smarty->assign('NOTIFY', lang_get('CommentPublished'));
} elseif ($_FILES['photo']) {
#We've a file !
$hash = md5(microtime() . serialize($_FILES));
$extension = get_extension($_FILES['photo']['name']);
$filename = $CurrentPerso->id . '_' . $hash . '.' . $extension;
#We ignore $_FILES[photo][error] 4, this means no file has been uploaded
#(so user doesn't want upload a new file)
#See http:/www.php.net/features.file-upload and http://www.php.net/manual/en/features.file-upload.errors.php about common errors
#Not valid before PHP 4.2.0
switch ($_FILES['photo']['error']) {
case 0:
#There is no error, the file uploaded with success.
if (!move_uploaded_file($_FILES['photo']['tmp_name'], PHOTOS_DIR . '/' . $filename)) {
$errors[] = "Upload successful, but error saving it.";
} else {
//Attaches the picture to the profile
$photo = new ProfilePhoto();
$photo->name = $filename;
$photo->perso_id = $CurrentPerso->id;
$photo->description = $_POST['description'];
if ($photo->avatar) $photo->promote_to_avatar();
$photo->save_to_database();
//Generates thumbnail
if (!$photo->generate_thumbnail()) {
$smarty->assign('WAP', "Error generating thumbnail.");
}
$smarty->assign('NOTIFY', lang_get('PhotoUploaded'));
$mode = 'view';
}
break;
case 1:
$errors[] = "The file is too large.";
break;
#TODO : more explicit error messages
default:
$errors[] = "Unknown error (#" . $_FILES['photo']['error'] . ")";
break;
}
if (count($errors)) {
$smarty->assign('WAP', join($errors, '<br />'));
}
} elseif ($_POST['id']) {
//Edits photo properties
$photo = new ProfilePhoto($_POST['id']);
if ($photo->lastError) {
$smarty->assign('WAP', $photo->lastError);
$mode = 'view';
} elseif ($photo->perso_id != $CurrentPerso->id) {
$smarty->assign('WAP', lang_get('NotYourPic'));
$mode = 'view';
} else {
//OK
$wereAvatar = $photo->avatar;
$photo->load_from_form();
if (!$wereAvatar && $photo->avatar) {
//Promote to avatar
$photo->promote_to_avatar();
}
$photo->save_to_database();
}
}
//Prepares output
if ($profile->text) {
//Profile
$smarty->assign('PROFILE_TEXT', $profile->text);
$smarty->assign('PROFILE_FIXEDWIDTH', $profile->fixedwidth);
}
if ($mode == 'view') {
require_once('includes/objects/profilephoto.php');
//Self profile?
$self = $CurrentPerso->id == $profile->perso_id;
//Gets profiles comments, photos, tags
$comments = ProfileComment::get_comments($profile->perso_id);
$photos = ProfilePhoto::get_photos($profile->perso_id);
$tags = $profile->get_cached_tags();
//Records timestamp, to be able to track new comments
if ($self) $CurrentPerso->set_flag('profile.lastvisit', time());
//Template
$smarty->assign('PROFILE_COMMENTS', $comments);
$smarty->assign('PROFILE_SELF', $self);
if ($tags) $smarty->assign('PROFILE_TAGS', $tags);
$smarty->assign('USERNAME', $perso->username);
$smarty->assign('NAME', $perso->name ? $perso->name : $perso->nickname);
$template = 'profile.tpl';
} elseif ($mode == 'edit') {
switch ($url[2]) {
case 'profile':
$smarty->assign('USERNAME', $perso->name);
$smarty->assign('DIJIT', true);
$css[] = THEME . '/forms.css';
$template = 'profile_edit.tpl';
break;
case 'account':
$smarty->assign('user', $CurrentUser);
$smarty->assign('DIJIT', true);
$css[] = THEME . '/forms.css';
$template = 'user_account.tpl';
break;
case '':
$smarty->assign('NOTIFY', "What do you want to edit ? Append /profile, /account or /photos to the URL");
break;
case 'photo':
case 'photos':
$smarty->assign('USERNAME', $perso->name);
switch ($action = $url[3]) {
case '':
//Nothing to do
break;
case 'delete':
//Deletes a picture
if (!$id = $url[4]) {
$smarty->assign('WAP', "URL error. Parameter missing: picture id.");
} else {
$photo = new ProfilePhoto($id);
if ($photo->lastError) {
//Probably an non existent id (e.g. double F5, photo already deleted)
$smarty->assign('WAP', $photo->lastError);
} elseif ($photo->perso_id != $CurrentPerso->id) {
$smarty->assign('WAP', lang_get('NotYourPic'));
} else {
//OK we can delete it
$photo->delete();
$smarty->assign('NOTIFY', lang_get('PictureDeleted'));
}
}
break;
case 'edit':
if (!$id = $url[4]) {
$smarty->assign('WAP', "URL error. Parameter missing: picture id.");
} else {
$photo = new ProfilePhoto($id);
if ($photo->lastError) {
//Probably an non existent id (e.g. double F5, photo already deleted)
$smarty->assign('WAP', $photo->lastError);
} elseif ($photo->perso_id != $CurrentPerso->id) {
$smarty->assign('WAP', lang_get('NotYourPic'));
} else {
//Photo information edit form
$smarty->assign('photo', $photo);
$template = 'profile_photo_edit.tpl';
}
}
break;
case 'avatar':
//Promotes a picture to avatar
if (!$id = $url[4]) {
$smarty->assign('WAP', "URL error. Parameter missing: picture id.");
} else {
$photo = new ProfilePhoto($id);
if ($photo->lastError) {
$smarty->assign('WAP', $photo->lastError);
} elseif ($photo->perso_id != $CurrentPerso->id) {
$smarty->assign('WAP', lang_get('NotYourPic'));
} else {
//OK, promote it to avatar
$photo->promote_to_avatar();
$photo->save_to_database();
$smarty->assign('NOTIFY', lang_get('PromotedToAvatar'));
}
}
break;
default:
$smarty->assign('WAP', "Unknown URL. To delete a picture it's /delete/<picture id>. To edit it /edit/<picture id>");
break;
}
if (!$template) {
$photos = ProfilePhoto::get_photos($profile->perso_id);
if (!$smarty->tpl_vars['NOTIFY'])
$smarty->assign('NOTIFY', "Your feedback is valued. Report any bug or suggestion on the graffiti wall.");
$template = 'profile_photo.tpl';
}
break;
default:
$smarty->assign('WAP', "URL error. You can use /edit with profile, account or photos.");
break;
}
}
//
// HTML output
//
//Photos
if (count($photos) || $photo) {
$smarty->assign('URL_PICS', PHOTOS_URL);
$css[] = 'lightbox.css';
- $smarty->assign('PAGE_JS', array('prototype.js', 'effects.js', 'lightbox.js'));
+ $smarty->assign('PAGE_JS', ['prototype.js', 'effects.js', 'lightbox.js']);
$smarty->assign('PICS', $photos);
}
//Serves header
$css[] = THEME . "/profile.css";
$smarty->assign('PAGE_CSS', $css);
$smarty->assign('PAGE_TITLE', $perso->name);
include('header.php');
//Serves content
if ($template) $smarty->display($template);
//Serves footer
include('footer.php');
diff --git a/controllers/settings.php b/controllers/settings.php
index 536117c..89141d2 100644
--- a/controllers/settings.php
+++ b/controllers/settings.php
@@ -1,95 +1,95 @@
<?php
/**
* Settings
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* This controller allows user to set its preferences, according the Settings
* classes and the preferences.xml document.
*
* It handles the /settings URL.
*
* @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
*
* @todo replace the on the fly preferences.xml code generation by a cached code generation
* @todo reduce the number of for loops in this controller
*/
//
// Loads settings
//
lang_load('settings.conf');
include('includes/settings/settings.php');
$settings = new Settings('includes/settings/preferences.xml');
//Selects relevant settings page
$pages = $settings->pages;
if (count($url) > 1) {
//From url: /settings/account -> page account
if (array_key_exists($url[1], $settings->pages)) {
$page = $pages[$url[1]];
} else {
message_die(GENERAL_ERROR, "/settings/$url[1] isn't a valid setting page");
}
} else {
//Default page
$page = array_shift($pages);
}
//Pages links
foreach ($settings->pages as $tmppage) {
$pagesLinks[$tmppage->id] = $tmppage->title;
}
//
// Handles form
//
if (array_key_exists('settings_page', $_POST)) {
if ($_POST['settings_page'] == $page->id) {
//Updates settings
- $errors = array();
+ $errors = [];
$page->handle_form($errors);
if (count($errors)) {
//Prints error message
$smarty->assign('WAP', implode('<br />', $errors));
}
} else {
//The field settings.page isn't the current page
//Prints an HACK_ERROR to avoid to save properties with the same names.
$id_current = $page->id;
$id_toSave = $_POST['settings_page'];
message_die(HACK_ERROR, "You're on /settings/$id_current but you want to update /settings/$id_toSave");
}
}
//
// HTML output
//
//Serves header
define('DIJIT', true);
$title = lang_get('Settings');
$smarty->assign('PAGE_TITLE', $title);
include('header.php');
//Serves settings page;
$smarty->assign('page', $page);
$smarty->assign('pages', $pagesLinks);
$smarty->display('settings_page.tpl');
//Servers footer
include('footer.php');
diff --git a/do.php b/do.php
index 0d4d82f..c76cbbb 100644
--- a/do.php
+++ b/do.php
@@ -1,474 +1,474 @@
<?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
///
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
//Gets current perso
require_once('includes/objects/perso.php');
$CurrentUser = get_logged_user(); //Gets current user infos
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 print 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 whether 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 move 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
$location_local = urldecode($location_local);
$CurrentPerso->move_to(null, $location_local);
//Returns GeoLocation relevant instance
return $CurrentPerso->location;
}
/**
* Moves the current perso's, setting a new local location.
*
* We don't require a security hash. If the users want to play with it, no problem.
* You generally move inside a global location as you wish.
* So, if you write a story capturing a perso, use flags to handle this escape!
*
* @param string $move the move (coordinates or direction)
* @param int $factor a number multiplying the specified move [optional]
* @return GeoLocation the current perso's GeoLocation object
*
* e.g. to move from 2 units to east, you can use one of those instructions:
* local_move('east', 2);
* local_move('2,0,0');
* local_move('1,0,0', 2);
*
* Valid moves string are north, east, south, west, up and down.
* Valid moves coordinates are x,y,z (3 integers, comma as separator)
*/
static function local_move ($move, $factor = 1)
{
global $CurrentPerso;
//Ensures we've the correct amount of arguments
if (func_num_args() < 1) {
return null;
}
//Parses $move
switch ($move) {
case 'north':
- $move = array(0, 1, 0);
+ $move = [0, 1, 0];
break;
case 'east':
- $move = array(1, 0, 0);
+ $move = [1, 0, 0];
break;
case 'south':
- $move = array(0, -1, 0);
+ $move = [0, -1, 0];
break;
case 'west':
- $move = array(-1, 0, 0);
+ $move = [-1, 0, 0];
break;
case 'up':
- $move = array(0, 0, 1);
+ $move = [0, 0, 1];
break;
case 'down':
- $move = array(0, 0, -1);
+ $move = [0, 0, -1];
break;
default:
$move = split(',', $move, 3);
foreach ($move as $coordinate) {
if (!is_numeric($coordinate)) {
return null;
}
}
}
//Moves current perso to specified location
if ($location_local = GeoPoint3D::fromString($CurrentPerso->location->local)) {
$location_local->translate($move[0] * $factor, $move[1] * $factor, $move[2] * $factor);
$CurrentPerso->move_to(null, $location_local->sprintf("(%d, %d, %d)"));
//Returns GeoLocation relevant instance
return $CurrentPerso->location;
}
//Old local location weren't a GeoPoint3D
return null;
}
/**
* Moves the current perso's, setting a new local location, using polar+z coordinates.
* Polar+z coordinates are polar coordinates, plus a cartesian z dimension.
*
* We don't require a security hash. If the users want to play with it, no problem.
* You generally move inside a global location as you wish.
* So, if you write a story capturing a perso, use flags to handle this escape!
*
* @param string $move the move (coordinates or direction)
* @param int $factor a number multiplying the specified move [optional]
* @return GeoLocation the current perso's GeoLocation object
*
* Valid moves string are cw, ccw, out, in, up and down.
* r: out = +12 in = -12
* °: cw = +20° ccw = -20
* Valid moves coordinates are r,°,z (3 integers, comma as separator)
* (the medium value can also be integer + °)
*
* e.g. to move of two units (the unit is 20°) clockwise:
* polarz_local_move('cw', 2);
* polarz_local_move('(0, 20°, 0)', 2);
* polarz_local_move('(0, 40°, 0)');
* Or if you really want to use radians (PI/9 won't be parsed):
* polarz_local_move('(0, 0.6981317007977318, 0)';
*
*/
static function polarz_local_move ($move, $factor = 1) {
global $CurrentPerso;
//Ensures we've the correct amount of arguments
if (func_num_args() < 1) {
return null;
}
//Parses $move
$move = urldecode($move);
switch ($move) {
case 'cw':
- $move = array(0, '20°', 0);
+ $move = [0, '20°', 0];
break;
case 'ccw':
- $move = array(0, '-20°', 0);
+ $move = [0, '-20°', 0];
break;
case 'in':
- $move = array(+12, 0, 0);
+ $move = [+12, 0, 0];
break;
case 'out':
- $move = array(-12, 0, 0);
+ $move = [-12, 0, 0];
break;
case 'up':
- $move = array(0, 0, 1);
+ $move = [0, 0, 1];
break;
case 'down':
- $move = array(0, 0, -1);
+ $move = [0, 0, -1];
break;
default:
$move = split(',', $move, 3);
foreach ($move as $coordinate) {
if (!is_numeric($coordinate) && !preg_match("/^[0-9]+ *°$/", $coordinate)) {
return null;
}
}
}
dieprint_r($move);
//Moves current perso to specified location
if ($location_local = GeoPoint3D::fromString($CurrentPerso->location->local)) {
$location_local->translate($move[0] * $factor, $move[1] * $factor, $move[2] * $factor);
$CurrentPerso->move_to(null, $location_local->sprintf("(%d, %d, %d)"));
//Returns GeoLocation relevant instance
return $CurrentPerso->location;
}
//Old local location weren't a GeoPoint3D
return null;
}
/**
* Moves the current perso's, setting a new global and local location.
*
* @param string $location_global The global location
* @param string $location_local The local location
* @return GeoLocation the current perso's GeoLocation object
*/
static function global_move ($location_global, $location_local = null) {
//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;
}
//Moves
global $CurrentPerso;
$CurrentPerso->move_to($location_global, $location_local);
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();
$content->load_from_form();
$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
///
//Parses URL
$Config['SiteURL'] = get_server_url() . $_SERVER["PHP_SELF"];
$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);
+ $result = call_user_func_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);
+ $result = @call_user_func_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);
}
}
}
diff --git a/includes/SmartLine/SmartLine.php b/includes/SmartLine/SmartLine.php
index daa2b8f..df86aba 100755
--- a/includes/SmartLine/SmartLine.php
+++ b/includes/SmartLine/SmartLine.php
@@ -1,537 +1,537 @@
<?php
/**
* SmartLine 0.1
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2007-07-28 01:36 [DcK] Initial release
* 2010-07-02 00:39 [Dck] Documentation
*
* @package Zed
* @subpackage SmartLine
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @copyright 2007 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/
* @link http://bitbucket.org/dereckson/smartline
* @filesource
///////////////////////////////////////////////////////////////////////////////
// SECTION I - INITIALIZATION
///////////////////////////////////////////////////////////////////////////////
//Constants
/**
* The standard, regular output (like STDOUT on POSIX systems)
*/
if (!defined('STDOUT')) {
define('STDOUT', 1, true);
}
/**
* The error output (like STDERR on POSIX systems)
*/
if (!defined('STDERR')) {
define('STDERR', -1, true);
}
///////////////////////////////////////////////////////////////////////////////
// SECTION Ibis - L10n
///////////////////////////////////////////////////////////////////////////////
//Ensures $lang is a standard array
if (empty($lang) || !is_array($lang)) {
- $lang = array();
+ $lang = [];
}
-$lang = array_merge($lang, array(
+$lang = array_merge($lang, [
//Errors
'InvalidCommand' => "Invalid command %s. Use <strong>showcommands</strong> to show all commands.",
'RegisteredButNotExistingCommand' => "[CRITICAL ERROR] The command %s has correctly been registered but its method or class doesn't exist.",
'NotYetHelpForThiscommand' => "This command hasn't been documented yet.",
//Help
'DefaultHelp' => "This SmartLine is a command line interface.
<br /><br /><strong>showcommands</strong> prints the list.
<br /><strong>help &lt;command&gt;</strong> prints help for this command.",
- 'Help' => array(
+ 'Help' => [
'help' => "<strong>help &lt;command&gt;</strong> prints command help.",
'showcommands' => 'show available commands'
- )
-));
+ ]
+]);
///////////////////////////////////////////////////////////////////////////////
// SECTION II - HELPERS FUNCTIONS
///////////////////////////////////////////////////////////////////////////////
/**
* Error handler called during SmartLine command execution.
*
* Any error occurring during command execution will be set in STDERR.
*
* To get an array with all the errors:
* <code>$errors = $yourSmartLine->gets_all(STDERR)</code>
*
* Or to prints all the error:
* <code>$yourSmartLine->prints_all(STDERR)</code>
*
* Or to pops (gets and deletes) only the last error:
* <code>$lastError = $yourSmartLine->gets(STDERR)</code>
*
* @link http://www.php.net/manual/en/function.set-error-handler.php set_error_handler, PHP manual
* @link http://www.php.net/manual/en/errorfunc.examples.php Error handling examples, PHP manual
*
* @param int $level The PHP error level
* @param string $error The error description
* @param string $file The script where the error occurred
* @param int $line The line where the error occurred
*/
function SmartLineHandler($level, $error, $file, $line) {
switch ($level) {
case E_NOTICE:
$type = 'Notice';
break;
CASE E_WARNING:
$type = 'Warning';
break;
CASE E_ERROR:
$type = 'Error';
break;
default:
$type = "#$level";
}
$_SESSION['SmartLineOutput'][STDERR][] = "[PHP $type] $error in $file line $line.";
return true;
}
///////////////////////////////////////////////////////////////////////////////
// SECTION III - BASE CLASSES
///////////////////////////////////////////////////////////////////////////////
//SmartLineCommand is a class implementing a SmartLine command.
//If you want to create a more complex command, extends this class.
/**
* The SmartLine command base class.
*
* To add a command, create an instance of the class, like:
* <code>
* class HelloWorldSmartLineCommand extends SmartLineCommand {
* public function run ($argv, $argc) {
* $this->SmartLine->puts('Hello World!');
* }
* }
* </code>
*
* Then, registers your command:
* <code>
* $yourSmartLine->register_object('hello', 'HelloWorldSmartLineCommand');
* </code>
*
* @see SmartLine::register_object
*/
class SmartLineCommand {
/**
* Initializes a new instance of the SmartLine Command
*
* @param SmartLine $SmartLine the SmartLine the command belongs
*/
public function __construct ($SmartLine) {
$this->SmartLine = $SmartLine;
}
/**
* Gets the command help text or indicates help should be fetched from $lang array
*
* @return string|bool a string containing the command help or the bool value false, to enable the default behavior (ie prints $lang['help']['nameOfTheCommand'])
*/
public function help () {
return false;
}
/**
* Runs the command
*
* @param array $argv an array of string, each item a command argument
* @param int $argc the number of arguments
*/
public function run ($argv, $argc) {
}
/**
* The SmartLine where this instance of the command is registered
*
* @var SmartLine
*/
public $SmartLine;
}
/**
* This class represents a SmartLine instance
*
* If you use only register_object, you can use it directly.
* If you use register_method, extends this class in your SmartLine.
*/
class SmartLine {
/**
* Initializes a new instance of the SmartLine object.
*/
public function __construct () {
//Assumes we've an empty array where store registered commands.
- $this->commands = array();
+ $this->commands = [];
//Let's register standard commands
$this->register_object('showcommands', 'ShowCommandsSmartLineCommand');
$this->register_object('help', 'HelpSmartLineCommand');
}
/**
* Registers a private method as command.
*
* @param string $command The name of the command to register
* @param string $method The method to register [OPTIONAL]. If omitted, the method registered will be the method having the same name as the command.
* @param bool $useArgvArgc If true, indicates the method uses $argv, $argc as parameters. If false, indicates the method uses its parameters (default behavior). [OPTIONAL]
*
* @return bool true if the command have successfully been registered ; otherwise, false.
*/
public function register_method ($command, $method = null, $useArgvArgc = false) {
if (is_null($function)) $method = $command;
if (!method_exists($this, $method)) {
$this->lastError = "Registration failed. Unknown method $method";
return false;
}
$className = ucfirst($method) . 'SmartLineCommand';
//If class exists, add a uniqid after function
while (class_exists($method)) {
$className = uniqid(ucfirst($method)) . 'SmartLineCommand';
}
//Creates the class
if ($useArgvArgc) {
$call = "$this->SmartLine->$method(\$argv, \$argc);";
} else {
//We don't know how many args we've, so we use call_user_func_array
$call = "array_shift(\$argv);
call_user_func_array(
array(&\$this->SmartLine, '$method'),
\$argv
);";
}
$code = "class $className extends SmartLineCommand {
public function run (\$argv, \$argc) {
$call
}
}";
eval($code);
$this->register_object($command, $className);
return true;
}
/**
* Registers an object extending SmartLineCommand as command.
*
* @param string $command The name of the command to register
* @param SmartLineCommand|string $object The object extending SmartLineCommand. This can be the name of the class (string) or an instance already initialized of the object (SmartLineCommand).
* @return bool true if the command have successfully been registered ; otherwise, false.
*/
public function register_object ($command, $object) {
if (is_object($object)) {
//Sets SmartLine property
$object->SmartLine = $this;
} elseif (is_string($object) && class_exists($object)) {
//Creates a new instance of $object
$object = new $object($this);
} else {
$this->lastError = "Registration failed. register_object second parameter must be a class name (string) or an already initialized instance of such class (object) and not a " . gettype($object);
return false;
}
if (!$this->caseSensitive) {
$command = strtolower($command);
}
$this->commands[$command] = $object;
return true;
}
/**
* Determines whether the specified command have been registered.
*
* @param string $command The name of the command to check
* @return true if the specified command have been registered ; otherwise, false.
*/
public function isRegistered ($command) {
if (!$this->caseSensitive) {
$command = strtolower($command);
}
return array_key_exists($command, $this->commands);
}
/**
* Executes the specified expression.
*
* If an error occurs during the command execution:
* the STDERR output will contains the errors,
* the value returned by this methods will be false.
*
* To execute the command and prints error:
* <code>
* $fooSmartLine = new SmartLine();
* //...
* $result = $fooSmartLine->execute($expression);
* $fooSmartLine->prints_all();
* if (!$result) {
* //Errors!
* echo "<h3>Errors</h3>";
* $fooSmartLine->prints_all(STDERR);
* }
* </code>
*
* @param string $expression The expression containing the command to execute
* @return bool true if the command have been successfully executed ; otherwise, false.
*/
public function execute ($expression) {
//Does nothing if blank line
if (!$expression) return;
//Prepares $argv and $argc
$argv = $this->expression2argv($expression);
$argc = count($argv);
//Gets command
$command = $this->caseSensitive ? $argv[0] : strtolower($argv[0]);
//If command doesn't exist, throws an error
if (!array_key_exists($command, $this->commands)) {
global $lang;
$this->puts(sprintf($lang['InvalidCommand'], $command), STDERR);
return false;
}
//Executes command, intercepting error and returns result
set_error_handler("SmartLineHandler");
try {
$result = $this->commands[$command]->run($argv, $argc);
} catch (Exception $ex) {
$this->puts("<pre>$ex</pre>", STDERR);
}
restore_error_handler();
return $result;
}
/**
* Adds a message to the specified output queue.
*
* @param string $message the message to queue
* @param int $output The output queue (common values are STDERR and STDOUT constants). It's an optional parameter ; if omitted, the default value will be STDOUT.
*/
public function puts ($message, $output = STDOUT) {
//
$_SESSION['SmartLineOutput'][$output][] = $message;
}
/**
* Truncates the specified output queue.
*
* @param int $output The output queue (common values are STDERR and STDOUT constants). It's an optional parameter ; if omitted, the default value will be STDOUT.
*/
public function truncate ($output = STDOUT) {
unset($_SESSION['SmartLineOutput'][$output]);
}
/**
* Pops (gets and clears) the first message from the specified output queue.
*
* @param int $output The output queue (common values are STDERR and STDOUT constants). It's an optional parameter ; if omitted, the default value will be STDOUT.
* @return string the message
*/
public function gets ($output = STDOUT) {
if (count($_SESSION['SmartLineOutput'][$output] > 0)) {
return array_pop($_SESSION['SmartLineOutput'][$output]);
}
}
/**
* Gets the number of messages in the specified output queue.
*
* @param int $output The output queue (common values are STDERR and STDOUT constants). It's an optional parameter ; if omitted, the default value will be STDOUT.
*/
public function count ($output = STDOUT) {
return count($_SESSION['SmartLineOutput'][$output]);
}
/**
* Gets all the message from the specified output queue.
*
* @param int $output The output queue (common values are STDERR and STDOUT constants). It's an optional parameter ; if omitted, the default value will be STDOUT.
* @param string $prefix The string to prepend each message with. It's an optional parameter ; if omitted, '<p>'.
* @param string $suffix The string to append each message with. It's an optional parameter ; if omitted, '</p>'.
* @return Array an array of string, each item a message from the specified output queue
*/
public function gets_all ($output = STDOUT, $prefix = '<p>', $suffix = '</p>') {
$count = count($_SESSION['SmartLineOutput'][$output]);
if ($count == 0) {
return;
}
for ($i = 0 ; $i < $count ; $i++) {
$buffer .= $prefix . $_SESSION['SmartLineOutput'][$output][$i] . $suffix;
}
unset ($_SESSION['SmartLineOutput'][$output]);
return $buffer;
}
/**
* Prints all the message from the specified output queue.
*
* @param int $output The output queue (common values are STDERR and STDOUT constants). It's an optional parameter ; if omitted, the default value will be STDOUT.
* @param string $prefix The string to prepend each message with. It's an optional parameter ; if omitted, '<p>'.
* @param string $suffix The string to append each message with. It's an optional parameter ; if omitted, '</p>'.
*/
public function prints_all ($output = STDOUT, $prefix = '<p>', $suffix = '</p>') {
$count = count($_SESSION['SmartLineOutput'][$output]);
if ($count == 0) {
return;
}
for ($i = 0 ; $i < $count ; $i++) {
echo $prefix, $_SESSION['SmartLineOutput'][$output][$i], $suffix;
}
unset ($_SESSION['SmartLineOutput'][$output]);
}
/**
* Gets the command help
*
* @param string $command The command to get help from
* @param string The command help
*/
public function gethelp ($command) {
return $this->commands[$command]->help();
}
/**
* Gets an an argv array from the specified expression
*
* @param string $expression The expression to transform into a argv array
* @return Array An array of string, the first item the command, the others those arguments.
*/
private function expression2argv ($expression) {
//Checks if expression contains "
$pos1 = strpos($expression, '"');
//We isolate "subexpression"
if ($pos1 !== false) {
$pos2 = $pos1;
do {
$pos2 = strpos($expression, '"', $pos2 + 1);
} while ($pos2 !== false && ($expression[$pos2 - 1] == "\\" && $expression[$pos2 - 2] != "\\"));
if ($pos2 === false) {
//If final quote is missing, throws a warning and autoadds it.
$this->puts("[Warning] Final \" missing in $expression.", STDERR);
$argv = $this->expression2argv(substr($expression, 0, $pos1));
$argv[] = substr($expression, $pos1 + 1);
return $argv;
}
return array_merge(
$this->expression2argv(substr($expression, 0, $pos1)),
- array(substr($expression, $pos1 + 1, $pos2 - $pos1 - 1)),
+ [substr($expression, $pos1 + 1, $pos2 - $pos1 - 1)],
$this->expression2argv(substr($expression, $pos2 + 1))
);
}
//Standard expression (ie without ")
- $argv = array();
+ $argv = [];
$items = explode(' ', $expression);
foreach ($items as $item) {
$item = trim($item);
if (!$item) {
//blank, we ignore
continue;
}
$argv[] = $item;
}
return $argv;
}
//Contains last error
public $lastError = '';
//If true, command isn't equal to Command
public $caseSensitive = true;
}
///////////////////////////////////////////////////////////////////////////////
// SECTION IV - STANDARD COMMANDS
///////////////////////////////////////////////////////////////////////////////
/*
* These commands are available in all default smartlines instance
*/
/**
* The standard command "showcommands"
*
* This command returns a list, with all the available commands
*/
class ShowCommandsSmartLineCommand extends SmartLineCommand {
/**
* Runs the command
*
* @param array $argv an array of string, each item a command argument
* @param int $argc the number of arguments
*/
public function run ($argv, $argc) {
$commands = array_keys($this->SmartLine->commands);
sort($commands);
$this->SmartLine->puts(implode(' ', $commands));
}
}
/**
* The standard command "help"
*
* This command prints command help.
*
* Help could be defined
* in the command classes, as a return value from the help method ;
* in the $lang['Help'] array, at the command key (e.g. $lang['Help']['quux'] for the quux command).
*/
class HelpSmartLineCommand extends SmartLineCommand {
/**
* Runs the command
*
* @param array $argv an array of string, each item a command argument
* @param int $argc the number of arguments
*/
public function run ($argv, $argc) {
global $lang;
if ($argc == 1) {
$this->SmartLine->puts($lang['DefaultHelp']);
} elseif (!$this->SmartLine->isRegistered($argv[1])) {
$this->SmartLine->puts(sprintf($lang['InvalidCommand'], str_replace(' ', '&nbsp;', $argv[1])), STDERR);
} else {
$command = strtolower($argv[1]);
if (!$help = $this->SmartLine->gethelp($command)) {
if (array_key_exists($command, $lang['Help'])) {
$help = $lang['Help'][$command];
} else {
$help = $lang['NotYetHelpForThiscommand'];
}
}
$this->SmartLine->puts($help);
}
}
}
///////////////////////////////////////////////////////////////////////////////
diff --git a/includes/api/BeautyXML.class.php b/includes/api/BeautyXML.class.php
index 4b57d83..98c7842 100755
--- a/includes/api/BeautyXML.class.php
+++ b/includes/api/BeautyXML.class.php
@@ -1,161 +1,161 @@
<?php
/**
* XML beautifier
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* This class is simple XML beautifier
* it's very, very, very simple - feature version will be better :-)
*
* IMPORTANT NOTE
* there is no warranty, implied or otherwise with this software.
*
* version 0.1 | August 2004
*
* released under a LGPL licence.
*
* Slawomir Jasinski,
* http://www.jasinski.us (polish only - my home page)
* http://www.cgi.csd.pl (english & polish)
* contact me - sj@gex.pl
*
* @package Zed
* @subpackage API
* @author Slawomir Jasinski <sj@gex.pl>
* @copyright 2004 Slawomir Jasinski, 2010 Sébastien Santoro aka Dereckson
* @license http://www.gnu.org/licenses/lgpl.html LGPL
* @version 0.1
* @link http://scherzo.dereckson.be/doc/zed
* @link http://zed.dereckson.be/
* @filesource
*
* @todo Contact Slawomir Jasinski and ask it if the current code could be
* relicensed under BSD license. If not, rewrite from scratch under BSD license.
*/
/**
* This class is simple XML beautifier.
* It's very, very, very simple - feature version will be better :-)
*
* @author Slawomir Jasinski <sj@gex.pl>
*/
class BeautyXML {
/**
* Indicates what characters to use to indent.
*
* If you wish a regular tabulation, the suggested value is \t ;
* If you wish spaces instead, put the correct amount of spaces as value.
*
* @var string
*/
var $how_to_indent = " "; // you can user also \t or more/less spaces
/**
* Determines if long text have to be wrapped.
*
* If true, the text will be wrapped ; otherwise, long lines will be kept.
*
* @var bool
*/
var $wrap = false;
/**
* If $wrap is true, determines the line length.
*
* After this length, any text will be wrapped.
*
* @see $wrap
* @var @int
*/
var $wrap_cont = 80; // where wrap words
/**
* Indents the specified string.
*
* @param string $str the string to indent
* @param int $level the indent level, ie the number of indentation to prepend the string with
*/
function indent (&$str, $level) {
$spaces = '';
$level--;
for ($a = 0; $a < $level; $a++) {
$spaces .= $this->how_to_indent;
}
return $spaces .= $str;
}
/**
* Formats the specified string, beautifying it, with proper indent.
*
* This is the main class method.
*
* @param $str the XML fragment to beautify
* @return string the beautified XML fragment
*/
function format ($str) {
$str = preg_replace("/<\?[^>]+>/", "", $str);
$tmp = explode("\n", $str); // extracting string into array
// cleaning string from spaces and other stuff like \n \r \t
for ($a = 0, $c = count($tmp); $a < $c; $a++) {
$tmp[$a] = trim($tmp[$a]);
}
// joining to string ;-)
$newstr = join("", $tmp);
$newstr = preg_replace("/>([\s]+)<\//", "></", $newstr);
// adding \n lines where tags ar near
$newstr = str_replace("><", ">\n<", $newstr);
// exploding - each line is one XML tag
$tmp = explode("\n", $newstr);
// preparing array for list of tags
- $stab = array('');
+ $stab = [''];
// lets go :-)
for ($a = 0, $c = count($tmp); $a <= $c; $a++) {
$add = true;
preg_match("/<([^\/\s>]+)/", $tmp[$a], $match);
$lan = trim(strtr($match[0], "<>", " "));
$level = count($stab);
if (in_array($lan, $stab) && substr_count($tmp[$a], "</$lan") == 1) {
$level--;
$s = array_pop($stab);
$add = false;
}
if (substr_count($tmp[$a], "<$lan") == 1 && substr_count($tmp[$a], "</$lan") == 1) {
$add = false;
}
if (preg_match("/\/>$/", $tmp[$a], $match)) {
$add = false;
}
$tmp[$a] = $this->indent($tmp[$a], $level);
if ($this->wrap) {
$tmp[$a] = wordwrap($tmp[$a], $this->wrap_cont, "\n" . $this->how_to_indent . $this->how_to_indent . $this->how_to_indent);
}
if ($add && !@in_array($lan, $stab) && $lan != '') {
array_push($stab, $lan);
}
}
return join("\n", $tmp);
}
}
diff --git a/includes/cache/cache.php b/includes/cache/cache.php
index ce4d391..46f59ef 100755
--- a/includes/cache/cache.php
+++ b/includes/cache/cache.php
@@ -1,89 +1,89 @@
<?php
/**
* Cache calling class.
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* This file provides a calling class, which read the configuration, ensures
* the cache class for the cache engine given in config exists and initializes
* it.
*
* You'll find a sample of implementation in the CacheMemcached.
* @see CacheMemcached
*
* If no caching mechanism, a "blackhole" void cache will be used.
* @see CacheVoid.
*
* The class to call is determined from the following preference:
* <code>
* $Config['cache']['engine'] = 'memcached'; //will use CacheMemcached class.
* </code>
*
* 0.1 2010-07-06 22:45 Initial version [DcK]
*
* @package Zed
* @subpackage Cache
* @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
*/
/**
* Cache caller
*/
class Cache {
/**
* Gets the cache instance, initializing it if needed
*
* The correct cache instance to initialize will be determined from the
* $Config['cache']['engine'] preference.
*
* The class cache to use will be Cache + (preference engine, capitalized)
*
* This method will creates an instance of the specified object,
* calling the load static method from this object class.
*
* Example:
* <code>
* $Config['cache']['engine'] = 'quux';
* $cache = Cache::load(); //Cache:load() will call CacheQuux:load();
* </code>
*
* @return Cache the cache instance, or null if nothing is cached
*/
static function load () {
global $Config;
if (
!array_key_exists('cache', $Config) ||
!array_key_exists('engine', $Config['cache'])
) {
//cache is not configured or engine is not specified
$engine = 'void';
} else {
//engine is specified in the configuration
$engine = $Config['cache']['engine'];
}
$engine_file = 'includes/cache/' . $engine . '.php';
$engine_class = 'Cache' . ucfirst($engine);
if (!file_exists($engine_file)) {
message_die(GENERAL_ERROR, "Can't initialize $engine cache engine.<br />$engine_file not found.", 'Cache');
}
require_once($engine_file);
if (!class_exists($engine_class)) {
message_die(GENERAL_ERROR, "Can't initialize $engine cache engine.<br />$engine_class class not found.", 'Cache');
}
- return call_user_func(array($engine_class, 'load'));
+ return call_user_func([$engine_class, 'load']);
}
}
diff --git a/includes/content/location.php b/includes/content/location.php
index dbd24ff..05ed461 100755
--- a/includes/content/location.php
+++ b/includes/content/location.php
@@ -1,228 +1,228 @@
<?php
/**
* Content location class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2010-12-03 2:58 Forked from Content class
*
* @package Zed
* @subpackage Content
* @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
*/
/**
* Content location class
*
* This class maps the content_locations table.
*
* A content location is defined by 3 parameters:
* - location_global
* - location_local
* - location_k, an index for the content at the specified location
*
* This class allows to get or set the content_id at this
* (global, local, k) location.
*
* This class also provides a static helper method to
* get local content from a specific location.
*/
class ContentLocation {
/* -------------------------------------------------------------
Properties
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
public $location_global = null;
public $location_local = null;
public $location_k = null;
public $content_id;
/* -------------------------------------------------------------
Constructor, __toString
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/**
* Initializes a new ContentLocation instance
*
* @param string $location_global the global location
* @param string $location_local the local location
* @param int $location_k the item indice for the specified location
*/
function __construct ($location_global = null, $location_local = null, $location_k = null) {
$this->location_global = $location_global;
$this->location_local = $location_local;
if ($location_k) {
$this->location_k = $location_k;
$this->load_from_database();
} else {
$this->location_k = self::get_free_location_k($location_global, $location_local);
}
}
/**
* Returns a string representation of current Content instance
*
* @return string the content title or path if title is blank.
*/
function __toString () {
$location_global = $this->location_global ? $this->location_global : '?';
$location_local = $this->location_local ? $this->location_local : '?';
$location_k = $this->location_k ? $this->location_k : '?';
return "($location_global, $location_local, $location_k)";
}
/* -------------------------------------------------------------
Load/save class
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/**
* Loads the object ContentLocation (ie fill the properties) from the database
*/
function load_from_database () {
global $db;
$location_global = "'" . $db->sql_escape($this->location_global) . "'";
$location_local = "'" . $db->sql_escape($this->location_local) . "'";
$location_k = "'" . $db->sql_escape($this->location_k) . "'";
$sql = "SELECT * FROM content_locations WHERE location_global = '$location_global' AND location_local = '$location_local' AND location_k = '$location_k'";
if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Unable to query content", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
$this->lastError = "Content location unknown: " . $this->content_id;
return false;
}
$this->load_from_row($row);
return true;
}
/**
* Loads the object from row
*/
function load_from_row ($row) {
$this->content_id = $row['content_id'];
$this->location_global = $row['location_global'];
$this->location_local = $row['location_local'];
$this->location_k = $row['location_k'];
}
/**
* Saves to database
*/
function save_to_database () {
global $db;
$location_global = "'" . $db->sql_escape($this->location_global) . "'";
$location_local = "'" . $db->sql_escape($this->location_local) . "'";
$location_k = "'" . $db->sql_escape($this->location_k) . "'";
$content_id = $this->content_id ? "'" . $db->sql_escape($this->content_id) . "'" : 'NULL';
$sql = "REPLACE INTO content_locations (location_global, location_local, location_k, content_id) VALUES ($location_global, $location_local, $location_k, $content_id)";
if (!$db->sql_query($sql))
message_die(SQL_ERROR, "Can't save content location", '', __LINE__, __FILE__, $sql);
}
/* -------------------------------------------------------------
Helper methods
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/**
* Gets the next k free value for the specified location
*
* @param string $location_global the global location
* @param string $location_local the local location
*
* @param int $location_k the next free local content indice
*/
function get_free_location_k ($location_global, $location_local) {
$location_global = "'" . $db->sql_escape($location_global) . "'";
$location_local = "'" . $db->sql_escape($location_local) . "'";
$sql = "SELECT MAX(location_k) + 1 FROM content_locations WHERE location_global = '$location_global' AND location_local = '$location_local'";
if (!$result = $db->sql_query($sql))
message_die(SQL_ERROR, "Can't get content location k", '', __LINE__, __FILE__, $sql);
$row = $db->sql_fetchrow($result);
return $row[0];
}
/**
* Deletes this content location from the database
*/
function delete() {
$location_global = "'" . $db->sql_escape($this->location_global) . "'";
$location_local = "'" . $db->sql_escape($this->location_local) . "'";
$location_k = "'" . $db->sql_escape($this->location_k) . "'";
$sql = "DELETE FROM content_locations WHERE location_global = '$location_global' AND location_local = '$location_local' AND location_k = '$location_k' LIMIT 1";
if (!$db->sql_query($sql))
message_die(SQL_ERROR, "Can't delete current content location", '', __LINE__, __FILE__, $sql);
}
/**
* Moves the content into new location
*
* @param string $location_global the target global location
* @param string $location_local the target local location
* @param int $location_k the target local content indice [facultative]
*/
function move ($location_global, $location_local, $location_k = null) {
if ($this->content_id) {
$this->delete();
}
if ($location_k) {
$this->location_k = $location_k;
} else {
$this->location_k = self::get_free_location_k($location_global, $location_local);
}
if ($this->content_id) {
$this->save_to_database();
}
}
/* -------------------------------------------------------------
Gets content
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/**
* Gets content at specified location
*
* @param string $location_global global content location
* @param string $location_local local content location
* @return Array array of ContentFile instances
*
* The returned array indices are the local_k.
*/
static function get_local_content ($location_global, $location_local) {
global $db;
//Get contents at this location
$location_global = $db->sql_escape($location_global);
$location_local = $db->sql_escape($location_local);
$sql = "SELECT c.* FROM content c WHERE c.location_global = '$location_global' AND c.location_local = '$location_local' ORDER BY location_k ASC";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't get content", '', __LINE__, __FILE__, $sql);
}
//Fills content array
- $contents = array();
+ $contents = [];
while ($row = $db->sql_fetchrow($result)) {
$k = $row['location_k'];
$contents[$k] = new ContentFile();
$contents[$k]->load_from_row($row);
}
return $contents;
}
}
diff --git a/includes/content/zone.php b/includes/content/zone.php
index 0f8ab16..a998659 100755
--- a/includes/content/zone.php
+++ b/includes/content/zone.php
@@ -1,195 +1,195 @@
<?php
/**
* Zone class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* @package Zed
* @subpackage Content
* @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
*/
/**
* Content zone class
*
* A zone is a physical place, independent from the location.
* This mechanism allows to more easily move zones.
*
* This class maps the content_zones table.
*/
class ContentZone {
public $id;
public $title;
public $type;
public $params;
public $deleted = false;
/**
* Initializes a new instance of a zone object
*
* @param int $id The zone ID
*/
function __construct ($id = '') {
if ($id) {
$this->id = $id;
return $this->load_from_database();
}
}
/**
* Loads the object zone (ie fill the properties) from the $_POST array
*/
function load_from_form () {
if (array_key_exists('title', $_POST)) $this->user_id = $_POST['title'];
if (array_key_exists('type', $_POST)) $this->user_id = $_POST['type'];
if (array_key_exists('params', $_POST)) $this->user_id = $_POST['params'];
if (array_key_exists('deleted', $_POST)) $this->user_id = $_POST['deleted'];
}
/**
* Loads the object zone (ie fill the properties) from the $row array
*/
function load_from_row ($row) {
$this->id = $row['zone_id'];
$this->title = $row['zone_title'];
$this->type = $row['zone_type'];
$this->params = $row['zone_params'];
$this->deleted = $row['zone_deleted'] ? true : false;
}
/**
* Loads the object zone (ie fill the properties) from the database
*/
function load_from_database () {
global $db;
$id = $db->sql_escape($this->id);
$sql = "SELECT * FROM " . TABLE_CONTENT_ZONES . " WHERE zone_id = '" . $id . "'";
if (!$result = $db->sql_query($sql)) message_die(SQL_ERROR, 'Unable to query content_zones', '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
$this->lastError = 'Zone unknown: ' . $this->id;
return false;
}
$this->load_from_row($row);
return true;
}
/**
* Saves the object to the database
*/
function save_to_database () {
global $db;
$id = $this->id ? "'" . $db->sql_escape($this->id) . "'" : 'NULL';
$title = $db->sql_escape($this->title);
$type = $db->sql_escape($this->type);
$params = $db->sql_escape($this->params);
$deleted = $this->deleted ? 1 : 0;
$sql = "REPLACE INTO " . TABLE_CONTENT_ZONES . " (`zone_id`, `zone_title`, `zone_type`, `zone_params`, `zone_deleted`) VALUES ($id, '$title', '$type', '$params', $deleted)";
if (!$db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to save", '', __LINE__, __FILE__, $sql);
}
if (!$this->id) {
$this->id = $db->sql_nextid();
}
}
/**
* Assigns the zone at the specified location.
*
* @param string $location_global the global location
* @param string $location_global the local location
* @param bool $delete_old_locations if true, delete old locations
*/
function assign_to ($location_global, $location_local, $delete_old_locations = true) {
if (!$this->id) {
$this->save_to_database();
}
global $db;
if ($delete_old_locations) {
$sql = "DELETE FROM " . TABLE_CONTENT_ZONES_LOCATIONS . " WHERE zone_id = " . $this->id;
if (!$db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to delete", '', __LINE__, __FILE__, $sql);
}
}
$g = $db->sql_escape($location_global);
$l = $db->sql_escape($location_local);
$sql = "REPLACE INTO " . TABLE_CONTENT_ZONES_LOCATIONS . " (location_global, location_local, zone_id) VALUES ('$g', '$l', $this->id)";
if (!$db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to set zone location", '', __LINE__, __FILE__, $sql);
}
}
/**
* Gets the zone at specified location
*
* @param string $location_global the global location
* @param string $location_global the local location
* @param bool $create if the zone doesn't exist, create it [optional] [default value: false]
* @return ContentZone the zone, or null if the zone doesn't exist and $create is false
*/
static function at ($location_global, $location_local, $create = false) {
global $db;
$g = $db->sql_escape($location_global);
$l = $db->sql_escape($location_local);
$sql = "SELECT * FROM " . TABLE_CONTENT_ZONES_LOCATIONS . " WHERE location_global = '$g' AND location_local = '$l'";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to set zone location", '', __LINE__, __FILE__, $sql);
}
if ($row = $db->sql_fetchrow($result)) {
return new ContentZone($row['zone_id']);
} elseif ($create) {
$zone = new ContentZone();
$zone->assign_to($location_global, $location_local);
return $zone;
} else {
return null;
}
}
/**
* Gets all the zones matching the specified location queries
*
* @param string $location_global_query the global location query
* @param string $location_local_query the local location query
* @return Array a ContentZone array, with each item a zone found
*
* [SECURITY] They are passed as is in SQL [R]LIKE queries, you can't inject users expression.
*
* The following properties are added to the ContentZone items of the returned array:
* - location_global
* - location_local
*/
static function search ($location_global_query, $location_local_query, $use_regexp_for_local = false) {
global $db;
- $zones = array();
+ $zones = [];
$op = $use_regexp_for_local ? 'RLIKE' : 'LIKE';
$sql = "SELECT * FROM " . TABLE_CONTENT_ZONES_LOCATIONS . " WHERE location_global LIKE '$location_global_query' AND location_local $op '$location_local_query'";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to set zone location", '', __LINE__, __FILE__, $sql);
}
while ($row = $db->sql_fetchrow($result)) {
$zone = new ContentZone($row['zone_id']);
$zone->location_global = $row['location_global'];
$zone->location_local = $row['location_local'];
$zones[] = $zone;
}
return $zones;
}
}
?>
diff --git a/includes/core.php b/includes/core.php
index 9aae9d1..1ece7e1 100755
--- a/includes/core.php
+++ b/includes/core.php
@@ -1,664 +1,664 @@
<?php
/**
* Core: helper methods and main libraries loader
*
* 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
*/
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Configures PHP and loads site-wide used libraries ///
/// ///
////////////////////////////////////////////////////////////////////////////////
error_reporting(E_ALL & ~E_NOTICE);
include_once("config.php");
include_once("error.php");
include_once("db/Database.php");
$db = Database::load();
Database::cleanupConfiguration();
include_once("sessions.php");
include_once("autoload.php");
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Information helper methods ///
/// ///
////////////////////////////////////////////////////////////////////////////////
/**
* Gets the nickname from the specified perso ID
*
* @param integer $perso_id The specified perso ID
* @return string The perso's nickname
*/
function get_name ($perso_id) {
global $db;
$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 the user ID from the specified username
*
* @param string $username The username
* @return integer the user ID
*/
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'];
}
/**
* Gets an information from the application global registry
*
* @param string $key the registry's key
* @return string The key value
*/
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'];
}
/**
* Sets an information in the application global registry
*
* @param string $key the registry key
* @param string $value the value to store at the specified registry key
*/
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, according the specified format.
*
* <code>
* echo generate_random_string('AAA111'); //this could output SDQ245.
* </code>
*
* @author Pierre Habart <p.habart@ifrance.com>
*
* @param string $format The format e.g. AAA111
* @return string a random string
*/
function generate_random_string ($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;
}
//Plural management
/**
* Returns "s" when the $amount request a plural
* This function is a French plural helper.
*
* @param $amount the amount of objects
* @return string 's' if $amount implies a plural ; '' if it implies a singular.
*/
function s ($amount) {
if ($amount >= 2 || $amount <= -2) return "s";
}
/**
* Returns "x" when the $amount request a plural
* This function is a French plural helper.
*
* @param $amount the amount of objects
* @return string 'x' if $amount implies a plural ; '' if it implies a singular.
*/
function x ($amount) {
if ($amount >= 2 || $amount <= -2) return "x";
}
//Debug
/**
* Prints human-readable information about a variable.
*
* It behaves like the print_r command, but the output is enclosed in pre tags,
* to have a preformatted HTML output.
*
* @param mixed $expression The expression to be printed
*/
function dprint_r ($expression) {
echo '<pre>';
print_r($expression);
echo '</pre>';
}
//GUID
/**
* Generates a GUID, or more precisely an UUID
* @link http://en.wikipedia.org/wiki/Universally_Unique_Identifier Wikipedia, Universally Unique Identifier.
*
* A UUID is a 36 chars string of 32 hexadecimal and 4 dashes, with a
* very high probability to be unique.
*
* @return string the UUID
*/
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;
}
/**
* Determines if the expression is a valid UUID (a guid without {}).
* @see new_guid
*
* @param string $expression the expression to check
* @return boolean true if the specified expression is a valid UUID ; otherwise, false.
*/
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
* @return string the extension from the specified file
*/
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 the LANG constant, to lang to print
*
* This information is contained in the session, or if not yet defined,
* it's to determine according the user's browser preferences.
* @see find_lang
*/
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's browser
* @see get_http_accept_languages
*
* @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];
}
}
}
/**
* Gets the languages accepted by the browser, by order of priority.
*
* This will read the HTTP_ACCEPT_LANGUAGE variable sent by the browser in the
* HTTP request.
*
* @return Array an array of string, each item a language accepted by browser
*/
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);
+ $userlangs[] = [1, $language];
} else {
- $userlangs[] = array($userlang[1], $userlang[0]);
+ $userlangs[] = [$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->configLoad("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->configLoad('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
* @link http://en.wikipedia.org/wiki/Unix_time Unix time
*
* @param string $timestamp the timestamp to convert
* @return integer the 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
* @see to_unixtime
*
* @param int $unixtime the time to convert
* @param int $format 8 or 10. If 8 (default), will output YYYYMMDD. If 10, YYYY-MM-DD.
* @return string the timestamp
*/
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 or gets the current hypership time.
* @link http://en.wikipedia.org/wiki/Unix_time
* @link http://www.purl.org/NET/Zed/blog/HyperShipTime
*
* @param int $unixtime The unixtime to convert to HyperShip time. If omitted, the current unixtime.
* @return string The HyperShip time
*/
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 the URL matching the specified resource.
*
* Example:
* <code>
* $url = get_url('ship', $ship);
* echo $url; //if $ship contains S00001, this should print /ship/S00001
* </code>
*
* @param string $resource,... the resources
* @return string the URL matching the specified resource
*/
function get_url () {
global $Config;
if (func_num_args() > 0) {
$pieces = func_get_args();
return $Config['BaseURL'] . '/' . implode('/', $pieces);
} elseif ($Config['BaseURL'] == "" || $Config['BaseURL'] == $_SERVER["PHP_SELF"]) {
return "/";
} else {
return $Config['BaseURL'];
}
}
/**
* Gets the current page URL
*
* @return string the current page URL
*/
function get_page_url () {
$url = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];
if (substr($url, -10) == $_SERVER["PHP_SELF"]) {
return substr($url, 0, -9);
}
return $url;
}
/**
* Gets the 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.
*
* This function allows the entry point controllers to get the current URL
* in a consistent way, for any redirection configuration
*
* So with /foo/bar, /index.php/foo/bar, /zed/index.php/foo/bar or /zed/foo/bar
* get_current_url will return /foo/bar
*
* @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
* @see get_current_url
*
* This method is used by the controllers entry points to know the URL and
* call relevant subcontrollers.
*
* @return Array an array of string, one for each URL fragment
*/
function get_current_url_fragments () {
$url_source = get_current_url();
- if ($url_source == $_SERVER["PHP_SELF"]) return array();
+ if ($url_source == $_SERVER["PHP_SELF"]) return [];
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 parameter 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/includes/db/Database.php b/includes/db/Database.php
index f7be960..a40e44d 100755
--- a/includes/db/Database.php
+++ b/includes/db/Database.php
@@ -1,84 +1,84 @@
<?php
/**
* Database calling class.
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2015, Dereckson, some rights reserved.
* Released under BSD license.
*
* This file provides a calling class, which read the configuration, ensures
* the database class for the db engine given in config exists and initializes
* it.
*
* The class to call is determined from the following preference:
* <code>
* $Config['database']['engine'] = 'MySQL'; //will use DatabaseMySQL class.
* </code>
*
* @package Zed
* @subpackage Database
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @copyright 2015 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
*/
/**
* Databasecaller
*/
class Database {
/**
* Gets the database instance, initializing it if needed
*
* The correct database instance to initialize will be determined from the
* $Config['database']['engine'] preference.
*
* The database class to use will be Database + (preference engine, capitalized)
*
* This method will creates an instance of the specified object,
* calling the load static method from this object class.
*
* Example:
* <code>
* $Config['database']['engine'] = 'quux';
* $db = Database::load(); //Database:load() will call DatabaseQuux:load();
* </code>
*
* @return Database the database instance
*/
static function load () {
global $Config;
if (
!array_key_exists('database', $Config) ||
!array_key_exists('engine', $Config['database'])
) {
//database is not configured or engine is not specified
message_die(GENERAL_ERROR, 'A database engine (a MySQL variant is recommended) should be configured. Please ensure you have a ["database"]["engine"] value in the configuration.', "Setup issue");
} else {
//engine is specified in the configuration
$engine = $Config['database']['engine'];
}
$engine_file = 'includes/db/' . $engine . '.php';
$engine_class = 'Database' . ucfirst($engine);
if (!file_exists($engine_file)) {
message_die(GENERAL_ERROR, "Can't initialize $engine database engine.<br />$engine_file not found.", 'Setup issue');
}
require_once($engine_file);
if (!class_exists($engine_class)) {
message_die(GENERAL_ERROR, "Can't initialize $engine database engine.<br />$engine_class class not found.", 'Setup issue');
}
- return call_user_func(array($engine_class, 'load'));
+ return call_user_func([$engine_class, 'load']);
}
static function cleanupConfiguration () {
global $Config;
unset($Config['database']['password']);
}
}
diff --git a/includes/geo/body.php b/includes/geo/body.php
index e9d7f25..f5301ea 100755
--- a/includes/geo/body.php
+++ b/includes/geo/body.php
@@ -1,172 +1,172 @@
<?php
/**
* Geo body class.
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* A 3D grid of objects
*
* 0.1 2010-01-27 21:51 Autogenerated by Pluton Scaffolding
*
* @package Zed
* @subpackage Geo
* @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
*/
/**
* Geo body class
*/
class GeoBody {
public $code;
public $name;
public $hypership;
public $asteroid;
public $moon;
public $planet;
public $star;
public $orbital;
public $hidden;
public $location;
public $description;
public $lastError;
/**
* Initializes a new instance
*
* @param int $code the primary key
*/
function __construct ($code = null) {
if ($code) {
$this->code = $code;
$this->load_from_database();
}
}
/**
* Loads the object body (ie fill the properties) from the $_POST array
*
* @param bool $readBoolean if false, don't read any form item matching a boolean field to avoid to set it to false if there are absent from a form.
*/
function load_from_form ($readBoolean = true) {
if (array_key_exists('name', $_POST)) $this->name = $_POST['name'];
if ($readBoolean) {
if (array_key_exists('hypership', $_POST)) $this->hypership = $_POST['hypership'];
if (array_key_exists('star', $_POST)) $this->start = $_POST['star'];
if (array_key_exists('asteroid', $_POST)) $this->hypership = $_POST['asteroid'];
if (array_key_exists('moon', $_POST)) $this->start = $_POST['moon'];
if (array_key_exists('planet', $_POST)) $this->start = $_POST['planet'];
if (array_key_exists('orbital', $_POST)) $this->start = $_POST['orbital'];
if (array_key_exists('hidden', $_POST)) $this->start = $_POST['hidden'];
}
if (array_key_exists('location', $_POST)) $this->location = $_POST['location'];
if (array_key_exists('description', $_POST)) $this->description = $_POST['description'];
}
/**
* Loads the object body (ie fill the properties) from the database
*/
function load_from_database () {
global $db;
$sql = "SELECT * FROM " . TABLE_BODIES . " WHERE body_code = '" . $this->code . "'";
if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Unable to query geo_bodies", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
$this->lastError = "body unknown: " . $this->code;
return false;
}
$this->name = $row['body_name'];
$this->location = $row['body_location'];
$this->description = $row['body_description'];
if ($row['body_status']) {
$flags = explode(',', $row['body_status']);
foreach ($flags as $flag) {
$this->$flag = true;
}
}
return true;
}
/**
* Gets the status field
*
* @return string the status field value (e.g. "asteroid,hidden")
*/
function getStatus () {
- $flags = array('hypership','asteroid','moon','planet','star','orbital','hidden');
+ $flags = ['hypership','asteroid','moon','planet','star','orbital','hidden'];
foreach ($flags as $flag) {
if ($this->$flag) {
$status[] = $flag;
}
}
return implode(',', $status);
}
/**
* Gets the kind of place the body is (e.g. asteroid)
*
* @return string the kind of place
*/
function kind () {
//If a location can be described by 2 flags, order the relevant flags list
//by priority, as it'll return the first triggered.
//e.g. a moon converted in hypership will be "hypership" and not "moon".
- $relevantFlags = array('hypership','asteroid','moon','planet','star','orbital');
+ $relevantFlags = ['hypership','asteroid','moon','planet','star','orbital'];
foreach ($relevantFlags as $flag) {
if ($this->$flag) {
return $flag;
}
}
return "";
}
/**
* Gets the name of the body, as a string representation of the object
*
* @return string the name of the body
*/
function __toString () {
return $this->name;
}
/**
* Saves to database
*/
function save_to_database () {
global $db;
$code = $this->code ? "'" . $db->sql_escape($this->code) . "'" : 'NULL';
$name = $db->sql_escape($this->name);
$status = getStatus();
$location = $db->sql_escape($this->location);
$description = $db->sql_escape($this->description);
//Updates or inserts
$sql = "REPLACE INTO " . TABLE_BODIES . " (`body_code`, `body_name`, `body_status`, `body_location`, `body_description`) VALUES ($code, '$name', '$status', '$location', '$description')";
if (!$db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to save", '', __LINE__, __FILE__, $sql);
}
if (!$code) {
//Gets new record code value
$this->code = $db->sql_nextid();
}
}
}
diff --git a/includes/geo/galaxy.php b/includes/geo/galaxy.php
index 7a274f0..be224f5 100755
--- a/includes/geo/galaxy.php
+++ b/includes/geo/galaxy.php
@@ -1,119 +1,119 @@
<?php
/**
* Geo galaxy class.
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* A 3D grid of objects
*
* 0.1 2010-02-08 14:02 Initial version [DcK]
* 0.2 2010-07-25 9:20 Spherical conversion, get objects
*
* @package Zed
* @subpackage Geo
* @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
*/
/**
* Geo galaxy class
*
* This class provides methods to convert coordinate polars.
*
* @todo create a unit testing file dev/tests/GeoGalaxyTest.php
* @todo add unit testing for the normalizeAngle method in dev/tests/GeoGalaxyTest.php
*/
class GeoGalaxy {
/*
* ----------------------------------------------------------------------- *
* Objects fetchers
* ----------------------------------------------------------------------- *
*/
/**
* Gets all the coordinates of the objects in the galaxy.
*
* @return array An array of array. Each item is [string object_name, string object_type, GeoPoint3D coordinates]
*/
static function getCoordinates () {
global $db;
$sql = "SELECT * FROM geo_coordinates";
if (!$result = $db->sql_query($sql)) message_die(SQL_ERROR, "Can't query geo_coordinates view.", '', __LINE__, __FILE__, $sql);
- $objects = array();
+ $objects = [];
while ($row = $db->sql_fetchrow($result)) {
//Demios ship xyz: [-50, 30, 40]
//Kaos asteroid xyz: [150, -129, 10]
- $objects[] = array($row[0], $row[1], GeoPoint3D::fromString($row[2]));
+ $objects[] = [$row[0], $row[1], GeoPoint3D::fromString($row[2])];
}
return $objects;
}
/*
* ----------------------------------------------------------------------- *
* Helper methods - math
* ----------------------------------------------------------------------- *
*/
/**
* Normalizes an angle, so 0 =< angle < 2 PI
*
* @param float $angle angle in radians (use deg2rad() if you've degrees)
* @return an angle in the 0 =< angle < 2 PI interval
*/
static function normalizeAngle ($angle) {
while ($angle < 0) {
$angle += 2 * M_PI;
}
while ($angle >= 2 * M_PI) {
$angle -= 2 * M_PI;
}
return $angle;
}
/**
* Converts (x, y, z) cartesian to (ρ, φ, θ) spherical coordinates
*
* The algo used is from http://fr.wikipedia.org/wiki/Coordonn%C3%A9es_sph%C3%A9riques#Relation_avec_les_autres_syst.C3.A8mes_de_coordonn.C3.A9es_usuels
*
* @param int $x the x coordinate
* @param int $y the y coordinate
* @param int $z the z coordinate
* @return array an array of 3 floats number, representing the (ρ, φ, θ) spherical coordinates
*/
static function cartesianToSpherical ($x, $y, $z) {
$rho = sqrt($x * $x + $y * $y + $z * $z); //ρ = sqrt(x² + y² + z²)
$theta= acos($z / $rho); //φ = acos z/φ
$phi = acos($x / sqrt($x * $x + $y * $y)); //θ = acos x / sqrt(x² + y²)
if (y < 0) $phi = 2 * M_PI - $phi; //∀ y < 0 θ = 2π - θ
- return array(round($rho, 2), round(rad2deg($theta), 2), round(rad2deg($phi), 2));
+ return [round($rho, 2), round(rad2deg($theta), 2), round(rad2deg($phi), 2)];
}
/**
* Converts (x, y, z) cartesian to (ρ, φ, θ) spherical coordinates
*
* The algo used is from http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Cartesian_to_polar_conversion
*
* @param int $x the x coordinate
* @param int $y the y coordinate
* @param int $z the z coordinate
* @return array an array of 3 floats number, representing the (ρ, φ, θ) spherical coordinates
*/
static function cartesianToSphericalAlternative ($x, $y, $z) {
$rho = sqrt($x * $x + $y * $y + $z * $z); //ρ = sqrt(x² + y² + z²)
$theta= atan2($y, $x); //φ = atan2 $y $x
$phi = acos($z / $rho); //θ = acos z/φ
- return array(round($rho, 2), round(rad2deg($theta), 2), round(rad2deg($phi), 2));
+ return [round($rho, 2), round(rad2deg($theta), 2), round(rad2deg($phi), 2)];
}
}
diff --git a/includes/geo/location.php b/includes/geo/location.php
index 8be9601..03583fb 100755
--- a/includes/geo/location.php
+++ b/includes/geo/location.php
@@ -1,434 +1,434 @@
<?php
/**
* Geo location class.
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2010-01-28 18:52 DcK
*
* @package Zed
* @subpackage Geo
* @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
*/
require_once('body.php');
require_once('place.php');
require_once('point3D.php');
require_once('includes/objects/ship.php');
/**
* Geo location class
*
* This class contains properties to get, set or compare a location and
* explore the geo classes linked to.
*
* It quickly allow to parse through the location classes in templates and
* controllers.
*
* @todo Initialize $point3D from $body or $ship own locations
* @todo Improve GeoLocation documentation (especially magic properties)
*/
class GeoLocation {
/**
* An array of strings containing location data.
*
* In the current class implementation,
* the first element is the global location
* and the second element is the local location.
*
* @var Array
*/
private $data;
/**
* A body object
*
* It contains a GeoBody value when the global location is a body
* ie if $this->data[0][0] == 'B'
*
* Otherwise, its value is null.
*
* @var GeoBody
*/
public $body = null;
/**
* A place object
*
* It contains a GeoPlacevalue when the global location is a place
* ie if $this->data[0][0] == 'B' && strlen($this->data[0]) == 9
*
* Otherwise, its value is null.
*
* @var GeoPlace
*/
public $place = null;
/**
* A point identified by x, y, z coordinates
*
* @var GeoPoint3D
*/
public $point3D = null;
/**
* A ship object
*
* It contains a Ship value when the global location is a ship
* ie if $this->data[0][0] == 'S'
*
* Otherwise, its value is null.
*
* @var Ship
*/
public $ship = null;
/**
* Initializes a new location instance
*
* @param string $global the global location
* @param string local the locallocation
*
* @todo Improve local location handling
*/
function __construct ($global = null, $local = null) {
if (!$global) {
- $this->data = array();
+ $this->data = [];
} elseif (preg_match("/[BS][0-9]{5}[0-9]{3}/", $global)) {
$this->data[0] = $global;
} elseif (preg_match("/[BS][0-9]{5}/", $global)) {
$this->data[0] = $global;
} elseif (preg_match("/^xyz\:/", $global)) {
$coords = sscanf($global, "xyz: [%d, %d, %d]");
if (count($coords) == 3) {
$this->data[0] = $global;
} else {
throw new Exception("Invalid expression: $global");
}
} else {
global $db;
$name = $db->sql_escape($global);
$sql = "SELECT location_code FROM " . TABLE_LOCATIONS . " WHERE location_name LIKE '$name'";
$code = $db->sql_query_express($sql);
if ($code) {
$this->data[0] = $code;
return;
}
throw new Exception("Invalid expression: $global");
}
//TODO: handle $local in a better way: from the global location, gets
//a local location handler. Or a some inheritance, like a class
//HypershipGeoLocation extending GeoLocation.
if ($local !== null) $this->data[1] = $local;
$this->load_classes();
}
/**
* Gets $place, $body and $ship instances if they're needed
*/
function load_classes () {
//No data, no class to load
if (!count($this->data))
return;
//Loads global classes
$global = $this->data[0];
$code = substr($global, 1, 5);
switch ($global[0]) {
case 'B':
switch (strlen($global)) {
case 9:
$this->place = GeoPlace::from_code($global);
case 6:
$this->body = new GeoBody($code);
break;
}
break;
case 'S':
$this->ship = new Ship($code);
break;
case 'x':
$coords = sscanf($global, "xyz: [%d, %d, %d]");
if (count($coords) == 3) {
$this->point3D = new GeoPoint3D($coords[0], $coords[1], $coords[2]);
}
break;
}
}
/**
* Magic method called when a unknown property is get.
*
* Handles $global, $local, $type, $body_code, $ship_code, $place_code,
* $body_kind, $containsGlobalLocation, $containsLocalLocation.
*/
function __get ($variable) {
switch ($variable) {
/* main variables */
case 'global':
return $this->data[0];
break;
case 'local':
return (count($this->data) > 1) ? $this->data[1] : null;
break;
/* global location */
case 'type':
return $this->data[0][0];
case 'body_code':
if ($this->data[0][0] == 'B') {
return substr($this->data[0], 1, 5);
}
return null;
case 'place_code':
if ($this->data[0][0] == 'B') {
return substr($this->data[0], 6, 3);
}
return null;
case 'ship_code':
if ($this->data[0][0] == 'S') {
return substr($this->data[0], 1, 5);
}
return null;
case 'body_kind':
if ($this->data[0][0] == 'B' && $this->body != null) {
if ($kind = $this->body->kind()) {
return $kind;
}
} elseif ($this->data[0][0] == 'S') {
return 'ship';
}
return 'place';
case 'containsGlobalLocation':
return count($this->data) > 0;
case 'containsLocalLocation':
return count($this->data) > 1;
default:
throw new Exception("Unknown variable: $variable");
break;
}
}
/**
* Checks if the place exists
*
* @return bool true if the place exists ; otherwise, false.
*
* @todo Handle alias
*/
function exists () {
$n = count($this->data);
//If not defined, it doesn't exist
if ($n == 0) return false;
//Checks global location
switch ($this->data[0][0]) {
case 'B':
switch (strlen($this->data[0])) {
case 9:
if (!$place = GeoPlace::from_code($this->data[0]))
return false;
break;
case 6:
$body = new GeoBody(substr($this->data[0], 1));
if ($body->lastError) return false;
break;
default:
message_die(GENERAL_ERROR, "Invalid global location expression size: " . $this->data[0], "GeoLocation exists method", __LINE__, __FILE__);
}
break;
case 'S':
$ship = new Ship(substr($this->data[0], 1));
if ($body->lastError) return false;
break;
default:
message_die(GENERAL_ERROR, "Invalid global location expression size: " . $this->data[0], "GeoLocation exists method", __LINE__, __FILE__);
return false;
}
if ($n > 1) {
if (!isset($place)) {
message_die(GENERAL_ERROR, "Can't check if a local place exists for the following location: " . $this->data[0], "GeoLocation exists method", __LINE__, __FILE__);
}
if (!$place->is_valid_local_location($this->data[1])) {
return false;
}
}
return true;
}
/**
* Checks if the place is equals at the specified expression or place
*
* @return bool true if the places are equals ; otherwise, false.
*
* @todo Create a better set of rules to define when 2 locations are equal.
*/
function equals ($expression) {
//Are global location equals?
//TODO: create a better set of rules to define when 2 locations are equal.
if (is_a($expression, 'GeoLocation')) {
if (!$this->equals($expression->data[0])) {
return false;
}
if (count($expression->data) + count($this->data) > 2) {
return $expression->data[1] == $this->data[1];
}
}
if ($expression == $this->data[0]) return true;
$n1 = strlen($expression);
$n2 = strlen($this->data[0]);
if ($n1 > $n2) {
return substr($expression, 0, $n2) == $this->data[0];
}
return false;
}
/**
* Represents the current location instance as a string
*
* @return string a string representing the current location
*/
function __toString () {
if (!$this->data[0])
return "";
switch ($this->data[0][0]) {
case 'S':
$ship = new Ship($this->ship_code);
$location[] = $ship->name;
break;
case 'B':
$body = new GeoBody($this->body_code);
$location[] = $body->name ? $body->name : lang_get('UnknownBody');
if (strlen($this->data[0]) == 9) {
$place = GeoPlace::from_code($this->data[0]);
$location[] = $place->name ? $place->name : lang_get('UnknownPlace');
}
break;
case 'x':
$pt = $this->point3D->toSpherical();
return sprintf("(%d, %d°, %d°)", $pt[0], $pt[1], $pt[2]);
default:
message_die(GENERAL_ERROR, "Unknown location identifier: $type.<br />Expected: B or S.");
}
return implode(", ", array_reverse($location));
}
/**
* Magic method called when a unknown property is set.
*
* Handles $global, $local, $type, $body_code, $ship_code, $place_code
*/
function __set ($variable, $value) {
switch ($variable) {
/* main variables */
case 'global':
$this->data[0] = $value;
break;
case 'local':
$this->data[1] = $value;
break;
/* global location */
case 'type':
if ($value == 'B' || $value == 'S') {
if (!$this->data[0]) {
$this->data[0] = $value;
} else {
$this->data[0][0] = $value;
}
}
break;
case 'body_code':
if (preg_match("/[0-9]{1,5}/", $value)) {
$value = sprintf("%05d", $value);
if (!$this->data[0]) {
$this->data[0] = "B" . $value;
return;
} elseif ($this->data[0][0] == 'B') {
$this->data[0] = "B" . $value . substr($this->data[0], 6);
return;
}
throw new Exception("Global location isn't a body.");
}
throw new Exception("$value isn't a valid body code");
case 'ship_code':
if (preg_match("/[0-9]{1,5}/", $value)) {
$value = sprintf("%05d", $value);
if (!$this->data[0]) {
$this->data[0] = "S" . $value;
return;
} elseif ($this->data[0][0] == 'S') {
$this->data[0] = "S" . $value . substr($this->data[0], 6);
return;
}
throw new Exception("Global location isn't a ship.");
}
throw new Exception("$value isn't a valid ship code");
case 'place_code':
if (!preg_match("/[0-9]{1,3}/", $value)) {
throw new Exception("$value isn't a valid place code");
}
$value = sprintf("%03d", $value);
if ($this->data[0][0] == 'B') {
$this->data[0] = substr($this->data[0], 0, 6) . $value;
}
throw new Exception("Global location isn't a body.");
default:
throw new Exception("Unknown variable: $variable");
break;
}
}
}
diff --git a/includes/geo/octocube.php b/includes/geo/octocube.php
index 0ea74d9..568183f 100755
--- a/includes/geo/octocube.php
+++ b/includes/geo/octocube.php
@@ -1,141 +1,141 @@
<?php
/**
* Geo octocube class.
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* @package Zed
* @subpackage Geo
* @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
*/
/**
* Geo octocube class
*
* An octocube is a cube divided in 8 parts (sliced in two in x, y and z)
*
* The coordinates (0, 0, 0) represents the octocube center.
*/
class GeoOctocube {
/**
* Gets the sector from the (x, y, z) specified coordinates
*
* Sector will be:
* <code>
* // _____ _____
* // / 5 / 6 /|
* // /- - -/- - -/ |
* // /_____/____ /| |
* // | | | |/|
* // | 7 | 8 | / | 2
* // |_____|_____|/| |
* // | | | |/
* // | 3 | 4 | /
* // |_____|_____|/
* </code>
*
* @param int $x the x coordinate
* @param int $y the y coordinate
* @param int $z the z coordinate
* @return int the number of the sector (0 if x = y = z = 0 ; otherwise, 1 to 8)
*/
static function getSector ($x, $y, $z) {
//Cube center
if ($x == 0 && $y == 0 && $z == 0) return 0;
//One of the 8 cubes
$sector = 1;
if ($x >= 0) $sector++; //we're at right
if ($y < 0) $sector += 2; //we're at bottom
if ($z >= 0) $sector += 4; //we're on the top layer
return $sector;
}
/**
* Gets the sector from the (x, y, z) specified coordinates
* @see getSector
*
* @param mixed $pt a GeoPoint3D object for the x, y, z coordinates or a parsable string
* @return int the number of the sector (0 if x = y = z 0 ; otherwise, 1 to 8)
*/
static function getSectorFromPoint3D ($pt) {
if (is_string($pt)) {
$pt = GeoPoint3D::fromString($pt);
}
return self::getSector($pt->x, $pt->y, $pt->z);
}
/**
* Gets the base vector for the specified sector
*
* Example code:
*
* $vector = GeoOctocube::getBaseVector(4);
* //$vector is a (1, -1, -1) array
*
* @param int $sector the sector number (0-8)
* @return array if the sector is 0, (0, 0, 0) ; otherwise, an array with three signed 1 values.
*/
static function getBaseVector ($sector) {
switch ($sector) {
- case 0: return array(0, 0, 0);
- case 1: return array(-1, 1, -1);
- case 2: return array(1, 1, -1);
- case 3: return array(-1, -1, -1);
- case 4: return array(1, -1, -1);
- case 5: return array(-1, 1, 1);
- case 6: return array(1, 1, 1);
- case 7: return array(-1, -1, 1);
- case 8: return array(1, -1, 1);
+ case 0: return [0, 0, 0];
+ case 1: return [-1, 1, -1];
+ case 2: return [1, 1, -1];
+ case 3: return [-1, -1, -1];
+ case 4: return [1, -1, -1];
+ case 5: return [-1, 1, 1];
+ case 6: return [1, 1, 1];
+ case 7: return [-1, -1, 1];
+ case 8: return [1, -1, 1];
default: message_die(GENERAL_ERROR, "Invalid sector: $sector", "GeoOctocube::getBaseVector");
}
}
/**
* Gets SQL RLIKE pattern for the specified sector
*
* @param int $sector the sector number (0-8)
* @param int $z if not null, limits the query to the specified z coordinate [optional]
* @return string a SQL clause like "([0-9]+, -[0,9]+, [0,9]+)"
*/
static function getRlikePatternFromSector ($sector, $z = null) {
if ($sector == 0) return "(0, 0, 0)";
$vector = self::getBaseVector($sector);
//x
if ($vector[0] == 1)
$query = "([0-9]+, ";
else
$query = "(-[0-9]+, ";
//y
if ($vector[1] == 1)
$query .= "[0-9]+, ";
else
$query .= "-[0-9]+, ";
//z
if ($z !== null) {
$query .= "$z)";
} elseif ($vector[2] == "1") {
$query .= "[0-9]+)";
} else {
$query .= "-[0-9]+)";
}
return $query;
}
}
diff --git a/includes/geo/place.php b/includes/geo/place.php
index 02c2c9f..53e3372 100755
--- a/includes/geo/place.php
+++ b/includes/geo/place.php
@@ -1,214 +1,214 @@
<?php
/**
* Geo place class.
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2010-01-28 01:48 Autogenerated by Pluton Scaffolding
*
* @package Zed
* @subpackage Geo
* @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
*/
/**
* Default local location format
*
* The local_location format is a PCRE regular expression
*
* By default, local_location format is an (x, y, z) expression
*/
define('LOCATION_LOCAL_DEFAULT_FORMAT', '/^\([0-9]+( )*,( )*[0-9]+( )*,( )*[0-9]+\)$/');
/**
* Geo place
*
* A place is a city or a hypership district.
*
* It's identified by a 9 chars geocode like B0001001.
* The 5 first chars indicates the body (class GeoBody) where the place is and
* the 3 last digits is the place number.
*
* This class maps the geo_places table.
*/
class GeoPlace {
public $id;
public $body_code;
public $code;
public $name;
public $description;
public $location_local_format;
public $start;
public $hidden;
/**
* Initializes a new instance
*
* @param int $id the primary key
*/
function __construct ($id = null) {
if ($id) {
$this->id = $id;
$this->load_from_database();
}
}
/**
* Loads the object place (ie fill the properties) from the $_POST array
*/
function load_from_form () {
if (array_key_exists('body_code', $_POST)) $this->body_code = $_POST['body_code'];
if (array_key_exists('code', $_POST)) $this->code = $_POST['code'];
if (array_key_exists('name', $_POST)) $this->name = $_POST['name'];
if (array_key_exists('description', $_POST)) $this->description = $_POST['description'];
if (array_key_exists('status', $_POST)) $this->status = $_POST['status'];
if (array_key_exists('location_local_format', $_POST)) $this->location_local_format = $_POST['location_local_format'];
}
/**
* Loads the object place (ie fill the properties) from the database
*/
function load_from_database () {
global $db;
$sql = "SELECT * FROM " . TABLE_PLACES . " WHERE place_id = '" . $this->id . "'";
if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Unable to query geo_places", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
$this->lastError = "place unknown: " . $this->id;
return false;
}
$this->body_code = $row['body_code'];
$this->code = $row['place_code'];
$this->name = $row['place_name'];
$this->description = $row['place_description'];
$this->location_local_format = $row['location_local_format'];
//Explodes place_status SET field in boolean variables
if ($row['place_status']) {
$flags = explode(',', $row['place_status']);
foreach ($flags as $flag) {
$this->$flag = true;
}
}
return true;
}
/**
* Gets status field value
*
* @return string the status field value (e.g. "requiresPTA,default")
*/
function getStatus () {
- $flags = array('start', 'hidden');
+ $flags = ['start', 'hidden'];
foreach ($flags as $flag) {
if ($this->$flag == true) {
$status[] = $flag;
}
}
return implode(',', $status);
}
/**
* Saves to database
*/
function save_to_database () {
global $db;
$id = $this->id ? "'" . $db->sql_escape($this->id) . "'" : 'NULL';
$body_code = $db->sql_escape($this->body_code);
$code = $db->sql_escape($this->code);
$name = $db->sql_escape($this->name);
$description = $db->sql_escape($this->description);
$status = $this->getStatus();
$location_local_format = $db->sql_escape($this->location_local_format);
//Updates or inserts
$sql = "REPLACE INTO " . TABLE_PLACES . " (`place_id`, `body_code`, `place_code`, `place_name`, `place_description`, `place_status`, `location_local_format`) VALUES ($id, '$body_code', '$code', '$name', '$description', '$status', '$location_local_format')";
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();
}
}
/**
* Determines if the specified local location looks valid
*
* @param string $local_location the local location
* @return boolean true if the specified local location looks valid ; otherwise, false.
*/
function is_valid_local_location ($local_location) {
$format = $this->location_local_format ? $this->location_local_format : LOCATION_LOCAL_DEFAULT_FORMAT;
return preg_match($format, $local_location) > 0;
}
/**
* Gets a string representation of the current place
*
* @return string A Bxxxxxyyy string like B00001001, which represents the current place.
*/
function __tostring () {
return 'B' . $this->body_code . $this->code;
}
/**
* Creates a Place instance, from the specified body/place code
*
* @param $code the place's code
* @return GeoPlace the place instance
*/
static function from_code ($code) {
global $db;
$sql = "SELECT * FROM " . TABLE_PLACES . " WHERE CONCAT('B', body_code, place_code) LIKE '$code'";
if (!$result = $db->sql_query($sql)) message_die(SQL_ERROR, "Unable to query geo_places", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
return null;
}
$place = new GeoPlace();
$place->id = $row['place_id'];
$place->body_code = $row['body_code'];
$place->code = $row['place_code'];
$place->name = $row['place_name'];
$place->description = $row['place_description'];
$place->location_local_format = $row['location_local_format'];
//Explodes place_status SET field in boolean variables
if ($row['place_status']) {
$flags = explode(',', $row['place_status']);
foreach ($flags as $flag) {
$place->$flag = true;
}
}
return $place;
}
/**
* Gets a start location
*
* @return string The global location code of a start location
*
* @TODO sql optimisation (query contains ORDER BY RAND())
*/
static function get_start_location () {
global $db;
$sql = "SELECT CONCAT('B', body_code, place_code) FROM " . TABLE_PLACES . " WHERE FIND_IN_SET('start', place_status) > 0 ORDER BY rand() LIMIT 1";
return $db->sql_query_express($sql);
}
}
diff --git a/includes/geo/pointPolarZ.php b/includes/geo/pointPolarZ.php
index 3098089..0b44265 100755
--- a/includes/geo/pointPolarZ.php
+++ b/includes/geo/pointPolarZ.php
@@ -1,374 +1,374 @@
<?php
/**
* Geo point polar+z class.
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* @package Zed
* @subpackage Geo
* @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
*/
require_once("point3D.php");
/**
* Geo point polar+z class.
*
* This class represents a r, ρ, z point.
*
* They are useful to express coordinates in a cylinder shape, like a tower
* where it make senses to use polar coordinates instead x, y but where the
* height is not relative to a center, like it would be in a sphere.
*
* It implements IteratorAggregate to allow the foreach instruction
* on a GeoPointPolarZ object:
*
* <code>
* $point = new GeoPointPolarZ(17, '24°', -6);
* foreach ($point as $axis => $coordinate) {
* echo "\n\t$axis = $coordinate";
* }
* //This will output:
* // r = 17
* // t = 24°
* // z = -6
* </code>
*
* The point 3D representation is rtz: [ρ, θ, z] ; you can print it as a string
* and get this format:
*
* <code>
* $point = new GeoPointPolarZ(17, '24°', -6);
* echo (string)$point; //will output rρz: [17, 24°, -6]
* </code>
*
*/
class GeoPointPolarZ implements IteratorAggregate {
//
// ρ, θ, z public properties
//
/**
* the ρ coordinate
*
* @var float
*/
public $r;
/**
* the θ coordinate
*
* This coordinate could be expressed as:
* - a string with a float, appended by "°" or " °" (in degree)
* - as a float (in radian)
*
* @var mixed
*/
public $t;
/**
* the z coordinate
*
* @var float
*/
public $z;
//
// constructor / toString
//
/**
* Initializes a new instance of GeoPointPolarZ class
*
* @param float $r the ρ coordinate
* @param mixed $t the θ coordinate, in ° (string) or radian (float)
* @param float $z the z coordinate
*/
function __construct ($r, $t, $z) {
$this->r = (float)$r;
$this->t = trim($t);
$this->z = (float)$z;
}
/**
* Parses a string expression and gets a GeoPointPolarZ object
*
* Formats recognized are:
* - rtz: [ρ, θ, z]
* - (ρ, θ, z)
*
* @param string $expression the expression to parse
* @return GeoPointPolarZ If the specified expression could be parsed, a GeoPointPolarZ instance ; otherwise, null.
*/
static function fromString ($expression) {
if (string_starts_with($expression, 'rtz:', false)) {
$pos1 = strpos($expression, '[', 4) + 1;
$pos2 = strpos($expression, ']', $pos1);
if ($pos1 > -1 && $pos2 > -1) {
$expression = substr($expression, $pos1, $pos2 - $pos1);
$rtz = explode(',', $expression, 3);
return new GeoPointPolarZ($rtz[0], $rtz[1], $rtz[2]);
}
} elseif ($expression[0] = '(') {
$expression = substr($expression, 1, -1);
$rtz = explode(',', $expression, 3);
return new GeoPointPolarZ($rtz[0], $rtz[1], $rtz[2]);
}
return null;
}
/**
* Returns a string representation of the point coordinates.
*
* @param $format the format to use
* @return string a string representation of the coordinates
*
* To print a "rtz: [10, 20°, 40]" string:
* $point = new GeoPointPolarZ(10, '20°', 40);
* echo $point->sprintf("rtz: [%d, %s, %d]");
*
* //Of course, you could have (implicitly) use the __toString method:
* echo $point;
*
* To print a (10, 20°, 40) string:
* $point = new GeoPointPolarZ(10, 20°, 40);
* echo $point->sprintf("(%d, %s, %d)");
*/
function sprintf ($format) {
return sprintf($format, $this->r, self::getDegrees($this->t), $this->z);
}
/**
* Returns a rρz: [r, ρ, z] string representation of the point coordinates.
*
* @return string a rtz: [ρ, θ, z] string representation of the coordinates
*/
function __toString () {
return $this->sprintf("rtz: [%d, %s, %d]");
}
/**
* Determines if this point is equal to the specified point.
*
* @param GeoPointPolarZ $point The point to compare
* @return bool true if the two points are equal ; otherwise, false.
*/
function equals ($point) {
return ($this->r == $point->r) && self::areAngleEqual($this->t, $point->t) && ($this->z == $point->z);
}
/**
* Determines if two angles are equal
* @param mixed $angle1 the first angle value, ie a float (angle in radian) or a string formed by an integer appended by ° (degrees)
* @param mixed $angle2 the second angle value, a float (angle in radian) or a string formed by an integer appended by ° (degrees)
* @return bool true if the angles are equal ; otherwise, false.
*/
static function areAngleEqual ($angle1, $angle2) {
if ($angle1 === $angle2) return true;
if (!is_numerical($angle1)) {
$angle1 = deg2rad((float)$angle1);
}
if (!is_numerical($angle2)) {
$angle2 = deg2rad((float)$angle2);
}
$angle1 = self::normalizeAngle($angle1);
$angle2 = self::normalizeAngle($angle2);
return ($angle1 == $angle2);
}
/**
* Normalizes an angle (in radians) in the interval [0, π[ (or a custom interval)
*
* @param float $angle the angle (in radians)
* @param float $min the radians value the angle must be greater or equal than [optional, default value: 0]
* @param float $max the radians value the angle must be strictly lesser than [optional, default value: M_PI]
* @param float $interval the increment interval [optional, default value: 360]
*/
static function normalizeAngle ($angle, $min = 0, $max = M_PI, $interval = M_PI) {
while ($angle < $min) {
$angle += $interval;
}
while ($angle >= $max) {
$angle -= $interval;
}
return $angle;
}
/**
* Normalizes an angle (in degrees) in the interval [0, 360[ (or a custom interval)
*
* @param float $angle the angle to normalize, in degrees
* @param float $min the degrees value the angle must be greater or equal than [optional, default value: 0]
* @param float $max the degrees value the angle must be strictly lesser than [optional, default value: 360]
* @param float $interval the increment interval [optional, default value: 360]
*/
static function normalizeAngleInDegrees ($angle, $min = 0, $max = 360, $interval = 360) {
while ($angle < $min) {
$angle += $interval;
}
while ($angle >= $max) {
$angle -= $interval;
}
return $angle;
}
/**
* Gets the specified angle in radians
*
* @param mixed $angle the angle, a float in radians or a string (a float + "°" or " °" in degrees
* @return float the angle in radians
*/
static function getRadians ($angle) {
return is_numeric($angle) ? $angle : deg2rad((float)$angle);
}
/**
* Gets the specified angle in degrees
*
* @param mixed $angle the angle, a float in radians or a string (a float + "°" or " °" in degrees
* @return string the angle (float) in degrees followed by "°"
*/
static function getDegrees ($angle) {
return is_numeric($angle) ? rad2deg((float)$angle) . '°' : $angle;
}
/**
* Converts a polar coordinate angle to a 0-360° CW angle
*/
static function getNaturalDegrees ($angle) {
return self::normalizeAngleinDegrees(90 - self::getDegrees($angle));
}
//
// Math
//
/**
* Gets the (x, y, z) cartesian coordinates from the current ρ, θ, z polar+z point
*
* @return array an array of 3 floats number, representing the (x, y, z) cartesian coordinates
*/
function toCartesian () {
$x = $this->r * cos(self::getRadians($this->t));
$y = $this->r * sin(self::getRadians($this->t));
- return array($x, $y, $this->z);
+ return [$x, $y, $this->z];
}
/**
* Converts the current GeoPointPolarZ instance to a GeoPoint3D instance
*
* @return GeoPoint3D an instance of the GeoPoint3D class representing the (x, y, z) cartesian coordinates
*/
function toPoint3D () {
$pt = $this->toCartesian();
return new GeoPoint3D($pt[0], $pt[1], $pt[2]);
}
/**
* Gets the (ρ, φ, θ) spherical coordinates from the current (ρ, θ, z) polar+z point
*
* The algo used is from http://fr.wikipedia.org/wiki/Coordonn%C3%A9es_sph%C3%A9riques#Relation_avec_les_autres_syst.C3.A8mes_de_coordonn.C3.A9es_usuels
*
* @return array an array of 3 floats number, representing the (ρ, φ, θ) spherical coordinates
*/
function toSpherical () {
$pt = $this->toCartesian();
return GeoGalaxy::cartesianToSpherical($pt[0], $pt[1], $pt[2]);
}
/**
* Gets the (ρ, φ, θ) spherical coordinates from the current (ρ, θ, z) polar+z point
*
* The algo used is from http://www.phy225.dept.shef.ac.uk/mediawiki/index.php/Cartesian_to_polar_conversion
*
* @return array an array of 3 floats number, representing the (ρ, φ, θ) spherical coordinates
*/
function toSphericalAlternative () {
$pt = $this->toCartesian();
return GeoGalaxy::cartesianToSphericalAlternative($pt[0], $pt[1], $pt[2]);
}
/**
* Translates the center and rescales.
*
* This method allow to help to represent coordinate in a new system
*
* This method is used to represent Zed objects in dojo with the following
* parameters:
* <code>
* $pointKaos = GeoPointPolarZ(800, 42, 220);
* $pointKaos->translate(500, 300, 200, 2);
* echo $pointKaos;
* //This will output rρz: [150, -129, 10]
* </code>
*
* @param float $dr the difference between the old ρ and new ρ (ie the value of ρ = 0 in the new system)
* @param float $dt the difference between the old θ and new θ (ie the value of θ = 0 in the new system)
* @param float $dz the difference between the old y and new z (ie the value of z = 0 in the new system)
* @param int $scale if specified, divides each coordinate by this value (optional)
*/
function translate ($dr, $dt, $dz, $scale = 1) {
if ($scale == 1) {
$this->r += $dr;
$this->t += $dt;
$this->z += $dz;
} elseif ($scale == 0) {
$this->r = 0;
$this->t = 0;
$this->z = 0;
} else {
$this->r = $this->r * $scale + $dr;
$this->t = $this->t * $scale + $dt;
$this->z = $this->z * $scale + $dz;
}
}
/**
* Calculates the section number the specified angle belongs
*
* @param $angle float The natural angle in degree (North 0°, East 90°, etc. clockwise)
* @param int $count the number of sections (default value: 6)
* @return $int the section number
*/
static function calculateSection ($angle, $count = 6) {
if ($angle < 90) {
$angle += 270;
} else {
$angle -= 90;
}
return 1 + (int)($angle / (360/$count));
}
/**
* Gets the section number the θ angle belongs to.
*
* @param int $count the number of sections
* @return $int the section number
*/
function getSection ($count = 6) {
return self::calculateSection(self::getNaturalDegrees($this->t), $count);
}
//
// Implementing IteratorAggregate
//
/**
* Retrieves class iterator. It traverses ρ, θ and z.
*
* @return Traversable the iterator
*/
function getIterator () {
return new ArrayIterator($this);
}
}
diff --git a/includes/geo/scene.php b/includes/geo/scene.php
index 17e51ff..ec0002b 100755
--- a/includes/geo/scene.php
+++ b/includes/geo/scene.php
@@ -1,212 +1,212 @@
<?php
/**
* Geo scene class.
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* @package Zed
* @subpackage Geo
* @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
*/
require_once('location.php');
require_once('octocube.php');
require_once('sceneindex.php');
if (!defined('SCENE_DIR')) {
/**
* The directory containing scenes files
*/
define('SCENE_DIR', 'content/scenes');
}
/**
* Geo scene class
*
* This class provides methods to determine and renders the local scene.
*/
class GeoScene {
/**
* Last error or warning
*
* @var string
*/
public $lastError;
/**
* File scene to serve
*
* @var string
*/
public $sceneFile;
/**
* The location of the scene to print
*
* @var GeoLocation
*/
public $location;
/**
* Initializes a new GeoScene instance
*
* @param GeoLocation $location location the scene is to print
*/
function __construct ($location) {
$this->location = $location;
//Gets local scene
if ($location->containsLocalLocation) {
if ($this->get_local_scene()) return;
}
//Gets global scene
if ($location->containsGlobalLocation) {
if ($this->get_global_scene()) return;
}
//If not scene found, let's set a warning
$this->lastError = "No scene found.";
}
/**
* Gets local scene
*
* @return boolean true if a scene have been found ; otherwise, false.
*/
private function get_local_scene () {
//From the index
$index = GeoSceneIndex::Load(SCENE_DIR);
if ($tpl = $index->get_local_template($this->location->global, $this->location->local)) {
$this->sceneFile = SCENE_DIR . '/' . $tpl;
return true;
}
//From filename
$expression = $this->location->global . ' ' . $this->location->local;
if ($this->try_get_scene($expression)) {
return true;
}
return false;
}
/**
* Gets global scene
*
* @return boolean true if a scene have been found ; otherwise, false.
*/
private function get_global_scene () {
$location = $this->location;
if ($location->place) {
if ($this->try_get_scene($location->global)) {
return true;
}
}
if ($location->body) {
if ($this->try_get_scene('B' . $location->body->code)) {
return true;
}
}
return false;
}
/**
* Gets file extension
*
* @param string $file the file path
* @return string the file extension
*/
public static function get_file_extension ($file) {
$pathinfo = pathinfo($file);
return $pathinfo['extension'];
}
/**
* Renders the file
*
* @todo Add standard code to render .swf Flash/ShockWave files.
*/
public function render () {
if ($file = $this->sceneFile) {
switch ($ext = GeoScene::get_file_extension($file)) {
case 'png':
case 'jpg':
case 'gif':
case 'bmp':
echo "<img src=\"$file\" />";
break;
case 'tpl':
global $smarty, $Config;
$template_dir = $smarty->template_dir;
- $smarty->template_dir = array(getcwd(), $template_dir);
+ $smarty->template_dir = [getcwd(), $template_dir];
//$this->location is the object reference
//Some objects like the hypership move, so we also need to know where there are.
//From the template, this object location is assigned to $location
//To get $this->location from template, use $CurrentPerso->location
if ($this->location->body) {
$smarty->assign("location", new GeoLocation($this->location->body->location));
} elseif ($this->location->ship) {
$smarty->assign("location", new GeoLocation($this->location->ship->location));
}
//Gets zone information
require_once('includes/content/zone.php');
if ($zone = ContentZone::at($this->location->global, $this->location->local)) {
$smarty->assign('zone', $zone);
}
//Scene-specific variables
$smarty->assign("SCENE_URL", defined('SCENE_URL') ? SCENE_URL : '/' . SCENE_DIR);
if ($Config['builder']['hotglue']['enable']) {
$smarty->assign("HOTGLUE", $Config['builder']['hotglue']['URL']);
}
lang_load('scenes.conf', $this->location->global);
//Displays scene, then restores regular settings
$smarty->display($file);
$smarty->template_dir = $template_dir;
break;
case 'php':
message_die(HACK_ERROR, ".php scene files not allowed without review", '', __LINE__, __FILE__);
default:
message_die(GENERAL_ERROR, "Can't handle $ext extension for $file scene", 'GeoScene render error', __LINE__, __FILE__);
}
echo "\n\n";
}
}
/**
* Tries to get the scene file.
*
* It will tries to find in the scene directory a file with $code as name,
* and .tpl .png .gif .bmp .swf .html or .php as extension.
*
* @param string the location code (and filename)
* @return bool true if a scene file have been found and set ; otherwise, false.
*/
private function try_get_scene ($code) {
$file = SCENE_DIR . "/$code";
- $extensions = array('tpl', 'png', 'jpg', 'gif', 'bmp', 'swf', 'html', 'php');
+ $extensions = ['tpl', 'png', 'jpg', 'gif', 'bmp', 'swf', 'html', 'php'];
foreach ($extensions as $ext) {
if (file_exists("$file.$ext")) {
$this->sceneFile = "$file.$ext";
return true;
}
}
return false;
}
}
diff --git a/includes/geo/sceneindex.php b/includes/geo/sceneindex.php
index e1f3cba..e7ac4a1 100755
--- a/includes/geo/sceneindex.php
+++ b/includes/geo/sceneindex.php
@@ -1,218 +1,218 @@
<?php
/**
* Geo scene index class.
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* @package Zed
* @subpackage Geo
* @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
*
* This class implements a singleton pattern.
*/
require_once('includes/cache/cache.php');
/**
* Geo scene class
*
* This class provides an index of available scene template files.
*/
class GeoSceneIndex {
/**
* Global location templates array
*
* Keys are global location codes.
* Values the relevant template file.
*
* @var Array
*/
public $global_templates;
/**
* Local location templates 2D array
*
* Keys are global and local location codes.
* Values the relevant template file.
*
* e.g. $local_templates['B00017001']['(10, 50, 8)'] => 'B00017_port.tpl'
*
* @var Array
*/
public $local_templates;
/**
* Time of the last updated file in the scenes directory
*
* @var int
*/
public $updated;
/**
* The directory where templates are stored
*
* @var string
*/
public $directory;
/**
* The current index instance array
*
* Keys are scene directories (string)
* Items are GeoSceneIndex instances
*
* @var Array
*/
- static $instance = array();
+ static $instance = [];
/**
* Gets the index instance, initializing it if needed
*
* @return index the index instance
*/
static function load ($directory) {
//Creates the index object if needed
if (!array_key_exists($directory, self::$instance)) {
self::$instance[$directory] = new GeoSceneIndex($directory);
}
return self::$instance[$directory];
}
/**
* Initializes a new GeoSceneIndex instance
*
* @param string $directory the scene templates directory
*/
public function __construct ($directory) {
$this->directory = $directory;
if (!$this->get_cached_information() || !$this->is_up_to_date()) {
$this->refresh_information();
$this->set_cached_information();
}
}
/**
* Caches index data
*/
public function set_cached_information () {
$cache = Cache::load();
$cache->set('zed_sceneindex', serialize($this));
}
/**
* Gets index from cache
*/
public function get_cached_information () {
$cache = Cache::load();
$cached_index =$cache->get('zed_sceneindex');
if ($index = unserialize($cache->get('zed_sceneindex'))) {
$index = unserialize($cache->get('zed_sceneindex'));
$this->global_templates = $index->global_templates;
$this->local_templates = $index->local_templates;
$this->updated = $index->updated;
$this->directory = $index->directory;
return true;
}
return false;
}
/**
* Reads scene templates and indexes information
*/
public function refresh_information () {
- $this->global_templates = array();
- $this->local_templates = array();
+ $this->global_templates = [];
+ $this->local_templates = [];
$this->updated = filemtime($this->directory);
if ($handle = opendir($this->directory)) {
while (false !== ($file = readdir($handle))) {
if (GeoScene::get_file_extension($file) == 'tpl') {
$template = file_get_contents($this->directory . '/' . $file, false, NULL, 0, 1024);
$location = self::get_template_location($template);
if ($location[1] !== NULL) {
$this->local_templates[$location[0]][$location[1]] = $file;
} elseif ($location[0] != NULL) {
$this->global_templates[$location[0]] = $file;
}
}
}
closedir($handle);
}
}
/**
* Determines if the information is still up to date
*
* @return bool true if the information is up to date ; otherwise, false.
*/
public function is_up_to_date () {
return ($this->updated == filemtime($this->directory));
}
/**
* Gets template location
*
* @return Array an string array of the location (two items; global, local)
* At key 0, a string with global location, or NULL if not specified
* At key 1, a string with local location, or NULL if not specified
*/
private static function get_template_location ($template) {
- $location = array(NULL, NULL);
+ $location = [NULL, NULL];
//Gets global location
$pos1 = strpos($template, "Global location: ");
if ($pos1 === false) {
throw new Exception("No location in template. Any template file must contain a comment line with the string 'Global location: ' followed by the global location matching the template. It should also contains a line 'Local location: ' when applicable.");
}
$pos1 += 17;
$pos2 = strpos($template, "\n", $pos1);
$location[0] = trim(substr($template, $pos1, $pos2 - $pos1));
//Gets local location
$pos1 = strpos($template, "Local location: ");
if ($pos1 !== false) {
$pos1 += 16;
$pos2 = strpos($template, "\n", $pos1);
$location[1] = trim(substr($template, $pos1, $pos2 - $pos1));
}
return $location;
}
/**
* Gets local template file from index
*
* @param string $location_global the global location
* @param string $location_global the local location
* @return string the relevant template scene file, or NULL if not existing
*/
public function get_local_template ($location_global, $location_local) {
if (isset($this->local_templates[$location_global][$location_local])) {
return $this->local_templates[$location_global][$location_local];
}
return NULL;
}
/**
* Gets global template file from index
*
* @param string $location_global the global location
* @return string the relevant template scene file, or NULL if not existing
*/
public function get_global_template ($location_global) {
if (isset($this->global_templates[$location_global])) {
return $this->global_templates[$location_global];
}
return NULL;
}
}
diff --git a/includes/login.php b/includes/login.php
index a3b806c..b9eb79a 100755
--- a/includes/login.php
+++ b/includes/login.php
@@ -1,156 +1,156 @@
<?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
///
$useOpenID = isset($Config['OpenID']) && $Config['OpenID'];
if ($useOpenID) {
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, completes the OpenID transaction
//and processes the result.
if (!$useOpenID()) {
header("Status: 403 Forbidden");
die("OpenID disabled.");
}
$consumer = get_openid_consumer();
$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'] && $useOpenID) {
//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();
+ $authentications = [];
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/content.php b/includes/objects/content.php
index 5560ba6..b501776 100755
--- a/includes/objects/content.php
+++ b/includes/objects/content.php
@@ -1,302 +1,302 @@
<?php
/**
* Content class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2010-02-24 15:57 Autogenerated by Pluton Scaffolding
*
* @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
*
* @deprecated
*/
/**
* Content class
*
* This class maps the content view.
*
* This view shows the content_files and content_locations tables.
*
* This class also provides helper methods, to handle files, generate thumbnails
* or get local content from a specific location.
*
* [DESIGN BY CONTRACT] This class works only with the following assertions:
* i. Each content have EXACTLY ONE location
* ii. Location fields will not be modified
*
* If a content have more than one location, only the first occurrence in
* content_locations table will be considered.
*
* If a content have no location, it will be ignored.
*
* If you edit content location, then call saveToDatabase, you will create
* a new location but future instances will contain first not deleted location.
*
* @todo remove dbc temporary limitations (cf. /do.php upload_content and infra)
* @todo create a class ContentLocation and move location fields there
* @todo validate SQL schema and add in config.php TABLE_CONTENT tables
*
* @deprecated
*/
class Content {
/* -------------------------------------------------------------
Properties
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
public $id;
public $path;
public $user_id;
public $perso_id;
public $title;
public $location_global = null;
public $location_local = null;
public $location_k = null;
public $perso_name;
public $perso_nickname;
/* -------------------------------------------------------------
Constructor, __toString
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/**
* Initializes a new Content instance
*
* @param int $id the primary key
*/
function __construct ($id = null) {
if ($id) {
$this->id = $id;
$this->load_from_database();
}
}
/**
* Returns a string representation of current Content instance
*
* @return string the content title or path if title is blank.
*/
function __toString () {
return $this->title ? $this->title : $this->path;
}
/* -------------------------------------------------------------
Load/save class
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/**
* Loads the object Content (ie fill the properties) from the $_POST array
*
* @param boolean $allowSensibleFields if false, allow only location_local, location_k and title to be defined ; otherwise, allow all fields.
*/
function load_from_form ($allowSensibleFields = false) {
if (array_key_exists('title', $_POST)) $this->title = $_POST['title'];
if (array_key_exists('location_local', $_POST)) $this->location_local = $_POST['location_local'];
if (array_key_exists('location_k', $_POST)) $this->location_k = $_POST['location_k'];
if ($allowSensibleFields) {
if (array_key_exists('path', $_POST)) $this->path = $_POST['path'];
if (array_key_exists('user_id', $_POST)) $this->user_id = $_POST['user_id'];
if (array_key_exists('perso_id', $_POST)) $this->perso_id = $_POST['perso_id'];
if (array_key_exists('location_global', $_POST)) $this->location_global = $_POST['location_global'];
}
}
/**
* Loads the object Content (ie fill the properties) from the database
*/
function load_from_database () {
global $db;
$id = $db->sql_escape($this->id);
$sql = "SELECT * FROM content WHERE content_id = '" . $id . "'";
if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Unable to query content", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
$this->lastError = "Content unknown: " . $this->id;
return false;
}
$this->load_from_row($row);
return true;
}
/**
* Loads the object from row
*/
function load_from_row ($row) {
$this->id = $row['content_id'];
$this->path = $row['content_path'];
$this->user_id = $row['user_id'];
$this->perso_id = $row['perso_id'];
$this->title = $row['content_title'];
$this->location_global = $row['location_global'];
$this->location_local = $row['location_local'];
$this->location_k = $row['location_k'];
if (array_key_exists('perso_name', $row)) $this->perso_name = $row['perso_name'];
if (array_key_exists('perso_nickname', $row)) $this->perso_nickname = $row['perso_nickname'];
}
/**
* Saves to database
*/
function save_to_database () {
global $db;
$id = $this->id ? "'" . $db->sql_escape($this->id) . "'" : 'NULL';
$path = $db->sql_escape($this->path);
$user_id = $db->sql_escape($this->user_id);
$perso_id = $db->sql_escape($this->perso_id);
$title = $db->sql_escape($this->title);
$location_global = ($this->location_global !== null) ? "'" . $db->sql_escape($this->location_global) . "'" : 'NULL';
$location_local = ($this->location_local !== null) ? "'" . $db->sql_escape($this->location_local) . "'" : 'NULL';
$location_k = ($this->location_k !== null) ? "'" . $db->sql_escape($this->location_k) . "'" : 'NULL';
//Updates or inserts
$sql = "REPLACE INTO content_files (`content_id`, `content_path`, `user_id`, `perso_id`, `content_title`) VALUES ($id, '$path', '$user_id', '$perso_id', '$title')";
if (!$db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't save content", '', __LINE__, __FILE__, $sql);
}
if (!$this->id) {
//Gets new record id value
$this->id = $db->sql_nextid();
}
//Saves location
$id = $this->id ? "'" . $db->sql_escape($this->id) . "'" : 'NULL';
$sql = "REPLACE INTO content_locations (location_global, location_local, location_k, content_id) VALUES ($location_global, $location_local, $location_k, $id)";
if (!$db->sql_query($sql))
message_die(SQL_ERROR, "Can't save content location", '', __LINE__, __FILE__, $sql);
}
/* -------------------------------------------------------------
File handling helper methods
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/**
* Determines if the extension is valid
*
* @param string $ext The extension (without dot)
* @return boolean true if this extension is valid ; otherwise, false.
*/
function is_valid_extension ($ext) {
switch ($ext = strtolower($ext)) {
//Pictures
case 'jpg':
case 'gif':
case 'png':
case 'bmp':
case 'xbm':
return true;
//Denied extension
default:
return false;
}
}
/**
* Creates a directory
*
* @param string $dir the directory to create
*/
function create_directory ($directory) {
if (!file_exists($directory)) {
@mkdir($directory); //Creates new directory, chmod 777
}
}
/**
* Handles uploaded file
*
* @return bool true if the file have been handled
*/
function handle_uploaded_file ($fileArray) {
if (count($fileArray) && $fileArray['error'] == 0) {
$this->create_directory("content/users/$this->user_id");
$this->path = "content/users/$this->user_id/$fileArray[name]";
if (!self::is_valid_extension(get_extension($fileArray[name]))) {
return false;
}
if (move_uploaded_file($fileArray['tmp_name'], $this->path)) {
return true;
} else {
$this->path = null;
return false;
}
} else {
return false;
}
}
/**
* Generates a thumbnail using ImageMagick binary
*
* @return boolean true if the thumbnail command returns 0 as program exit code ; otherwise, false
*/
function generate_thumbnail () {
global $Config;
//Builds thumbnail filename
$sourceFile = $this->path;
$pos = strrpos($this->path, '.');
$thumbnailFile = substr($sourceFile, 0, $pos) . 'Square' . substr($sourceFile, $pos);
//Executes imagemagick command
$command = $Config['ImageMagick']['convert'] . " \"$sourceFile\" -resize 162x162 \"$thumbnailFile\"";
@system($command, $code);
//Returns true if the command have exited with errorcode 0 (= ok)
return ($code == 0);
}
/* -------------------------------------------------------------
Gets content
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - */
/**
* Gets content at specified location
*
* @param string $location_global global content location
* @param string $location_local local content location
* @return Array array of Content instances
*/
static function get_local_content ($location_global, $location_local) {
global $db;
//Get contents at this location
$location_global = $db->sql_escape($location_global);
$location_local = $db->sql_escape($location_local);
$sql = "SELECT c.*, p.perso_nickname, p.perso_name FROM content c, persos p WHERE c.location_global = '$location_global' AND c.location_local = '$location_local' AND p.perso_id = c.perso_id ORDER BY location_k ASC";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't get content", '', __LINE__, __FILE__, $sql);
}
//Fills content array
- $contents = array();
+ $contents = [];
while ($row = $db->sql_fetchrow($result)) {
$content = new Content();
$content->load_from_row($row);
$contents[] = $content;
}
return $contents;
}
}
diff --git a/includes/objects/invite.php b/includes/objects/invite.php
index 995096e..de03309 100755
--- a/includes/objects/invite.php
+++ b/includes/objects/invite.php
@@ -1,197 +1,197 @@
<?php
/**
* User invite class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2010-06-29 02:13 Initial version [DcK]
*
* @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 invite class
*
* This class maps the users_invites table.
*/
class Invite {
public $code;
public $date;
public $from_user_id;
public $from_perso_id;
/**
* The user_id who have been claimed the invite
* Will be NULL as long as the invite haven't been claimed
*
* @var int
*/
public $to_user_id = NULL;
/**
* Initializes a new instance
*
* @param int $code the primary key
*/
function __construct ($code = NULL) {
if ($code) {
$this->code = $code;
$this->load_from_database();
} else {
//New invite code
$this->generate_code();
$this->date = time();
}
}
/**
* Generates a unique invite code and sets it in the code property.
*/
function generate_code () {
global $db;
do {
$this->code = generate_random_string("AAA111");
$sql = "SELECT COUNT(*) FROM " . TABLE_USERS_INVITES . " WHERE invite_code = '$this->code' LOCK IN SHARE MODE;";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't access invite users table", '', __LINE__, __FILE__, $sql);
}
$row = $db->sql_fetchrow($result);
} while ($row[0]);
}
/**
* Loads the object Invite (ie fill the properties) from the database
*/
function load_from_database () {
global $db;
$code = $db->sql_escape($this->code);
$sql = "SELECT * FROM " . TABLE_USERS_INVITES . " WHERE invite_code = '" . $code . "'";
if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Unable to query invite codes", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
$this->lastError = "Invite code unknown: " . $this->code;
return false;
}
$this->code = $row['invite_code'];
$this->date = $row['invite_date'];
$this->from_user_id = $row['invite_from_user_id'];
$this->from_perso_id = $row['invite_from_perso_id'];
$this->to_user_id = $row['invite_to_user_id'];
return true;
}
/**
* Determines whether the current invite code have been claimed by an user.
*
* @return true if the code have been claimed ; otherwise, false.
*/
function is_claimed () {
return (bool)$this->to_user_id;
}
/**
* Saves to database
*/
function save_to_database () {
global $db;
$code = $db->sql_escape($this->code);
$date = $db->sql_escape($this->date);
$from_user_id = $db->sql_escape($this->from_user_id);
$from_perso_id = $db->sql_escape($this->from_perso_id);
$to_user_id = $this->to_user_id ? "'" . $db->sql_escape($this->to_user_id) . "'" : 'NULL';
//Updates or inserts
$sql = "REPLACE INTO " . TABLE_USERS_INVITES . " (`invite_code`, `invite_date`, `invite_from_user_id`, `invite_from_perso_id`, `invite_to_user_id`) VALUES ('$code', '$date', '$from_user_id', '$from_perso_id', $to_user_id)";
if (!$db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to save invite code", '', __LINE__, __FILE__, $sql);
}
}
/**
* Deletes the invite
*/
function delete () {
global $db;
$code = $db->sql_escape($this->code);
$sql = "DELETE FROM " . TABLE_USERS_INVITES . " WHERE invite_code = '$code'";
if (!$db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to save delete code", '', __LINE__, __FILE__, $sql);
}
}
/**
* Creates an invite code
*
* @param int $user_id user id
* @param int $perso_id perso id
* @return string the invite code
*/
static function create ($user_id, $perso_id) {
$invite = new Invite();
$invite->from_perso_id = $perso_id;
$invite->from_user_id = $user_id;
$invite->save_to_database();
return $invite->code;
}
/**
* Gets invites generated by the specified perso ID
*
* @param int $perso_id the perso whom to get the invites
* @return Array an array of string, each line being an invite code
*/
static function get_invites_from ($perso_id) {
global $db;
$sql = "SELECT invite_code FROM " . TABLE_USERS_INVITES
. " WHERE invite_from_perso_id = $perso_id AND invite_to_user_id IS NULL ORDER BY invite_date ASC";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't access invite users table", '', __LINE__, __FILE__, $sql);
}
- $codes = array();
+ $codes = [];
while ($row = $db->sql_fetchrow($result)) {
$codes[] = $row['invite_code'];
}
return $codes;
}
/**
* Gets the perso ID who invited the specified perso
*
* @param int $perso_id the perso whom to get the invites
* @return int|null the perso whom to get the invites ; or null, if nobody have invited him
*/
static function who_invited ($perso_id) {
global $db;
$perso = Perso::get($perso_id);
if ($user_id = $perso->user_id) {
$sql = "SELECT invite_from_perso_id FROM " . TABLE_USERS_INVITES . " WHERE invite_to_user_id = '$user_id'";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't access invite users table", '', __LINE__, __FILE__, $sql);
}
if ($row = $db->sql_fetchrow($result)) {
return $row[0];
}
}
return null;
}
}
?>
diff --git a/includes/objects/perso.php b/includes/objects/perso.php
index bd07c49..8884bcc 100755
--- a/includes/objects/perso.php
+++ b/includes/objects/perso.php
@@ -1,579 +1,579 @@
<?php
/**
* Perso class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2010-01-27 00:39 Autogenerated by Pluton Scaffolding
* 0.2 2010-01-29 14:39 Adding flags support
* 0.3 2010-02-06 17:50 Adding static perso hashtable
* 0.4 2012-07-04 11:37 Refactoring: moving code from index.php
*
* @package Zed
* @subpackage Model
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @copyright 2010, 2012 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
*/
require_once("includes/geo/location.php");
/**
* Perso class
*
* This class maps the persos table.
*
* The class also provides methods
* to move or locate a perso,
* to gets and sets perso's flags and notes (tables persos_flags and persos_notes),
* to gets user's perso or check if a perso is online,
* to handle on select and logout events.
*
*/
class Perso {
public $id;
public $user_id;
public $name;
public $nickname;
public $race;
public $sex;
public $avatar;
public $location_global;
public $location_local;
public $flags;
public $lastError;
- public static $hashtable_id = array();
- public static $hashtable_name = array();
+ public static $hashtable_id = [];
+ public static $hashtable_name = [];
/**
* Initializes a new instance
*
* @param mixed $data perso ID or nickname
*/
function __construct ($data = null) {
if ($data) {
if (is_numeric($data)) {
$this->id = $data;
} else {
$this->nickname = $data;
}
if (!$this->load_from_database()) {
message_die(GENERAL_ERROR, $this->lastError, "Can't authenticate perso");
}
} else {
$this->generate_id();
}
}
/**
* Initializes a new Perso instance if needed or get already available one.
*
* @param mixed $data perso ID or nickname
* @return Perso the perso 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, Perso::$hashtable_id)) {
return Perso::$hashtable_id[$data];
}
} else {
if (array_key_exists($data, Perso::$hashtable_name)) {
return Perso::$hashtable_name[$data];
}
}
}
$perso = new Perso($data);
return $perso;
}
/**
* Loads the object Perso (ie fill the properties) from the $_POST array
*/
function load_from_form () {
if (array_key_exists('user_id', $_POST)) $this->user_id = $_POST['user_id'];
if (array_key_exists('name', $_POST)) $this->name = $_POST['name'];
if (array_key_exists('nickname', $_POST)) $this->nickname = $_POST['nickname'];
if (array_key_exists('race', $_POST)) $this->race = $_POST['race'];
if (array_key_exists('sex', $_POST)) $this->sex = $_POST['sex'];
if (array_key_exists('avatar', $_POST)) $this->avatar = $_POST['avatar'];
if (array_key_exists('location_global', $_POST)) $this->location_global = $_POST['location_global'];
if (array_key_exists('location_local', $_POST)) $this->location_local = $_POST['location_local'];
}
/**
* Loads the object Perso (ie fill the properties) from the database
*/
function load_from_database () {
global $db;
//Gets perso
$sql = "SELECT * FROM " . TABLE_PERSOS;
if ($this->id) {
$id = $db->sql_escape($this->id);
$sql .= " WHERE perso_id = '" . $id . "'";
} else {
$nickname = $db->sql_escape($this->nickname);
$sql .= " WHERE perso_nickname = '" . $nickname . "'";
}
if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Unable to query persos", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
$this->lastError = "Perso unknown: " . $this->id;
return false;
}
$this->id = $row['perso_id'];
$this->user_id = $row['user_id'];
$this->name = $row['perso_name'];
$this->nickname = $row['perso_nickname'];
$this->race = $row['perso_race'];
$this->sex = $row['perso_sex'];
$this->avatar = $row['perso_avatar'];
$this->location_global = $row['location_global'];
$this->location_local = $row['location_local'];
//Gets flags
$sql = "SELECT flag_key, flag_value FROM " . TABLE_PERSOS_FLAGS .
" WHERE perso_id = $this->id";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't get flags", '', __LINE__, __FILE__, $sql);
}
while ($row = $db->sql_fetchrow($result)) {
$this->flags[$row["flag_key"]] = $row["flag_value"];
}
//Gets location
$this->location = new GeoLocation(
$this->location_global,
$this->location_local
);
//Puts object in hashtables
Perso::$hashtable_id[$this->id] = $this;
Perso::$hashtable_name[$this->nickname] = $this;
return true;
}
/**
* Saves to database
*/
function save_to_database () {
global $db;
$id = $this->id ? "'" . $db->sql_escape($this->id) . "'" : 'NULL';
$user_id = $db->sql_escape($this->user_id);
$name = $db->sql_escape($this->name);
$nickname = $db->sql_escape($this->nickname);
$race = $db->sql_escape($this->race);
$sex = $db->sql_escape($this->sex);
$avatar = $db->sql_escape($this->avatar);
$location_global = $this->location_global ? "'" . $db->sql_escape($this->location_global) . "'" : 'NULL';
$location_local = $this->location_local ? "'" . $db->sql_escape($this->location_local) . "'" : 'NULL';
//Updates or inserts
$sql = "REPLACE INTO " . TABLE_PERSOS . " (`perso_id`, `user_id`, `perso_name`, `perso_nickname`, `perso_race`, `perso_sex`, `perso_avatar`, `location_global`, `location_local`) VALUES ($id, '$user_id', '$name', '$nickname', '$race', '$sex', '$avatar', $location_global, $location_local)";
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
*
* @param string $field The field to save
*/
function save_field ($field) {
global $db;
if (!$this->id) {
message_die(GENERAL_ERROR, "You're trying to update a perso record not yet saved in the database: $field");
}
$id = $db->sql_escape($this->id);
$value = $db->sql_escape($this->$field);
$sql = "UPDATE " . TABLE_PERSOS . " SET `$field` = '$value' WHERE perso_id = '$id'";
if (!$db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to save $field field", '', __LINE__, __FILE__, $sql);
}
}
/**
* Gets perso location
*
* @return string The location names
*/
public function where () {
return $this->location->__toString();
}
/**
* Moves the perso to a new location
*
* @param string $global the global target location
* @param string $global the local target location
*/
public function move_to ($global = null, $local = null) {
//Sets global location
if ($global != null) {
$this->location_global = $global;
}
//Sets local location
if ($local != null) {
$this->location_local = $local;
}
//Updates database record
if ($global != null && $local != null) {
global $db;
$perso_id = $db->sql_escape($this->id);
$g = $db->sql_escape($this->location_global);
$l = $db->sql_escape($this->location_local);
$sql = "UPDATE " . TABLE_PERSOS .
" SET location_global = '$g', location_local = '$l'" .
" WHERE perso_id = '$perso_id'";
if (!$db->sql_query($sql))
message_die(SQL_ERROR, "Can't save new $global $local location.", '', __LINE__, __FILE__, $sql);
} elseif ($global != null) {
$this->save_field('location_global');
} elseif ($local != null) {
$this->save_field('location_local');
}
//Updates location member
$this->location = new GeoLocation(
$this->location_global,
$this->location_local
);
}
/**
* Gets the specified flag value
*
* @param string $key flag key
* @param mixed $defaultValue default value if the flag doesn't exist
* @return mixed the flag value (string) or null if not existing
*/
public function get_flag ($key, $defaultValue = null) {
return $this->flag_exists($key) ? $this->flags[$key] : $defaultValue;
}
/**
* Determines if the specified flag exists
*
* @param string $key the flag key to check
* @return boolean true if the specified flag exists ; otherwise, false.
*/
public function flag_exists ($key) {
return array_key_exists($key, $this->flags);
}
/**
* Sets the specified flag
*
* @param string $key flag key
* @param string $value flag value (optional, default value: 1)
*/
public function set_flag ($key, $value = 1) {
//Checks if flag isn't already set at this value
if ($this->flags != null && array_key_exists($key, $this->flags) && $this->flags[$key] === $value)
return;
//Saves flag to database
global $db;
$id = $db->sql_escape($this->id);
$key = $db->sql_escape($key);
$value = $db->sql_escape($value);
$sql = "REPLACE " . TABLE_PERSOS_FLAGS . " SET perso_id = '$id', flag_key = '$key', flag_value = '$value'";
if (!$db->sql_query($sql))
message_die(SQL_ERROR, "Can't save flag", '', __LINE__, __FILE__, $sql);
//Sets flag in this perso instance
$this->flags[$key] = $value;
}
/**
* Deletes the specified flag
*
* @param string $key flag key
*/
public function delete_flag ($key) {
global $db;
if (!array_key_exists($key, $this->flags)) return;
$id = $db->sql_escape($this->id);
$key = $db->sql_escape($key);
$sql = "DELETE FROM " . TABLE_PERSOS_FLAGS .
" WHERE flag_key = '$key' AND perso_id = '$id' LIMIT 1";
if (!$db->sql_query($sql))
message_die(SQL_ERROR, "Can't delete flag", '', __LINE__, __FILE__, $sql);
}
/**
* Ensures the current perso have the specified flag or exits.
*
*
* @param string $flag the flag to assert
* @param int $threshold value the flags must strictly be greater than (optional, the default value is 0)
*
* Example:
* <code>
* $perso->set_flag('quux.foo', 1);
* //The perso wants to read quux, which we allow with the flag quux.foo
* $perso->request_flag('quux.foo'); //will be okay
*
* //The perso wants also to write quux, which we all allow if quux.foo = 2
* //The threshold will so be 1, as 2 > 1
* $perso->request_flag('quux.foo', 1); //Will exits, with a "You don't have quux.foo permission" message
* </code>
*/
public function request_flag ($flag, $threshold = 0) {
if (!array_key_exists($flag, $this->flags) || $this->flags[$flag] <= $threshold) {
message_die(HACK_ERROR, "You don't have $flag permission.", "Permissions");
}
}
/**
* Gets the specified note
*
* @param string $code the note code
* @return string the note content
*/
public function get_note ($code) {
global $db;
$id = $db->sql_escape($this->id);
$code = $db->sql_escape($code);
$sql = "SELECT note_text FROM " . TABLE_PERSOS_NOTES . " WHERE perso_id = '$id' AND note_code LIKE '$code'";
return $db->sql_query_express($sql);
}
/**
* Sets the specified note
*
* @param string $code the note code
* @param string $text the note content
*/
public function set_note ($code, $text) {
global $db;
$id = $db->sql_escape($this->id);
$code = $db->sql_escape($code);
$text = $db->sql_escape($text);
$sql = "REPLACE INTO " . TABLE_PERSOS_NOTES . " (perso_id, note_code, note_text) VALUES ('$id', '$code', '$text')";
if (!$db->sql_query($sql))
message_die(SQL_ERROR, "Can't save note", '', __LINE__, __FILE__, $sql);
}
/**
* Counts the amount of notes the perso have saved
*
* @return int the amount of notes assigned to the this perso
*/
public function count_notes () {
global $db;
$id = $db->sql_escape($this->id);
$sql = "SELECT COUNT(*) FROM " . TABLE_PERSOS_NOTES . " WHERE perso_id = '$id'";
return $db->sql_query_express($sql);
}
/*
* Determines if the specified ID is available
*
* @param integer $id The perso ID to check
* @return boolean true if the specified ID is available ; otherwise, false
*/
public static function is_available_id ($id) {
global $db;
$sql = "SELECT COUNT(*) FROM " . TABLE_PERSOS . " WHERE perso_id = $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);
return ($row[0] == 0);
}
/**
* Generates a unique ID for the current object
*/
private function generate_id () {
do {
$this->id = rand(2001, 5999);
} while (!Perso::is_available_id($this->id));
}
/**
* Checks if the nickname is available
*
* @param string $nickname the nickname to check
*/
public static function is_available_nickname ($nickname) {
global $db;
$nickname = $db->sql_escape($nickname);
$sql = "SELECT COUNT(*) FROM " . TABLE_PERSOS . " WHERE perso_nickname LIKE '$nickname' 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] == 0);
}
/**
* Counts the perso a user have
*
* @param int user_id the user ID
* @return the user's perso count
*/
public static function get_persos_count ($user_id) {
global $db;
$sql = "SELECT COUNT(*) FROM " . TABLE_PERSOS . " WHERE user_id = $user_id";
return $db->sql_query_express($sql);
}
/**
* Gets an array with all the perso of the specified user
*
* @param int $user_id the user ID
*/
public static function get_persos ($user_id) {
global $db;
$user_id = $db->sql_escape($user_id);
$sql = "SELECT perso_id FROM " . TABLE_PERSOS . " WHERE user_id = $user_id";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't get persos", '', __LINE__, __FILE__, $sql);
}
while ($row = $db->sql_fetchrow($result)) {
$persos[] = Perso::get($row[perso_id]);
}
return $persos;
}
/**
* Gets the first perso a user have
* (typically to be used when get_persos_count returns 1 to autoselect)
*
* @param int user_id the user ID
*/
public static function get_first_perso ($user_id) {
global $db;
$sql = "SELECT perso_id FROM " . TABLE_PERSOS ." WHERE user_id = $user_id LIMIT 1";
if ($perso_id = $db->sql_query_express($sql)) {
return new Perso($perso_id);
}
}
/**
* Determines whether the perso is online
*
* @return bool true if the perso is online ; otherwise, false.
*/
public function is_online () {
global $db;
$id = $db->sql_escape($this->id);
$sql = "SELECT MAX(online) FROM " . TABLE_SESSIONS ." WHERE perso_id = $id";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to query the table", '', __LINE__, __FILE__, $sql);
}
$row = $db->sql_fetchrow($result);
return ($row[0] == 1);
}
/**
* This event method is called when the user selects a new perso
*/
public function on_select () {
//Session
set_info('perso_id', $this->id);
$this->set_flag("site.lastlogin", $_SERVER['REQUEST_TIME']);
define("PersoSelected", true);
}
/**
* This event method is called when the user logs off its account or perso
*/
public function on_logout () {
//Clears perso information in $_SESSION and session table
set_info('perso_id', null);
clean_session();
}
/**
* This event method is called when the perso is created
*/
public function on_create () {
//Notifies host
$this->notify_inviter();
}
/**
* Creates a new perso, from a parameter form
*
* @param int $user The user to attach the perso to
* @param Perso $perso A reference to the created perso (don't initialize it, give it a null value)
* @param array $errors A reference to the arrays containing errors (should be an empty array, or the method will always return false)
* @return boolean true if the perso has ben created ; otherwise, false
*/
public static function create_perso_from_form ($user, &$perso, &$errors) {
$perso = new Perso();
$perso->load_from_form();
$perso->user_id = $user->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");
} elseif (!Perso::is_available_nickname($perso->nickname)) {
$errors[] = lang_get("UnavailableNickname");
}
if (count($errors)) return false;
//Creates perso
$perso->save_to_database();
$perso->on_create();
return true;
}
/**
* Notifies the person having invited this perso
*/
public function notify_inviter() {
require_once('includes/objects/message.php');
require_once('includes/objects/invite.php');
$message = new Message();
$message->from = 0;
$message->to = invite::who_invited($this->id);
$message->text = sprintf(
lang_get('InvitePersoCreated'),
$this->name,
get_server_url() . get_url('who', $this->nickname)
);
$message->send();
}
}
diff --git a/includes/objects/port.php b/includes/objects/port.php
index ba0b664..004ed92 100755
--- a/includes/objects/port.php
+++ b/includes/objects/port.php
@@ -1,197 +1,197 @@
<?php
/**
* Port class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2010-02-09 19:17 Autogenerated by Pluton Scaffolding
*
* @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
*/
require_once("includes/geo/location.php");
/**
* Port class
*
* This class maps the ports table.
*
* The class also provides helper methods to handle ports at specified location.
*/
class Port {
public $id;
public $location_global;
public $location_local;
public $name;
public $hidden;
public $requiresPTA;
public $default;
/**
* Initializes a new instance
* @param int $id the primary key
*/
function __construct ($id = NULL) {
if ($id) {
$this->id = $id;
$this->load_from_database();
}
}
/**
* Loads the object Port (ie fill the properties) from the $_POST array
*/
function load_from_form () {
if (array_key_exists('location_global', $_POST)) $this->location_global = $_POST['location_global'];
if (array_key_exists('location_local', $_POST)) $this->location_local = $_POST['location_local'];
if (array_key_exists('name', $_POST)) $this->name = $_POST['name'];
if (array_key_exists('hidden', $_POST)) $this->hidden = $_POST['hidden'] ? true : false;
if (array_key_exists('requiresPTA', $_POST)) $this->requiresPTA = $_POST['requiresPTA'] ? true : false;
if (array_key_exists('default', $_POST)) $this->hidden = $_POST['default'] ? true : false;
}
/**
* Loads the object Port (ie fill the properties) from the database
*/
function load_from_database () {
global $db;
$id = $db->sql_escape($this->id);
$sql = "SELECT * FROM " . TABLE_PORTS . " WHERE port_id = '" . $id . "'";
if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Unable to query ports", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
$this->lastError = "Port unknown: " . $this->id;
return false;
}
$this->location_global = $row['location_global'];
$this->location_local = $row['location_local'];
$this->name = $row['port_name'];
//Explodes place_status SET field in boolean variables
if ($row['place_status']) {
$flags = explode(',', $row['port_status']);
foreach ($flags as $flag) {
$this->$flag = true;
}
}
return true;
}
/**
* Gets status field value
*
* @return string the status field value (e.g. "requiresPTA,default")
*/
function getStatus () {
- $flags = array('hidden', 'requiresPTA', 'default');
+ $flags = ['hidden', 'requiresPTA', 'default'];
foreach ($flags as $flag) {
if ($this->$flag) {
$status[] = $flag;
}
}
return implode(',', $status);
}
/**
* Saves to database
*/
function save_to_database () {
global $db;
$id = $this->id ? "'" . $db->sql_escape($this->id) . "'" : 'NULL';
$location_global = $db->sql_escape($this->location_global);
$location_local = $db->sql_escape($this->location_local);
$name = $db->sql_escape($this->name);
$status = $this->getStatus();
//Updates or inserts
$sql = "REPLACE INTO " . TABLE_PORTS . " (`port_id`, `location_global`, `location_local`, `port_name`, `port_status`) VALUES ($id, '$location_global', '$location_local', '$name', '$status')";
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();
}
}
/**
* Determines if the specified location have a port
*
* @param string $location_global the global location
* @return boolean true if there is a spatioport exactly at the specified location ; otherwise, false.
*/
static function have_port ($location_global) {
return (get_port_id($location_global) !== NULL);
}
/**
* Gets the port situated exactly at the specified global location
*
* @param string $location_global the global location
* @return int the port ID
*/
static function get_port_id ($location_global) {
global $db;
$location_global = $db->sql_escape($location_global);
$sql = "SELECT port_id FROM " . TABLE_PORTS . " WHERE location_global = '$location_global'";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to get ports", '', __LINE__, __FILE__, $sql);
}
if ($row = $db->sql_fetchrow($result)) {
return $row['port_id'];
}
return null;
}
/**
* Gets default port, from specified global location
*
* @param string $location_global the global location
* @return Port the port near this location ; null if there isn't port there.
*/
static function from_location ($location_global) {
$havePlace = strlen($location_global) == 9;
$port_id = null;
if ($havePlace) {
//Checks if there's a port at specified location
$port_id = self::get_port_id($location_global);
}
if ($port_id == null) {
//Nearest default port.
//If place have been specified (B0001001), we've to found elsewhere
//==> B00001%
global $db;
$loc = $db->sql_escape(substr($location_global, 0, 6));
$sql = "SELECT port_id FROM " . TABLE_PORTS . " WHERE location_global LIKE '$loc%'";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't get port", '', __LINE__, __FILE__, $sql);
}
if ($row = $db->sql_fetchrow($result)) {
$port_id = $row['port_id'];
} else {
return null;
}
}
return new Port($port_id);
}
}
diff --git a/includes/objects/profile.php b/includes/objects/profile.php
index 0d35852..cbe0c01 100755
--- a/includes/objects/profile.php
+++ b/includes/objects/profile.php
@@ -1,146 +1,146 @@
<?php
/**
* Profile class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2010-01-02 16:49 Autogenerated by Pluton Scaffolding
* Import from Azhàr
* 0.2 2010-07-05 03:56 Tags
*
* @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
*/
/**
* Profile class
*
* This class maps the profiles table.
*
* The class also provides methods to handle and cache tags.
*/
class Profile {
public $perso_id;
public $text;
public $updated;
public $fixedwidth;
/**
* Initializes a new instance of the Profile class
*
* @param int $perso_id the perso ID
*/
function __construct ($perso_id) {
$this->perso_id = $perso_id;
$this->load_from_database();
}
/**
* Loads the object Profile (ie fill the properties) from the $_POST array
*/
function load_from_form ($read_boolean = true) {
if (array_key_exists('perso_id', $_POST)) $this->perso_id = $_POST['perso_id'];
if (array_key_exists('text', $_POST)) $this->text = $_POST['text'];
if (array_key_exists('updated', $_POST)) $this->updated = $_POST['updated'];
if ($read_boolean) {
if (array_key_exists('fixedwidth', $_POST)) $this->fixedwidth = $_POST['fixedwidth'];
}
}
/**
* Loads the object Profile (ie fill the properties) from the database
*/
function load_from_database () {
global $db;
$id = $db->sql_escape($this->perso_id);
$sql = "SELECT * FROM " . TABLE_PROFILES . " WHERE perso_id = '$id'";
if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Unable to query azhar_profiles", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
$this->lastError = "Profile unknown: " . $this->perso_id;
return false;
}
$this->text = $row['profile_text'];
$this->updated = $row['profile_updated'];
$this->fixedwidth = $row['profile_fixedwidth'];
return true;
}
/**
* Saves the object to the database
*/
function save_to_database () {
global $db;
$perso_id = $db->sql_escape($this->perso_id);
$text = $db->sql_escape($this->text);
$updated = $db->sql_escape($this->updated);
$fixedwidth = $this->fixedwidth ? 1 : 0;
$sql = "REPLACE INTO " . TABLE_PROFILES . " (`perso_id`, `profile_text`, `profile_updated`, `profile_fixedwidth`) VALUES ('$perso_id', '$text', '$updated', '$fixedwidth')";
if (!$db->sql_query($sql)) {
message_die(SQL_ERROR, "Unable to save", '', __LINE__, __FILE__, $sql);
}
}
///
/// Tags
///
/**
* Gets the profile's tags
*
* @return string The profile's tags
*/
function get_tags () {
global $db;
$id = $db->sql_escape($this->perso_id);
$sql = "SELECT tag_code, tag_class FROM " . TABLE_PROFILES_TAGS
. " WHERE perso_id = '$id'";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't get tags", '', __LINE__, __FILE__, $sql);
}
- $tags = array();
+ $tags = [];
while ($row = $db->sql_fetchrow($result)) {
$tags[$row['tag_class']][] = $row['tag_code'];
}
return $tags;
}
/**
* Gets the profile's cached tags
*
* @return string The profile's tags
*/
function get_cached_tags () {
require_once('includes/cache/cache.php');
$cache = Cache::load();
$key = 'zed_profile_tags_' . $this->perso_id;
if (!$tags_html = $cache->get($key)) {
//Regenerates tags cached html snippet
global $smarty;
$tags = $this->get_tags();
if (count($tags)) {
$smarty->assign('tags', $tags);
$tags_html = $smarty->fetch('profile_tags.tpl');
} else {
$tags_html = " ";
}
$cache->set($key, $tags_html);
}
return $tags_html;
}
}
diff --git a/includes/objects/ship.php b/includes/objects/ship.php
index d018853..bb9ca42 100755
--- a/includes/objects/ship.php
+++ b/includes/objects/ship.php
@@ -1,325 +1,325 @@
<?php
/**
* Ship class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2010-02-05 18:51 Autogenerated by Pluton Scaffolding
* 0.2 2010-02-06 17:30 Ship API
*
* @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
*/
require_once("perso.php");
require_once("includes/geo/location.php");
/**
* Ship class
*
* This class maps the ship table.
*
* It also provides helper methods to handle landing and fly out,
* or locate the ship.
*
* The class also provides methods for the ship API.
*/
class Ship {
/*
* ----------------------------------------------------------------------- *
* Ship class definition
* ----------------------------------------------------------------------- *
*/
public $id;
public $name;
public $location_global;
public $location_local;
public $api_key;
public $description;
- private static $hashtable = array();
+ private static $hashtable = [];
/**
* Initializes a new instance
*
* @param int $id the primary key
*/
function __construct ($id = null) {
if ($id) {
if (preg_match("/^S[0-9]{5}$/", $id)) {
$id = substr($id, 1);
}
$this->id = $id;
$this->load_from_database();
}
}
/**
* Initializes a new Ship instance if needed or gets already available one.
*
* @param mixed $data ship ID
* @return Ship the ship instance
*/
static function get ($data = null) {
if ($data !== null) {
if (preg_match("/^S[0-9]{5}$/", $id)) {
$id = substr($data, 1);
} else {
$id = $data;
}
//Checks in the hashtable if we already have loaded this instance
if (array_key_exists($id, self::$hashtable)) {
return self::$hashtable[$data];
}
}
$ship = new Ship($data);
return $ship;
}
/**
* Loads the object Ship (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('location_global', $_POST)) $this->location = $_POST['location_global'];
if (array_key_exists('location_local', $_POST)) $this->location = $_POST['location_local'];
if (array_key_exists('api_key', $_POST)) $this->api_key = $_POST['api_key'];
if (array_key_exists('description', $_POST)) $this->description = $_POST['description'];
}
/**
* Loads the object Ship (ie fill the properties) from the database
*/
function load_from_database () {
global $db;
$id = $db->sql_escape($this->id);
$sql = "SELECT * FROM ships WHERE ship_id = '" . $id . "'";
if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Unable to query Ships", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result)) {
$this->lastError = "Ship unknown: " . $this->id;
return false;
}
$this->name = $row['ship_name'];
$this->location_global = $row['location_global'];
$this->location_local = $row['location_local'];
$this->api_key = $row['api_key'];
$this->description = $row['ship_description'];
//Puts object in hashtable
self::$hashtable[$this->id] = $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);
$location_global = $db->sql_escape($this->location_global);
$location_local = $db->sql_escape($this->location_local);
$api_key = $db->sql_escape($this->api_key);
$description = $db->sql_escape($this->description);
//Updates or inserts
$sql = "REPLACE INTO ships (`ship_id`, `ship_name`, `location_global`, `location_local`, `api_key`, `ship_description`) VALUES ($id, '$name', '$location_global', '$location_location', '$api_key', '$description')";
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();
}
}
/**
* Gets the ship code, as a string representation of the instance.
*
* @return the ship's code
*/
function __toString () {
return $this->get_code();
}
/**
* Get ships at specified location
*
* @param string $location_global global location
* @param string $location_local local location
* @return array An array of Ship items, each one a ship at the specified location
*/
static function get_ships_at ($location_global, $location_local = null) {
global $db;
//Gets ships
$sql = "SELECT ship_id, location_global, location_local FROM " . TABLE_SHIPS . " WHERE location_global IS NOT NULL";
if (!$result = $db->sql_query($sql)) {
message_die(SQL_ERROR, "Can't get ships", '', __LINE__, __FILE__, $sql);
}
- $ships = array();
+ $ships = [];
$location = new GeoLocation($location_global, $location_local);
while ($row = $db->sql_fetchrow($result)) {
$shipLocation = new GeoLocation($row['location_global'], $row['location_local']);
if ($location->equals($shipLocation)) {
$ships[] = self::get($row['ship_id']);
}
}
return $ships;
}
/*
* ----------------------------------------------------------------------- *
* Helper methods
* ----------------------------------------------------------------------- *
*/
/**
* Gets ship code, e.g. S00001
*
* @return string the ship code
*/
function get_code () {
return sprintf("S%05d", $this->id);
}
/**
* Determines if the ship is at a spatioport (or assimilated)
*
* @return bool true if the ship is at a spatioport ; false if the ship is in space
*/
function in_spatioport () {
return $this->location_local !== null;
}
/**
* Flies in the sip
*
* @param string $location_local the spatioport location
*
* @todo Completes location global e.g. B00001 -> B00001003
*/
function fly_in ($location_local = null) {
$this->location_local = ($location_local == null) ? 0 : $location_local;
}
/**
* Flies out.
*/
function fly_out () {
$this->location_local = null;
}
/*
* ----------------------------------------------------------------------- *
* Ship API methods
* ----------------------------------------------------------------------- *
*/
/**
* Requests the specified perso to authenticate to this ship
*
* @param mixed $perso_data the perso id or name
*/
function request_perso_authenticate ($perso_data) {
$perso = Perso::get($perso_data);
$flag = sprintf("request.api.ship.auth.%s", $this->get_code());
$perso->set_flag($flag);
$perso->set_flag("site.requests");
}
/**
* Determines if a perso is authenticated to this ship
*
* @param mixed $perso_data the perso id or name
* @return boolean true if the specified perso name is authenticated to this ship ; otherwise, false.
*/
function is_perso_authenticated ($perso_data) {
$flag = sprintf("api.ship.auth.%s", $this->get_code());
return Perso::get($perso_data)->flags[$flag] == 1;
}
/**
* Requests the specified perso to confirm the ship API session
*
* @param string $session_id a session ID provided by calling application
* @param mixed $perso_data the perso id or name
*/
function request_perso_confirm_session ($session_id, $perso_data) {
$perso = Perso::get($perso_data);
$flag = sprintf("request.api.ship.session.%s.%s", $this->get_code(), $session_id);
$perso->set_flag($flag);
$perso->set_flag("site.requests");
}
/**
* Cleans ship API temporary sessions
*/
static function clean_ship_sessions () {
//Cleans old sessions
global $db;
$sql = "DELETE FROM " . TABLE_REGISTRY . " WHERE registry_key LIKE 'api.ship.session.%' AND registry_updated < NOW() - 7200";
if (!$db->sql_query($sql))
message_die(SQL_ERROR, "Can't delete old ship API sessions", '', __LINE__, __FILE__, $sql);
}
/**
* Gets perso id from specified session
*
* @param string $session_id a session ID provided by calling application
* @return mixed the session
*/
function get_perso_from_session ($session_id) {
//Cleans old session
self::clean_ship_sessions();
//Reads api.ship.session.S00001.$session_id
//This registry key contains perso_id if it exists and valid
$key = sprintf("api.ship.session.%s.%s", $this->get_code(), $session_id);
return registry_get($key);
}
/**
* Loads a Ship object from its API key
*
* @param string $key API key GUID
* @return Ship the ship matching the API key
*/
static function from_api_key ($key) {
global $db;
$key = $db->sql_escape($key);
$sql = "SELECT * FROM ships WHERE api_key = '" . $key . "'";
if ( !($result = $db->sql_query($sql)) ) message_die(SQL_ERROR, "Unable to query ships", '', __LINE__, __FILE__, $sql);
if (!$row = $db->sql_fetchrow($result))
return null;
//Fills ship information
$ship = new Ship();
$ship->id = $row['ship_id'];
$ship->name = $row['ship_name'];
$ship->location = $row['ship_location'];
$ship->api_key = $row['api_key'];
$ship->description = $row['ship_description'];
return $ship;
}
}
diff --git a/includes/objects/user.php b/includes/objects/user.php
index 52c839f..da12797 100755
--- a/includes/objects/user.php
+++ b/includes/objects/user.php
@@ -1,244 +1,244 @@
<?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();
+ public static $hashtable_id = [];
+ public static $hashtable_name = [];
/**
* 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 unknown: " . $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;
}
}
diff --git a/includes/settings/page.php b/includes/settings/page.php
index 3e6e9a8..70c6590 100755
--- a/includes/settings/page.php
+++ b/includes/settings/page.php
@@ -1,156 +1,156 @@
<?php
/**
* Settings: a settings page class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* @package Zed
* @subpackage Settings
* @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
*/
require_once("setting.php");
/**
* This class maps the page XML element, from our Settings XML schema
*
* <page id="account" title="Account">
* <setting ...>
* ...
* </setting>
* <setting ...>
* ...
* </setting>
* <page>
*
* It provides method to print a form built from this page and to handle form.
*/
class SettingsPage {
/**
* The page ID
*
* This property maps the id attribute from the page XML tag
*
* @var string the page ID
*/
public $id;
/**
* The page's title
*
* This property maps the title attribute from the page XML tag
*
* @var string the page title
*/
public $title;
/**
* The settings
*
* This property is an array of Setting items and maps the <setting> tags
* @var Array
*/
- public $settings = array();
+ public $settings = [];
/**
* Initializes a new instance of SettingsPage class
*
* @param string $id the page ID
*/
function __construct ($id) {
$this->id = $id;
}
/**
* Initializes a settings page from an SimpleXMLElement XML fragment
*
* @param SimpleXMLElement $xml the XML fragment
* @return SettingsPage the section instance
*/
static function from_xml ($xml) {
//Reads attributes
$id = ''; $title = '';
foreach ($xml->attributes() as $key => $value) {
switch ($key) {
case 'title':
case 'id':
$$key = (string)$value;
break;
default:
message_die(GENERAL_ERROR, "Unknown attribute: $key = \"$value\"", "Settings error");
}
}
//id attribute is mandatory
if (!$id) {
message_die(GENERAL_ERROR, "Section without id. Please add id='' in <section> tag", "Story error");
}
//Initializes new SettingsPage instance
$page = new SettingsPage($id);
$page->title = $title;
//Gets settings
if ($xml->setting) {
foreach ($xml->setting as $settingXml) {
$setting = Setting::from_xml($settingXml);
$page->settings[$setting->key] = $setting;
}
}
return $page;
}
/**
* Handles form reading $_POST array, set new settings values and saves.
*
* @param Array $errors an array where the errors will be filled
* @return boolean true if there isn't error ; otherwise, false.
*/
- function handle_form (&$errors = array()) {
- $objects = array();
+ function handle_form (&$errors = []) {
+ $objects = [];
//Sets new settings values
foreach ($this->settings as $setting) {
$value = $_POST[$setting->key];
if ($setting->field == "password" && !$value) {
//We don't erase passwords if not set
continue;
}
//If the setting value is different of current one, we update it
$currentValue = $setting->get();
if ($setting->field == "checkbox" || $currentValue != $value) {
if (!$setting->set($value)) {
$errors[] = $setting->lastError ? $setting->lastError : "An error have occurred in $setting->key field.";
}
if ($setting->object) $objects[] = $setting->object;
}
}
//Saves object (when the SETTINGS_SAVE_METHOD save method exists)
if (count($objects)) {
$objects = array_unique($objects);
foreach ($objects as $object) {
$object = $GLOBALS[$object];
if (method_exists($object, SETTINGS_SAVE_METHOD)) {
- call_user_func(array($object, SETTINGS_SAVE_METHOD));
+ call_user_func([$object, SETTINGS_SAVE_METHOD]);
}
}
}
}
}
diff --git a/includes/settings/setting.php b/includes/settings/setting.php
index aaf3ddf..a764c30 100755
--- a/includes/settings/setting.php
+++ b/includes/settings/setting.php
@@ -1,174 +1,174 @@
<?php
/**
* Settings: an individual setting class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* @package Zed
* @subpackage Settings
* @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
*/
/**
* Setting class
*
* This class map the <setting> XML block, from our settings XML format
*/
class Setting {
public $key;
//Rendering variables
public $field;
public $regExp;
public $choices;
//get/set variables
public $object;
private $property;
private $method;
private $handler;
//error variable
public $lastError;
/**
* Gets the current setting value
*
* @return string the setting value
*/
function get () {
//1 - Evaluates custom handler
if (array_key_exists('get', $this->handler)) {
return eval($this->handler['get']);
}
//2 - Gets object property
if ($this->object && $property = $this->property) {
return $GLOBALS[$this->object]->$property;
}
if ($this->field == "password") {
//Okay not to have a value for password fields
return;
}
message_die(GENERAL_ERROR, "Setting $this->key haven't any get indication. Please set <object> and <property> / or a custom <handler><get></get></handler> block.", "Settings error");
}
/**
* Sets a new value
*
* @param $value the setting new value
* @return boolean true if the setting have been successfully set ; otherwise, false.
*/
function set ($value) {
//Validates data
if ($this->regExp) {
if (!preg_match('/^' . $this->regExp . '$/', $value)) {
$this->lastError = "Invalid format for $this->key setting";
return false;
}
}
//Tries to set value
//1 - Evaluates custom handler
if (array_key_exists('set', $this->handler)) {
return eval($this->handler['set']);
}
//2 - Calls object method
//3 - Sets object property
if ($this->object) {
$object = $GLOBALS[$this->object];
if ($this->method) {
- return call_user_func(array($object, $this->method), $value);
+ return call_user_func([$object, $this->method], $value);
} elseif ($property = $this->property) {
$object->$property = $value;
return true;
}
}
message_die(GENERAL_ERROR, "Setting $this->key haven't any set indication. Please set <object> (and whether <method>, whether <property>) or a custom <handler><set></set></handler> block.", "Settings error");
}
/**
* Saves setting
*
* @return mixed the SETTINGS_SAVE_METHOD method value, or false if there's no method call;
*/
function save () {
if ($this->object) {
$object = $GLOBALS[$this->object];
if (method_exists($object, SETTINGS_SAVE_METHOD)) {
- return call_user_func(array($object, SETTINGS_SAVE_METHOD));
+ return call_user_func([$object, SETTINGS_SAVE_METHOD]);
}
}
return false;
}
/**
* Initializes a new instance of Setting class from a XML element
*
* @param SimpleXMLElement the xml element to parse
* @return Setting the setting class
*/
static function from_xml ($xml) {
//Reads attributes
$id = '';
foreach ($xml->attributes() as $key => $value) {
switch ($key) {
case 'id':
$id = (string)$value;
break;
default:
message_die(GENERAL_ERROR, "Unknown attribute: $key = \"$value\"", "Settings error");
}
}
//id attribute is mandatory
if (!$id) {
message_die(GENERAL_ERROR, "Setting without id. Please add id='' in <setting> tag", "Settings error");
}
//Initializes new Setting instance
$setting = new Setting($id);
//Parses simple <tag>value</tag>
- $properties = array('key', 'field', 'object', 'property', 'method', 'regExp');
+ $properties = ['key', 'field', 'object', 'property', 'method', 'regExp'];
foreach ($properties as $property) {
if ($xml->$property)
$setting->$property = (string)$xml->$property;
}
//Parses <handler>
- $setting->handler = array();
+ $setting->handler = [];
if ($xml->handler) {
if ($xml->handler->get) $setting->handler['get'] = (string)$xml->handler->get;
if ($xml->handler->set) $setting->handler['set'] = (string)$xml->handler->set;
}
//Parses <choices>
if ($xml->choices) {
foreach ($xml->choices->choice as $choiceXml) {
$setting->choices[(string)$choiceXml->key] = (string)$choiceXml->value;
}
}
return $setting;
}
}
diff --git a/includes/story/hook_demo.php b/includes/story/hook_demo.php
index ed9637f..43177f9 100755
--- a/includes/story/hook_demo.php
+++ b/includes/story/hook_demo.php
@@ -1,76 +1,76 @@
<?php
/**
* Story hook class: example code
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* This class illustrates how to use the StoryHook class.
*
* @package Zed
* @subpackage Story
* @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
*/
$class = "DemoStoryHook";
/**
* Story hook demo class
*/
class DemoStoryHook extends StoryHook {
/**
* Initializes resources
*
* @see StoryHook::initialize
*
* The initialize method is called after the constructor and is mandatory,
* even if you've nothing to initialize, as it's an abstract method.
*/
function initialize () {}
/**
* Updates the current section description.
*
* @see StoryHook::update_description
*
* @param string $description the description to update
*/
function update_description (&$description) {
//Performs the rot13 transform of the current description
$description = str_rot13($description);
//Appends a string to the current description
$description .= "\n\nWazzzzzzzzzzzzzzzzaaaaaaaaaaaaaaaaaaaaaa";
}
/**
* Updates the current section choices
*
* @see StoryHook::get_choices_links
*
* @param Array $links the section links
*/
function get_choices_links (&$links) {
//Adds a link to /push
- $links[] = array(lang_get("PushMessage"), get_url('push'));
+ $links[] = [lang_get("PushMessage"), get_url('push')];
}
/**
* Adds content after our story content block
*
* @see StoryHook::add_html
*/
function add_html () {
//Adds a html block
return '<div class="black">Lorem ipsum dolor</div>';
}
}
diff --git a/includes/story/section.php b/includes/story/section.php
index 0a7912c..e04de2d 100755
--- a/includes/story/section.php
+++ b/includes/story/section.php
@@ -1,158 +1,158 @@
<?php
/**
* Story section class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* @package Zed
* @subpackage Story
* @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
*/
require_once('choice.php');
require_once('hook.php');
/**
* Story section class
*
* This class is a PHP mapping from the Story XML format's <section> tag.
*
* This class also a method to get the section where a specific choice links to.
*/
class StorySection {
/**
* The section ID
*
* @var string
*/
public $id;
/**
* The section title
*
* @var string
*/
public $title;
/**
* The section description
*
* @var string
*/
public $description;
/**
* @var string the local location
*/
public $location_local;
/**
* @var Array the section choices (array of StoryChoice items)
*/
- public $choices = array();
+ public $choices = [];
/*
* @var Array the section hooks (array of StoryHook items)
*/
- public $hooks = array();
+ public $hooks = [];
/**
* @var boolean if true, it's the story start ; otherwise, false;
*/
public $start;
/**
* @var Story the story calling the section
*/
public $story;
/**
* Initializes a new instance of StorySection class
*/
function __construct ($id, $story = null) {
$this->id = $id;
if ($story !== null) {
$this->story = $story;
}
}
/**
* Gets choice from specified guid
*
* @return StoryChoice the wanted choice, or null if it doesn't exist
*/
function get_choice ($guid) {
foreach ($this->choices as $choice) {
if ($choice->guid == $guid)
return $choice;
}
return null;
}
/**
* Initializes a story section from an SimpleXMLElement XML fragment
*
* @param SimpleXMLElement $xml the XML fragment
* @param Story $story the calling story
* @return StorySection the section instance
*/
static function from_xml ($xml, $story = null) {
//Reads attributes
$id = '';
$start = false;
foreach ($xml->attributes() as $key => $value) {
switch ($key) {
case 'start':
if ($value) $start = true;
break;
case 'id':
$id = (string)$value;
break;
default:
message_die(GENERAL_ERROR, "Unknown attribute: $key = \"$value\"", "Story error");
}
}
if (!$id) {
message_die(GENERAL_ERROR, "Section without id. Please add id='' in <section> tag", "Story error");
}
$section = new StorySection($id, $story);
$section->title = (string)$xml->title;
$section->description = (string)$xml->description;
$section->location_local = (string)$xml->local;
$section->start = $start;
//Adds choices
if ($xml->choices) {
foreach ($xml->choices->choice as $choice) {
$section->choices[] = StoryChoice::from_xml($choice);
}
}
//Adds hooks
if ($xml->hooks) {
foreach ($xml->hooks->hook as $hook) {
//<hook type="spatioport" /> will assign 'spatioport' to $hook;
$hook = (string)$hook->attributes()->type;
require_once("hook_$hook.php");
$section->hooks[] = new $class($section->story, $section);
}
}
return $section;
}
}
diff --git a/includes/story/story.php b/includes/story/story.php
index b3adc6c..a9ac2bf 100755
--- a/includes/story/story.php
+++ b/includes/story/story.php
@@ -1,131 +1,131 @@
<?php
/**
* Story class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* @package Zed
* @subpackage Story
* @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
*/
require_once('section.php');
/**
* Story class
*
* This class is a PHP mapping from the Story XML format.
*
* This class also provides a collection of helper methods to explore the story.
*/
class Story {
/**
* The file path
*
* @var string
*/
public $file;
/**
* The story title
*
* @var string
*/
public $title;
/**
* An array of StorySection elements
*
* @var Array
*/
- public $sections = array();
+ public $sections = [];
/**
* The SimpleXML parser
*
* @var SimpleXMLElement
*/
private $xml;
/**
* The index of start section in sections array
*
* @var string
*/
private $startSection = null;
/**
* An array of StorySection elements, indexed by location
*
* @var Array
*/
- private $sectionsByLocation = array();
+ private $sectionsByLocation = [];
function __construct ($file) {
//Opens .xml
if (!file_exists($file)) {
message_die(GENERAL_ERROR, "$file not found.", "Story loading error");
}
$this->file = $file;
$this->parse();
}
/**
* Gets start section
*
* @return StorySection the section where the story starts, or null if not defined
*/
function get_start_section () {
return ($this->startSection != null) ? $this->sections[$this->startSection] : null;
}
/**
* Gets section from local location
*
* @return StorySection the default section at this location, or null if not defined
*/
function get_section_from_location ($location) {
return array_key_exists($location, $this->sectionsByLocation) ? $this->sectionsByLocation[$location] : null;
}
/**
* Parses XML file
*/
function parse () {
//Parses it
$this->xml = simplexml_load_file($this->file);
$this->title = (string)$this->xml->title;
foreach ($this->xml->section as $section) {
//Gets section
$section = StorySection::from_xml($section, $this);
//Have we a start section?
if ($section->start) {
//Ensures we've only one start section
if ($this->startSection != null) {
message_die(GENERAL_ERROR, "Two sections have start=\"true\": $section->id and $this->startSection.", "Story error");
}
$this->startSection = $section->id;
}
//By location
if ($section->location_local) {
$this->sectionsByLocation[$section->location_local] = $section;
}
//Adds to sections array
$this->sections[$section->id] = $section;
}
}
}
diff --git a/includes/travel/place.php b/includes/travel/place.php
index 99634d3..d8b3989 100755
--- a/includes/travel/place.php
+++ b/includes/travel/place.php
@@ -1,150 +1,150 @@
<?php
/**
* TravelPlace class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2010-07-19 22:10 DcK
*
* @package Zed
* @subpackage Travel
* @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
*/
/**
* TravelPlace class
*
* The TravelPlace class is a set of rules determining which moves are valid
* in a specific place.
*
* @see GeoPlace
*
*/
class TravelPlace {
/**
* The place code
*
* @var string
*/
public $code;
/**
* Determines if any local location move is valid
*
* @var bool
*/
public $freeLocalMove = false;
/**
* Array of strings, each item another place reachable
*
* This matches GlobalTravelTo XML tags.
*
* @var Array
*/
- public $globalTravelTo = array();
+ public $globalTravelTo = [];
/**
* Array of array, containing [location, alias, name] entries
*
* This matches LocalMove XML tags.
*
* @var Array
*/
- public $localMoves = array();
+ public $localMoves = [];
/**
* Array of array, containing [expression, global_location, local_location] entries
*
* This matches RewriteRule XML tags.
*
* @var Array
*/
- public $rewriteRules = array();
+ public $rewriteRules = [];
/**
* Initializes a new TravelPlace instance, from the specified XML fragment
*
* @param string $xml the XML fragment to parse
* @return TravelPlace the TravelPlace instance matching the specified XML fragment
*/
static function from_xml ($xml) {
$travelPlace = new TravelPlace();
//Reads attributes: <TravelPlace code="B00001001" freeLocalMove="true">
foreach ($xml->attributes() as $key => $value) {
switch ($key) {
case 'code':
$travelPlace->code = (string)$value;
break;
case 'freeLocalMove':
$travelPlace->freeLocalMove = (boolean)$value;
break;
}
}
//<GlobalTravelTo code="B00001002" />
foreach ($xml->GlobalTravelTo as $globalTravelToXml) {
foreach ($globalTravelToXml->attributes() as $key => $value) {
if ($key == "code") {
$travelPlace->globalTravelTo[] = (string)$value;
}
}
}
//<LocalMove local_location="(0, 0, 0)" alias="C0" name="Core" />
foreach ($xml->LocalMove as $localMoveXml) {
- $localMove = array(null, null, null);
+ $localMove = [null, null, null];
foreach ($localMoveXml->attributes() as $key => $value) {
switch ($key) {
case 'local_location':
$localMove[0] = (string)$value;
break;
case 'alias':
$localMove[1] = (string)$value;
break;
case 'name':
$localMove[2] = (string)$value;
break;
}
}
$travelPlace->localMoves[] = $localMove;
}
//<RewriteRule expression="/^T([1-9][0-9]*)$/" global_location="B00001001" local_location="T$1C1" />
foreach ($xml->RewriteRule as $rewriteRuleXml) {
- $rewriteRule = array(null, null, null);
+ $rewriteRule = [null, null, null];
foreach ($rewriteRuleXml->attributes() as $key => $value) {
switch ($key) {
case 'expression':
$rewriteRule[0] = (string)$value;
break;
case 'global_location':
$rewriteRule[1] = (string)$value;
break;
case 'local_location':
$rewriteRule[2] = (string)$value;
break;
}
}
$travelPlace->rewriteRules[] = $rewriteRule;
}
return $travelPlace;
}
}
diff --git a/includes/travel/travel.php b/includes/travel/travel.php
index 98ba92f..3d0c3a5 100755
--- a/includes/travel/travel.php
+++ b/includes/travel/travel.php
@@ -1,173 +1,173 @@
<?php
/**
* Travel helper class
*
* Zed. The immensity of stars. The HyperShip. The people.
*
* (c) 2010, Dereckson, some rights reserved.
* Released under BSD license.
*
* 0.1 2010-07-18 22:05 DcK
*
* @package Zed
* @subpackage Travel
* @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
*/
require_once('place.php');
/**
* Travel helper class
*
* The Travel class reads content/travel.xml to get travel special rules
*
* It so be able to provide methods determining if a move is or not valid.
*
* This class implements a singleton pattern.
*/
class Travel {
/**
* Array of TravelPlace, each one a custom travel rule
*
* This array is indexed by TravelPlace code.
*
* @var Array
*/
public $globalTravelTo;
/**
* Constructor
*/
function __construct () {
//Initializes array
- $this->globalTravelTo = array();
+ $this->globalTravelTo = [];
}
/**
* Gets and initializes if needed the Travel instance
*
* @return Travel the Travel instance
*/
static function load () {
require_once('includes/cache/cache.php');
$cache = Cache::load();
if (!$travel = $cache->get('zed_travel')) {
//Initializes resource and caches it
$travel = new Travel();
$travel->load_xml("content/travel.xml");
$cache->set('zed_travel', serialize($travel));
return $travel;
}
return unserialize($travel);
}
/**
* Loads a travel configuration XML file
*
* @param string the path to the travel XML file
*/
function load_xml ($file) {
$xml = simplexml_load_file($file);
foreach ($xml->TravelPlace as $travelPlaceXml) {
$travelPlace = TravelPlace::from_xml($travelPlaceXml);
$this->globalTravelTo[$travelPlace->code] = $travelPlace;
}
}
/**
* Tries to parse the specified expression, according the rewrite rules
* (for example defined by the <RewriteRule> xml tags)
*
* @param string $expression the expression to parse
* @param GeoLocation the location where the perso is
* @param GeoLocation the location where the perso wants to go
*
* @return boolean true if the expression have been parsed ; otherwise, false.
*/
function try_parse_rewrite_rule ($expression, $from, &$to) {
//Relevant write rules depends from the location the perso is ($from)
if (!array_key_exists($from->global, $this->globalTravelTo)) {
return false;
}
$travelPlace = $this->globalTravelTo[$from->global];
foreach ($travelPlace->rewriteRules as $rule) {
//$rule is an array [expression, global_location, local_location]
- $subpatterns = array();
+ $subpatterns = [];
$result = preg_match($rule[0], $expression, $subpatterns);
if ($result > 0) {
//$subpatterns is an array with:
// - at indice 0, the full matched regexp
// - from 1 to n, the (groups) inside the regexp
//We need so to replace $1 by $subpatterns[1] and so on.
for ($i = count($subpatterns) - 1 ; $i > 0 ; $i--) {
$rule[1] = str_replace('$' . $i, $subpatterns[$i], $rule[1]);
$rule[2] = str_replace('$' . $i, $subpatterns[$i], $rule[2]);
}
$to = new GeoLocation($rule[1], $rule[2]);
return true;
}
}
return false;
}
/**
* Determines if a perso can travel from $from to $to
*
* If an alias have been used for $to local location, set correct location.
*
* @param GeoLocation the location where the perso is
* @param GeoLocation the location where the perso wants to go
* @return boolean true if the travel move is valid ; otherwise, false.
*
* @todo From B00001002, goto C1 doesn't work. Alias seems ignored.
*/
function can_travel ($from, &$to) {
if ($from->global != $to->global) {
//Checks if we can locally from $from to $to place
if (!array_key_exists($from->global, $this->globalTravelTo)) {
return false;
}
$travelPlace = $this->globalTravelTo[$from->global];
if (!in_array($to->global, $travelPlace->globalTravelTo)) {
return false;
}
}
if ($to->containsLocalLocation) {
//Determines if we've custom rules about local moves in $to
if (!array_key_exists($to->global, $this->globalTravelTo)) {
return false;
}
$travelPlace = $this->globalTravelTo[$to->global];
//Is it's an especially allowed movement?
foreach ($travelPlace->localMoves as $move) {
//move is a [location, alias, name] array
//If any of those 3 parameters matches $to->local, it's okay
if (in_array($to->local, $move)) {
$to->local = $move[0];
return true;
}
}
if ($travelPlace->freeLocalMove) {
//We can move freely, perfect
return true;
}
//Local move not allowed
return false;
}
return true;
}
}
diff --git a/index.php b/index.php
index eefd55b..e22cc27 100644
--- a/index.php
+++ b/index.php
@@ -1,201 +1,201 @@
<?php
/**
* 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
///
//Keruald (formerly 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 information
//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->setTemplateDir($current_dir . '/skins/' . THEME);
$smarty->compile_dir = CACHE_DIR . '/compiled';
$smarty->cache_dir = CACHE_DIR;
$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 (=character) selector
///
//Handles form
if ($_POST['form'] == 'perso.create') {
$perso = null;
- $errors = array();
+ $errors = [];
if (Perso::create_perso_from_form($CurrentUser, $perso, $errors)) {
//Notifies and logs in
$smarty->assign('NOTIFY', lang_get('NewCharacterCreated'));
$CurrentPerso = $perso;
set_info('perso_id', $perso->id);
$CurrentPerso->set_flag("site.lastlogin", $_SERVER['REQUEST_TIME']);
} else {
//Prints again perso create form, so the user can fix it
$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 has selected a perso
$CurrentPerso = new Perso($_GET['perso_id']);
if ($CurrentPerso->user_id != $CurrentUser->id) {
//User have made an error in the URL
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 'builder':
case 'explore':
case 'page':
case 'request':
case 'settings':
case 'ship':
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 prettier 404 page
header("Status: 404 Not Found");
dieprint_r($url, 'Unknown URL');
}

File Metadata

Mime Type
text/x-diff
Expires
Sat, Nov 23, 10:10 (1 d, 3 h ago)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
20898
Default Alt Text
(289 KB)

Event Timeline