Page MenuHomeDevCentral

No OneTemporary

diff --git a/workspaces/src/includes/collection/MongoDBCollectionIterator.php b/workspaces/src/includes/collection/MongoDBCollectionIterator.php
index 00ec036..e69434d 100644
--- a/workspaces/src/includes/collection/MongoDBCollectionIterator.php
+++ b/workspaces/src/includes/collection/MongoDBCollectionIterator.php
@@ -1,89 +1,89 @@
<?php
/**
* _, __, _, _ __, _ _, _, _
* / \ |_) (_ | | \ | /_\ |\ |
* \ / |_) , ) | |_/ | | | | \|
* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
*
* MongoDB collection iterator class
*
* @package ObsidianWorkspaces
* @subpackage Collection
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD
* @filesource
*/
/**
* Iterator for MongoDBCollection::getAll()
*/
class MongoDBCollectionIterator implements Iterator {
/**
* @var MongoCursor The MongoDB cursor
*/
private $cursor;
/**
* @var MongoDBCollection The collection attached to the current iterator instance
*/
private $collection;
/**
* Initializes a new instance of the MongoDBCollectionIterator object
*
* @param MongoDBCollection $collection The collection to iterate
- * @param MongoCursor $cursor The cursor to the results [optional]
+ * @param ?MongoCursor $cursor The cursor to the results [optional]
*/
- public function __construct (MongoDBCollection $collection, MongoCursor $cursor = null) {
+ public function __construct (MongoDBCollection $collection, ?MongoCursor $cursor = null) {
$this->collection = $collection;
if ($cursor === null) {
$this->cursor = $collection->mongoCollection->find();
} else {
$this->cursor = $cursor;
}
}
/**
* Returns a collection document from the current result
*
* @return CollectionDocument the current result's document
*/
public function current () {
return $this->collection->getDocumentFromArray(
$this->cursor->current()
);
}
/**
* Returns the key of the current element
*
* @return string the current result's _id
*/
public function key () {
return $this->cursor->key();
}
/**
* Moves forward to next element
*/
public function next () {
$this->cursor->next();
}
/**
* Rewinds the iterator to the first element
*/
public function rewind () {
$this->cursor->rewind();
}
/**
* Checks if current position is valid
*
* @return boolean true if the current position is valid ; otherwise, false
*/
public function valid () {
return $this->cursor->valid();
}
}
diff --git a/workspaces/src/includes/collection/MySQLCollection.php b/workspaces/src/includes/collection/MySQLCollection.php
index c0362b2..c917049 100644
--- a/workspaces/src/includes/collection/MySQLCollection.php
+++ b/workspaces/src/includes/collection/MySQLCollection.php
@@ -1,167 +1,167 @@
<?php
/**
* _, __, _, _ __, _ _, _, _
* / \ |_) (_ | | \ | /_\ |\ |
* \ / |_) , ) | |_/ | | | | \|
* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
*
* MySQL Collection class
*
* @package ObsidianWorkspaces
* @subpackage Collection
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD
* @filesource
*/
/**
* MySQL Collection class
*
* This class represents a collection of documents, stored on MySQL.
*/
class MySQLCollection extends SQLCollection {
///
/// Singleton pattern to get the MySQLDatabase instance
///
/**
* @var MySQLDatabase The mongo client to the database the collection is hosted
*/
public static $client = null;
/**
* Gets the existing MySQLDatabase instance, or if not available, initializes one.
*
* @param Context $context
* @return MySQLDatabase The MySQLDatabase instance
*/
public static function getCurrentSiteDatabaseClient () {
if (self::$client === null) {
$client = Database::load();
if ($candidateClient instanceof MySQLDatabase) {
self::$client = $client;
} else {
throw new InvalidArgumentException("The MySQLDatabase driver is intended to be used when your main database product is MySQL. We recommend whether you pick the same engine for collections and other db use, whether you use a key/store storage solution for collections, like MongoDB.");
}
}
return self::$client;
}
///
/// Constructor
///
/**
* Initializes a new instance of MongoCollection
*
* @param string $id the collection identifiant
*/
- public function __construct ($id, MySQLDatabase $client = null, $table = '') {
+ public function __construct ($id, ?MySQLDatabase $client = null, $table = '') {
global $Config;
if ($client === null) {
self::getCurrentSiteDatabaseClient();
} else {
self::$client = $client;
}
if ($table == '') {
if (!array_key_exists('DocumentStorage', $Config) || !array_key_exists('Table', $Config['DocumentStorage'])) {
throw new Exception("Configuration parameter missing: \$Config['DocumentStorage']['Table']. Expected value for this parameter is the table to store the collections documents.");
}
$this->table = $Config['DocumentStorage']['Table'];
} else {
$this->table = $table;
}
$this->id = $id;
$this->initializeCollectionsTable();
}
///
/// Helper to create schema if required
///
/**
* Initialiazes collections table
*/
protected function initializeCollectionsTable () {
if (defined('COLLECTIONS_MYSQL_DATABASE_READY') && COLLECTIONS_MYSQL_DATABASE_READY) {
return;
}
self::$client->query("
CREATE TABLE if not exists $this->table (
collection_id VARCHAR(255),
document_id VARCHAR(255),
document_value BLOB,
PRIMARY KEY (collection_id, document_id)
);"
);
define('COLLECTIONS_MYSQL_DATABASE_READY', true);
}
///
/// SqlCollection implementation
///
/**
* Executes a SQL query
*
* @param string $sql The SQL query
* @return mixed If the query doesn't return any result, null. If the query return a row with one field, the scalar value. Otheriwse, an aossciative array, the fields as keys, the row as values.
*/
public function query ($sql) {
if ($sql == "") {
return null;
}
$db = self::$client;
if (!$result = $db->query($sql, MYSQL_ASSOC)) {
throw new Exception("Can't execute collection query.");
}
if (!$row = $db->fetchRow($result)) {
return null;
}
if (count($row) == 1) {
return array_shift($row);
} else {
return $row;
}
}
/**
* Escapes the SQL string
*
* @param string $value The value to escape
* @return string The escaped value
*/
public function escape ($value) {
return self::$client->escape($value);
}
/**
* Gets all the documents from the collection
*
* @return Iterator An iterator to the documents, each item an instance of CollectionDocument
*/
public function getAll () {
$db = self::$client;
$collectionId = $this->escape($this->id);
$sql = "SELECT * FROM $this->table WHERE collection_id = '$collectionId'";
if (!$result = $db->query($sql, MYSQL_ASSOC)) {
throw new Exception("Can't get each collection documents.");
}
$type = $this->documentType;
while ($row = $db->fetchRow($result)) {
$data = json_decode($row['document_value']);
yield $type::loadFromObject($data);
}
}
}
diff --git a/workspaces/src/includes/database/Database.php b/workspaces/src/includes/database/Database.php
index 9f68d02..358d19f 100644
--- a/workspaces/src/includes/database/Database.php
+++ b/workspaces/src/includes/database/Database.php
@@ -1,214 +1,214 @@
<?php
/**
* _, __, _, _ __, _ _, _, _
* / \ |_) (_ | | \ | /_\ |\ |
* \ / |_) , ) | |_/ | | | | \|
* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
*
* Database base class
*
* @package ObsidianWorkspaces
* @subpackage Keruald
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD
* @filesource
*
*/
abstract class Database implements LoadableWithContext {
///
/// Singleton pattern, LoadableWithContext implementation
///
/**
* @var Database the singleton instance
*/
private static $instance = null;
/**
* Loads a new instance of the relevant Database object
*
- * @param Context $context The application context
+ * @param ?Context $context The application context
* @return Database The database instance
*/
- public static function load (Context $context = null) {
+ public static function load (?Context $context = null) {
if (self::$instance === null ) {
if (!isset($context->config['sql']['engine'])) {
throw new InvalidArgumentException("To load a database, you need to add in your configuration a parameter block like:
'sql' => [
'engine' => 'TheSQLEngineYouWant',
//... configuration specific to the database
]"
);
}
$className = $context->config['sql']['engine'] . 'Database';
if (!class_exists($className)) {
throw new InvalidArgumentException("The class matching your engine doesn't exist: $className");
}
self::$instance = $className::load($context);
}
return self::$instance;
}
///
/// The methods to implement
///
/**
* Executes a query
*
* @param string $query The query to execute
* @return DatabaseResult The query result
*/
public abstract function query ($query);
/**
* Retrieves the id generated by the last statement
*
* @return int The last id generated
*/
public abstract function nextId ();
/**
* Escapes the expression
*
* @param $expression The expression to escape
* @return string The escaped expression
*/
public abstract function escape ($expression);
///
/// Generic methods
///
/**
* Fetches a row of the result
*
* @param DatabaseResult $result The query result
* @return array An associative array with the databae result
*/
public function fetchRow (DatabaseResult $result) {
return $result->fetchRow();
}
/**
* Gets number of rows in result
*
* @param DatabaseResult $result The query result
* @return int The number of rows in the specified result
*/
public function numRows (DatabaseResult $result) {
return $result->numRows();
}
/**
* Runs a query and fetches a scalar result. Dies if an error occurs.
*
* @param string $query the query
* @param string $errorMessage The error message to print when dying. [optional, by default CantExecuteQuery L10n message]
* @return string The result of the query
*/
public function queryScalar ($query = '', $errorMessage = '') {
if ($errorMessage === '') {
$errorMessage = Language::get('CantExecuteQuery');
}
if ($query === '' || $query === false || $query === null) {
//No query, no value
return '';
} elseif (!$result = $this->query($query)) {
//An error have occured
message_die(SQL_ERROR, $error_message, '', '', '', $query);
} elseif (!$row = $this->fetchRow($result)) {
return '';
} else {
return $row[0];
}
}
///
/// Events
///
/**
* @var Array
* @event CantConnectToHost Functions to call when it's not possible to connect to the database host
* @eventparam Database $db The current database instance
*/
public $cantConnectToHostEvents = [];
/**
* @var Array
* @event QueryError Functions to call when a query fails.
* @eventparam Database $db The current database instance
* @eventparam string $query The failed query
* @eventparam DatabaseException $ex The exception describing the query error
*/
public $queryErrorEvents = [];
/**
* Called on connect failure
*/
protected abstract function onCantConnectToHost();
/**
* Called on query error
*
* @param string $query The query executed when the error occured
*/
protected abstract function onQueryError ($query);
///
/// Compatibility feature
///
/**
* Allows the legacy use of sql_query, sql_fetchrow, sql_escape, etc.
*
* @param $name The name of the inaccessible method called
* @param $arguments The method arguments
* @return mixed The result of the method called
* @throws BadMethodCallException when the method name doesn't match a legacy method
* @deprecated
*/
public function __call ($name, $arguments) {
if (substr($name, 0, 4) == 'sql_') {
switch ($name) {
case 'sql_nextid':
$newMethodName = 'nextId';
break;
case 'sql_query_express':
$newMethodName = 'queryScalar';
break;
case 'sql_fetchrow':
$newMethodName = 'fetchRow';
break;
case 'sql_numrows':
$newMethodName = 'numRows';
break;
default:
$newMethodName = substr($name, 4);
}
if (method_exists($this, $newMethodName)) {
//trigger_error("\$db->$name calls shall be replaced by \$db->$newMethodName calls.", E_USER_DEPRECATED);
return call_user_func_array(
array($this, $newMethodName),
$arguments
);
}
}
$className = get_class($this);
throw new BadMethodCallException("Method doesn't exist: $className::$name");
}
}
diff --git a/workspaces/src/includes/database/DatabaseException.php b/workspaces/src/includes/database/DatabaseException.php
index 4a61ed0..e649da7 100644
--- a/workspaces/src/includes/database/DatabaseException.php
+++ b/workspaces/src/includes/database/DatabaseException.php
@@ -1,51 +1,51 @@
<?php
/**
* _, __, _, _ __, _ _, _, _
* / \ |_) (_ | | \ | /_\ |\ |
* \ / |_) , ) | |_/ | | | | \|
* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
*
* Database exception class
*
* @package ObsidianWorkspaces
* @subpackage Keruald
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD
* @filesource
*
*/
/**
* DatabaseException class.
*
* Used to throw exception running queries.
*/
class DatabaseException extends RuntimeException {
/**
* @var string the SQL query
*/
protected $query = null;
/**
* Initializes a new instance of the DatabaseException class
*
* @param string|null $query The query executed. Null if the exception occured outside a query.
* @param string $message The message to throw.
* @param int $code The code.
- * @param Exception $previous The previous exception used for the exception chaining.
+ * @param ?Exception $previous The previous exception used for the exception chaining.
*/
- public function __construct ($query = null, $message = '', $code = 0, Exception $previous = null) {
+ public function __construct ($query = null, $message = '', $code = 0, ?Exception $previous = null) {
$this->query = $query;
parent::__construct($message, $code, $previous);
}
/**
* Gets the the SQL query
*
* @return string|null The SQL query or null if the exception were thrown outside a query context.
*/
public final function getQuery () {
return $this->query;
}
}
diff --git a/workspaces/src/includes/i18n/Language.php b/workspaces/src/includes/i18n/Language.php
index 863d84d..d8bfed7 100644
--- a/workspaces/src/includes/i18n/Language.php
+++ b/workspaces/src/includes/i18n/Language.php
@@ -1,227 +1,227 @@
<?php
/**
* _, __, _, _ __, _ _, _, _
* / \ |_) (_ | | \ | /_\ |\ |
* \ / |_) , ) | |_/ | | | | \|
* ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
*
* Localization (l10n) language class
*
* @package ObsidianWorkspaces
* @subpackage I18n
* @author Sébastien Santoro aka Dereckson <dereckson@espace-win.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD
* @filesource
*/
/**
* 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
* @deprecated
*/
function lang_get ($key) {
trigger_error("The use of the L10n global functions is deprecated. Call Language::get('$key') instead.", E_USER_DEPRECATED);
return Language::get($key);
}
/**
* Language services
*/
class Language implements LoadableWithContext {
///
/// Properties
///
/**
* @var
*/
const FALLBACK = 'en';
/**
* @var Smarty the template engine
*/
private $templateEngine;
///
/// Singleton pattern. Constructor.
///
/**
* @var Language The loaded Language instance
*/
private static $instance;
/**
* Loads an instance of the class
*
- * @param Context $context The context
+ * @param ?Context $context The context
* @return Language An instance of the Language class
*/
- public static function Load (Context $context = null) {
+ public static function Load (?Context $context = null) {
if (static::$instance === null) {
//Initializes an instance
if ($context === null) {
throw new InvalidArgumentException("A context is required to load this class for the first time.");
}
if ($context->templateEngine === null) {
throw new InvalidArgumentException("A context is required to load this class for the first time. You provided one, but the template engine isn't initiliazed. This is required, as the languages files are managed by the template engine.");
}
static::$instance = new static($context->templateEngine);
}
return static::$instance;
}
/**
* Initializes a new instance of the Language class
*/
public function __construct ($templateEngine) {
$this->templateEngine = $templateEngine;
}
///
/// Static helper methods
///
/**
* 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 findLanguage
*/
public static function initialize () {
//If $_SESSION['lang'] doesn't exist yet, find a common language
if (!array_key_exists('lang', $_SESSION)) {
$lang = static::findLanguage();
$_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 Language::getHttpAcceptLanguages
*
* @return string the language
*/
public static function findLanguage () {
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 = static::getHttpAcceptLanguages())
return;
//Gets the intersection between the both languages arrays
//If it matches, returns first result
$intersect = array_intersect($userlangs, $langs);
if (count($intersect)) {
return array_shift($intersect);
}
//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 array_shift($intersect);
}
}
}
/**
* 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
*/
public static function getHttpAcceptLanguages () {
//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 (!isset($_SERVER) || !array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
return null;
}
$http_accept_language = explode(',', $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
foreach ($http_accept_language as $language) {
$userlang = explode(';q=', $language);
if (count($userlang) == 1) {
$userlangs[] = array(1, $language);
} else {
$userlangs[] = array($userlang[1], $userlang[0]);
}
}
rsort($userlangs);
foreach ($userlangs as $userlang) {
$result[] = $userlang[1];
}
return $result;
}
public static function get ($key) {
return static::load()->getConfigVar($key);
}
///
/// Methods
///
/**
* Loads specified language Smarty configuration file
*
* @param Smarty $templateEngine the template engine
* @param string $file the file to load
* @param mixed $sections array of section names, single section or null
*/
public function configLoad ($file, $sections = null) {
$fallback = static::FALLBACK;
//Loads English file as fallback if some parameters are missing
if (file_exists("lang/$fallback/$file")) {
$this->templateEngine->configLoad("lang/$fallback/$file", $sections);
}
//Loads wanted file (if it exists and a language have been defined)
if (defined('LANG') && LANG != '$fallback' && file_exists('lang/' . LANG . '/' . $file)) {
$this->templateEngine->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
*/
private function getConfigVar ($key) {
if (array_key_exists($key, $this->templateEngine->config_vars)) {
return $this->templateEngine->config_vars[$key];
}
trigger_error("The l10n key '$key' doesn't exist.", E_USER_NOTICE);
return "#$key#";
}
}

File Metadata

Mime Type
text/x-diff
Expires
Wed, Mar 18, 13:23 (11 h, 3 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3528995
Default Alt Text
(24 KB)

Event Timeline