* text=auto !eol
/Doxyfile -text
+application/.htaccess -text
application/mxchange/.htaccess -text
application/mxchange/class_ApplicationHelper.php -text
application/mxchange/config.php -text
inc/classes/exceptions/criteria/.htaccess -text
inc/classes/exceptions/criteria/class_FrameworkException.php -text
inc/classes/exceptions/database/.htaccess -text
+inc/classes/exceptions/database/class_DatabaseException.php -text
+inc/classes/exceptions/database/general/.htaccess -text
+inc/classes/exceptions/database/general/class_SqlException.php -text
inc/classes/exceptions/database/local_file/.htaccess -text
inc/classes/exceptions/database/local_file/class_SavePathIsEmptyException.php -text
inc/classes/exceptions/database/local_file/class_SavePathIsNoDirectoryException.php -text
inc/classes/exceptions/template/class_UnsupportedTemplateEngineException.php -text
inc/classes/exceptions/template/class_ViewHelperNotFoundException.php -text
inc/classes/exceptions/user/.htaccess -text
+inc/classes/exceptions/user/class_UserEmailMissingException.php -text
inc/classes/exceptions/user/class_UsernameMissingException.php -text
inc/classes/interfaces/.htaccess -text
inc/classes/interfaces/application/.htaccess -text
inc/classes/interfaces/criteria/class_Criteria.php -text
inc/classes/interfaces/criteria/extended/.htaccess -text
inc/classes/interfaces/criteria/extended/class_LocalCriteria.php -text
+inc/classes/interfaces/criteria/extended/class_LocalSearchCriteria.php -text
+inc/classes/interfaces/criteria/extended/class_StoreableCriteria.php -text
inc/classes/interfaces/database/.htaccess -text
inc/classes/interfaces/database/class_FrameworkDatabaseInterface.php -text
inc/classes/interfaces/database/frontend/.htaccess -text
inc/classes/interfaces/io/output/class_OutputStreamer.php -text
inc/classes/interfaces/language/.htaccess -text
inc/classes/interfaces/language/class_ManageableLanguage.php -text
+inc/classes/interfaces/login/.htaccess -text
+inc/classes/interfaces/login/class_LoginableUser.php -text
+inc/classes/interfaces/registration/.htaccess -text
+inc/classes/interfaces/registration/class_UserRegister.php -text
+inc/classes/interfaces/registry/.htaccess -text
+inc/classes/interfaces/registry/class_Register.php -text
+inc/classes/interfaces/registry/class_Registerable.php -text
inc/classes/interfaces/request/.htaccess -text
inc/classes/interfaces/request/class_Requestable.php -text
inc/classes/interfaces/resolver/.htaccess -text
inc/classes/interfaces/user/.htaccess -text
inc/classes/interfaces/user/class_ManageableUser.php -text
inc/classes/main/.htaccess -text
+inc/classes/main/actions/.htaccess -text
+inc/classes/main/actions/class_ -text
+inc/classes/main/actions/class_BaseAction.php -text
+inc/classes/main/actions/post_registration/.htaccess -text
+inc/classes/main/actions/post_registration/class_LoginAfterRegistrationAction.php -text
inc/classes/main/cache/.htaccess -text
inc/classes/main/cache/class_MemoryCache.php -text
inc/classes/main/class_ -text
inc/classes/main/controller/form/.htaccess -text
inc/classes/main/controller/form/class_WebDoFormController.php -text
inc/classes/main/criteria/.htaccess -text
+inc/classes/main/criteria/class_DataSetCriteria.php -text
inc/classes/main/criteria/class_SearchCriteria.php -text
+inc/classes/main/crypto/.htaccess -text
+inc/classes/main/crypto/class_CryptoHelper.php -text
inc/classes/main/database/.htaccess -text
inc/classes/main/database/class_ -text
inc/classes/main/database/class_BaseDatabaseFrontend.php -text
inc/classes/main/factories/web/.htaccess -text
inc/classes/main/factories/web/class_WebNewsFactory.php -text
inc/classes/main/filter/.htaccess -text
+inc/classes/main/filter/checkboxes/.htaccess -text
+inc/classes/main/filter/checkboxes/class_RulesAcceptedFilter.php -text
inc/classes/main/filter/class_ -text
inc/classes/main/filter/class_AbstractFilterDecorator.php -text
inc/classes/main/filter/class_FilterChain.php -text
+inc/classes/main/filter/decorator/.htaccess -text
+inc/classes/main/filter/null/.htaccess -text
+inc/classes/main/filter/null/class_NullFilter.php -text
inc/classes/main/filter/validator/.htaccess -text
+inc/classes/main/filter/validator/class_EmailValidatorFilter.php -text
+inc/classes/main/filter/validator/class_PasswordValidatorFilter.php -text
inc/classes/main/filter/validator/class_UserNameValidatorFilter.php -text
inc/classes/main/helper/.htaccess -text
inc/classes/main/helper/class_ -text
inc/classes/main/output/.htaccess -text
inc/classes/main/output/class_ConsoleOutput.php -text
inc/classes/main/output/class_WebOutput.php -text
+inc/classes/main/registration/.htaccess -text
+inc/classes/main/registration/class_BaseRegistration.php -text
+inc/classes/main/registry/.htaccess -text
+inc/classes/main/registry/class_Registry.php -text
inc/classes/main/request/.htaccess -text
inc/classes/main/request/class_HttpRequest.php -text
inc/classes/main/resolver/.htaccess -text
inc/classes/main/resolver/web/class_WebControllerResolver.php -text
inc/classes/main/response/.htaccess -text
inc/classes/main/response/class_HttpResponse.php -text
+inc/classes/main/result/.htaccess -text
+inc/classes/main/result/class_DatabaseResult.php -text
+inc/classes/main/rng/.htaccess -text
+inc/classes/main/rng/class_RandomNumberGenerator.php -text
inc/classes/main/template/.htaccess -text
inc/classes/main/template/class_TemplateEngine.php -text
inc/classes/main/user/.htaccess -text
--- /dev/null
+Deny from all
$this->setObjectDescription("Application-Helper");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
// Tidy up a little
$this->removeSystemArray();
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-//
-// Please remember that this include file is being loaded *before* the class
-// loader is loading classes from "exceptions", "interfaces" and "main"!
-//
-// Get an instance of the initializer
-$eval = sprintf("\$app = %s::getInstance();",
- FrameworkConfiguration::getInstance()->readConfig("app_helper_class")
-);
-eval($eval);
-
-// Set application name and version
-$app->setAppName("MXChange Mailtausch-Skript");
-$app->setAppVersion("0.3.0");
-$app->setAppShortName(FrameworkConfiguration::getInstance()->readConfig("selector_name"));
-
// Initialize output system
require(PATH . "inc/output.php");
// Get the database layer as well
require(PATH . "inc/database.php");
+// Generate call-back function
+$callback = sprintf("%s::getInstance",
+ FrameworkConfiguration::getInstance()->readConfig('app_helper_class')
+);
+
+// Get an instance of the helper
+$app = call_user_func_array($callback, array());
+
+// Set application name and version
+$app->setAppName("MXChange Mailtausch-Skript");
+$app->setAppVersion("0.3.0");
+$app->setAppShortName(FrameworkConfiguration::getInstance()->readConfig("selector_name"));
+
+// Set instances
+$app->setFileIoInstance($io);
+$app->setLanguageInstance($lang);
+$app->setDatabaseInstance($db);
+
// [EOF]
?>
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-// Is the variable set?
-if (!isset($application)) {
- // We need this!
- ApplicationEntryPoint::app_die("[Main:] Interne Variable <strong>application</strong> nicht gefunden!");
-}
+// Get config instance
+$cfg = FrameworkConfiguration::getInstance();
// Load all classes
-ClassLoader::getInstance()->loadClasses(sprintf("%s/%s/", FrameworkConfiguration::getInstance()->readConfig("application_path"), $application));
-
-// Include all classes
-ClassLoader::getInstance()->includeAllClasses();
+ClassLoader::getInstance()->loadClasses(sprintf("%s/%s/", $cfg->readConfig("application_path"), $cfg->readConfig("app_name")));
// Clean up the global namespace
unset($lowerClasses);
// Is there an application helper instance? We need the method main() for
// maining the application
-$app = ApplicationHelper::getInstance();
+$app = call_user_func_array(array(FrameworkConfiguration::getInstance()->readConfig('app_helper_class'), "getInstance"), array());
// Some sanity checks
if ((empty($app)) || (is_null($app))) {
// Call the entry point method
try {
- $eval = sprintf("%s::getInstance()->%s();",
- FrameworkConfiguration::getInstance()->readConfig("app_helper_class"),
- FrameworkConfiguration::getInstance()->readConfig("entry_method")
- );
- eval($eval);
+ call_user_func_array(array($app, FrameworkConfiguration::getInstance()->readConfig('entry_method')), array());
} catch (FrameworkException $e) {
ApplicationEntryPoint::app_die(sprintf("[Main:] Die Applikation <strong>%s</strong> kann nicht gestartet werden. Grund: <u>%s</u>",
$application,
));
}
-
// [EOF]
?>
}
}
-// Include all classes
-ClassLoader::getInstance()->includeAllClasses();
-
// Clean up the global namespace
unset($lowerClasses[3]); // Applications shall not have any middleware
unset($class);
--- /dev/null
+<?php
+/**
+ * A general database exception
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class DatabaseException extends FrameworkException {
+ /**
+ * The constructor
+ *
+ * @param $message Message from the exception
+ * @param $code Code number for the exception
+ * @return void
+ */
+ public function __construct ($message, $code) {
+ // Just call the parent constructor
+ parent::__construct($message, $code);
+ }
+}
+
+// [EOF]
+?>
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * A SQL exception thrown when an SQL error was detected.
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class SqlException extends DatabaseException {
+ /**
+ * The constructor
+ *
+ * @param $msgArray Message array
+ * @param $code Code number for the exception
+ * @return void
+ */
+ public function __construct (array $msgArray, $code) {
+ // Construct the message
+ $message = sprintf("[%s:%d] SQL error detected. Message from database: <u>%s</u>, code: <u>0x%s</u>.",
+ $msgArray[0]->__toString(),
+ $this->getLine(),
+ $msgArray[1],
+ dechex($msgArray[2])
+ );
+
+ // Call parent constructor
+ parent::__construct($message, $code);
+ }
+}
+
+// [EOF]
+?>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class SavePathIsEmptyException extends FrameworkException {
+class SavePathIsEmptyException extends DatabaseException {
/**
* The constructor
*
- * @param $message Message from the exception
- * @param $code Code number for the exception
+ * @param $message Message from the exception
+ * @param $code Code number for the exception
* @return void
*/
public function __construct (BaseFrameworkSystem $class, $code) {
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class SavePathIsNoDirectoryException extends FrameworkException {
+class SavePathIsNoDirectoryException extends DatabaseException {
/**
* The constructor
*
- * @param $message Message from the exception
- * @param $code Code number for the exception
+ * @param $message Message from the exception
+ * @param $code Code number for the exception
* @return void
*/
public function __construct ($path, $code) {
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class SavePathReadProtectedException extends FrameworkException {
+class SavePathReadProtectedException extends DatabaseException {
/**
* The constructor
*
- * @param $message Message from the exception
- * @param $code Code number for the exception
+ * @param $message Message from the exception
+ * @param $code Code number for the exception
* @return void
*/
public function __construct ($path, $code) {
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class SavePathWriteProtectedException extends FrameworkException {
+class SavePathWriteProtectedException extends DatabaseException {
/**
* The constructor
*
- * @param $message Message from the exception
- * @param $code Code number for the exception
+ * @param $message Message from the exception
+ * @param $code Code number for the exception
* @return void
*/
public function __construct ($path, $code) {
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class WrapperUserNameNotFoundException extends FrameworkException {
+class WrapperUserNameNotFoundException extends DatabaseException {
/**
* The constructor
*
- * @param $msgArray Message from the exception
- * @param $code Code number for the exception
+ * @param $msgArray Message from the exception
+ * @param $code Code number for the exception
* @return void
*/
public function __construct (array $msgArray, $code) {
--- /dev/null
+<?php
+/**
+ * A class for non-existing user emails
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class UserEmailMissingException extends FrameworkException {
+ /**
+ * The super constructor for all exceptions
+ *
+ * @param $msgArray The non-optional message for the exception
+ * @param $code An optional code for better debugging
+ * @return void
+ */
+ public function __construct(array $msgArray, $code = 0) {
+ // Create the message
+ $message = sprintf("[%s:%d] User email <u>%s</u> was not found.",
+ $msgArray[0]->__toString(),
+ $this->getLine(),
+ $msgArray[1]
+ );
+
+ // Make sure everything is assigned properly
+ parent::__construct($message, $code);
+ }
+}
+
+// [EOF]
+?>
*/
interface Criteria extends FrameworkInterface {
/**
- * Add extra criteria
+ * Add criteria
*
* @param $criteriaKey Criteria key
* @param $criteriaValue Criteria value
* @return void
*/
function addCriteria ($criteriaKey, $criteriaValue);
+
+ /**
+ * Add configured criteria
+ *
+ * @param $criteriaKey Criteria key
+ * @param $configEntry Configuration entry
+ * @return void
+ */
+ function addConfiguredCriteria ($criteriaKey, $configEntry);
}
//
--- /dev/null
+<?php
+/**
+ * An interface for local criterias
+ *
+ * @author Roland Haeder <webmaster@mxchange.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+interface LocalSearchCriteria extends Criteria {
+}
+
+//
+?>
--- /dev/null
+<?php
+/**
+ * An interface for storeable data sets
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+interface StoreableCriteria extends Criteria {
+}
+
+// [EOF]
+?>
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
interface FrameworkDatabaseInterface extends FrameworkInterface {
- /**
- * Saves a whole object by serializing it entirely or some specifyable
- * parts. Specifying parts must be done before this method is called. If
- * it is not done this method will serialize the whole object.
- *
- * @param $object An instance to the object we want to save
- * @return void
- * @see limitObject(ObjectLimits) limitObject
- */
- function saveObject ($object);
-
/**
* Analyses if a unique ID has already been used or not. This method does
* only pass the given ID through to the "real" database layer.
* isUniqueIdUsed() was not found
*/
function isUniqueIdUsed ($uniqueID, $inConstructor = false);
-
- /**
- * Gets cached data from the database layer and if not found fetch it from
- * the database again. This method does not return the header stuff because
- * The underlaying database class will return only the requested content.
- *
- * @param $idNumber The ID number which we need for looking up
- * the requested data
- * @return $cachedArray The maybe cached data from the database
- * @throws NullPointerException If $dbInstance is null
- * @throws NoObjectException If $dbInstance is not an object
- * @throws MissingMethodException If the required method
- * isUniqueIdUsed() was not found
- */
- function getObjectFromCachedData ($idNumber);
}
// [EOF]
*
* @return Object The fully re-created object or instance to
* ObjectContainer
+ * @deprecated
*/
function loadObject ();
/**
- * Makes sure that the database connection is alive
+ * Makes sure that the database connection is up and alive
*
* @return void
*/
* @param $tableName Name of the database table
* @param $criteria Search criteria class
* @return $resultData Result data of the query
+ * @throws UnsupportedCriteriaException If the criteria is unsupported
+ * @throws SqlException If an SQL error occurs
*/
function querySelect ($resultType, $tableName, Criteria $criteriaInstance);
+
+ /**
+ * "Inserts" a data set instance into a local file database folder
+ *
+ * @param $dataSetInstance A storeable data set
+ * @return void
+ * @throws SqlException If an SQL error occurs
+ */
+ function insertDataSet (StoreableCriteria $dataSetInstance);
}
// [EOF]
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * An interface for user login classes
+ *
+ * @author Roland Haeder <webmaster@mxchange.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+interface LoginableUser extends FrameworkInterface {
+ /**
+ * Logins the user with the given request containing the credential. The
+ * result of the login can be thrown by exception or, if prefered stored
+ * in a boolean attribute which is then readable by a matching getter.
+ *
+ * @param $requestInstance An instance of a Requestable class
+ * @return void
+ */
+ function doLogin (Requestable $requestInstance);
+}
+
+//
+?>
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * A class for user registration
+ *
+ * @author Roland Haeder <webmaster@mxchange.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+interface UserRegister extends FrameworkInterface {
+ /**
+ * Encrypt the given request key or throws an exception if the key was not
+ * found in the request
+ *
+ * @param $requestKey Key in request class
+ * @return void
+ */
+ function encryptPassword ($requestKey);
+
+ /**
+ * Perform things like informing assigned affilates about new registration
+ * before registration
+ *
+ * @return void
+ */
+ function doPreRegistration ();
+
+ /**
+ * Registers the new user account by insterting the request data into the
+ * database and paying some start credits or throw exceptions if this fails
+ *
+ * @return void
+ */
+ function registerNewUser ();
+
+ /**
+ * Perform things like notifying partner websites after registration is done
+ *
+ * @return void
+ */
+ function doPostRegistration ();
+
+ /**
+ * Do the action which is required after all registration steps are done.
+ * This can be a simple redirect to another webpage or displaying a message
+ * to the user. Or this can be a login step into the newly created account.
+ *
+ * @return void
+ */
+ function doPostAction ();
+
+ /**
+ * Adds registration elements to a given dataset instance
+ *
+ * @param $criteriaInstance An instance of a storeable criteria
+ * @return void
+ */
+ function addElementsToDataSet (StoreableCriteria $criteriaInstance);
+}
+
+//
+?>
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * An interface for registries
+ *
+ * @author Roland Haeder <webmaster@mxchange.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+interface Register extends FrameworkInterface {
+ /**
+ * Checks wether an instance key was found
+ *
+ * @param $instanceKey The key holding an instance in the registry
+ * @return $exists Wether the key exists in the registry
+ */
+ function instanceExists ($instanceKey);
+
+ /**
+ * Adds/overwrites a new instance to the registry at the given key
+ *
+ * @param $instanceKey The key to identify the instance
+ * @param $objectInstance An instance we shall store
+ * @return void
+ */
+ function addInstance ($instanceKey, Registerable $objectInstance);
+
+ /**
+ * Gets a registered instance or null if not found
+ *
+ * @param $instanceKey The key to identify the instance
+ * @return $objectInstance An instance we shall store
+ */
+ function getInstance ($instanceKey);
+}
+
+// [EOF]
+?>
--- /dev/null
+<?php
+/**
+ * A class for registerable classes
+ *
+ * @author Roland Haeder <webmaster@mxchange.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+interface Registerable extends FrameworkInterface {
+}
+
+// [EOF]
+?>
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ *
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class ???Action extends BaseAction implements Commandable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ protected function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set description
+ $this->setObjectDescription("");
+
+ // Generate unique key
+ $this->generateUniqueId();
+ }
+
+ /**
+ * Creates an instance of this action
+ *
+ * @return $actionInstance An instance of this action class
+ */
+ public final static function create???Action () {
+ // Get a new instance
+ $actionInstance = new ???Action();
+
+ // Return the instance
+ return $actionInstance;
+ }
+
+ /**
+ * Executes the command with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ $this->partialStub("You have to implement me.");
+ }
+}
+
+// [EOF]
+?>
--- /dev/null
+<?php
+/**
+ * A general action class
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.3.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.mxchange.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class BaseAction extends BaseFrameworkSystem {
+ /**
+ * Protected constructor
+ *
+ * @param $className Name of the class
+ * @return void
+ */
+ protected function __construct ($className) {
+ // Call parent constructor
+ parent::__construct($className);
+
+ // Clean up a little
+ $this->removeNumberFormaters();
+ $this->removeSystemArray();
+ }
+}
+
+// [EOF]
+?>
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * A post registration action to login after the registration is done
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class LoginAfterRegistrationAction extends BaseAction implements Commandable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ protected function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set description
+ $this->setObjectDescription("Post registration action for logging in");
+
+ // Generate unique key
+ $this->generateUniqueId();
+ }
+
+ /**
+ * Creates an instance of this action
+ *
+ * @return $actionInstance An instance of this action class
+ */
+ public final static function createLoginAfterRegistrationAction () {
+ // Get a new instance
+ $actionInstance = new LoginAfterRegistrationAction();
+
+ // Return the instance
+ return $actionInstance;
+ }
+
+ /**
+ * Executes the command with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ // Get a login class from factory
+ $loginInstance = ObjectFactory::createObjectByConfiguredName('login_user');
+
+ // Login the user by the request instance
+ $loginInstance->doLogin($requestInstance);
+
+ // Was the login fine? Then redirect here
+ if ($loginInstance->ifLoginWasSuccessfull()) {
+ // Try to redirect here
+ try {
+ $responseInstance->redirectConfiguredUrl('app_login');
+ } catch (FrameworkException $e) {
+ // Something went wrong here!
+ $responseInstance->addFatalMessage($e->getMessage());
+ }
+ } else {
+ // Attach error message to the response
+ $responseInstance->addFatalMessage('failed_login_after_registration');
+ }
+ }
+}
+
+// [EOF]
+?>
private $dataCache = null;
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
$this->setObjectDescription("Memory cache");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
*/
protected function initCache () {
// Now create the "data cache"
- $this->dataCache = new FrameworkArrayObject();
+ $this->dataCache = new FrameworkArrayObject("FakedDataCache");
}
/**
*
*
* @author Roland Haeder <webmaster@ship-simu.org>
- * @version 0.3.0
+ * @version 0.0.0
* @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
* @license GNU GPL 3.0 or any newer version
- * @link http://www.mxchange.org
+ * @link http://www.ship-simu.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
*/
class extends BaseFrameworkSystem {
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
$this->setObjectDescription("");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
*/
class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
/**
- * The instance to the debug output handler (should be DebugConsoleOutput or DebugWebOutput)
- *
- * @see DebugConsoleOutput
- * @see DebugWebOutput
- */
- private static $debug = null;
-
- /**
- * The instance to the web output handler (should be WebOutput)
- *
- * @see WebOutput
- */
- private static $webOutput = null;
-
- /**
- * The instance to the compression layer which should be CompressorChannel
- */
- private static $compressor = null;
-
- /**
- * The configuration instance which shall be FrameworkConfiguration
- */
- private static $cfgInstance = null;
-
- /**
- * The instance to the database layer which should be DatabaseConnection
+ * Instance to an application helper class
*/
- private $dbInstance = null;
+ private static $applicationInstance = null;
/**
- * Instance to an application helper class
+ * The language instance for the template loader
*/
- private $applicationInstance = null;
+ private static $langInstance = null;
/**
* The real class name
*/
private $decimals = ","; // German
- /**
- * The language instance for the template loader
- */
- private $langInstance = null;
-
/**
* The file I/O instance for the template loader
*/
*/
private $systemClasses = array(
"DebugMiddleware", // Debug middleware output sub-system
+ "Registry", // Object registry
+ "ObjectFactory", // Object factory
"DebugWebOutput", // Debug web output sub-system
+ "WebOutput", // Web output sub-system
+ "CompressorChannel", // Compressor sub-system
"DebugConsoleOutput", // Debug console output sub-system
"DebugErrorLogOutput", // Debug error_log() output sub-system
- "CompressorChannel", // Compressor sub-system
"FrameworkDirectoryPointer", // Directory handler sub-system
"NullCompressor", // Null compressor
"Bzip2Compressor", // BZIP2 compressor
"GzipCompressor", // GZIP compressor
- "WebOutput", // Web output sub-system
);
+ /* No longer used:
+ */
+
/**
* Private super constructor
*
// Set real class
$this->setRealClass($class);
- // Init this instance
- $this->initInstance($class);
+ // Initialize the class if the registry is there
+ if ((class_exists('Registry')) && (Registry::isInitialized() === false)) {
+ $this->initInstance();
+ }
}
/**
} elseif (is_string($arg)) {
// String
$argsString .= "\"".$arg."\"(string)";
+ } elseif (is_null($arg)) {
+ // Null
+ $argsString .= "(null)";
} else {
// Unknown type (please report!)
$argsString .= $arg."(unknown!)";
}
/**
- * Initializes the instance
+ * Private initializer for this class
*
* @return void
*/
- public function initInstance ($class) {
- // Get the current (singleton) configuration instance
- $this->setConfigInstance(FrameworkConfiguration::createFrameworkConfiguration());
-
- // Is the class weather debug nor compressor channel?
- if (!in_array($class, $this->systemClasses)) {
- // Initialize debug instance
- if (is_null($this->getDebugInstance())) {
- // Set the debug output system if it is not debug class ;)
- $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->readConfig('debug_engine')));
- }
-
- // Initialize web instance
- if (is_null($this->getWebOutputInstance())) {
- // Generate the eval() command
- $eval = sprintf("\$this->setWebOutputInstance(%s::create%s(\"%s\"));",
- $this->getConfigInstance()->readConfig('web_engine'),
- $this->getConfigInstance()->readConfig('web_engine'),
- $this->getConfigInstance()->readConfig('web_content_type')
- );
-
- // Debug message
- if (defined('DEBUG_EVAL')) $this->getDebugInstance()->output(sprintf("[%s:] Constructed PHP command: <pre><em>%s</em></pre><br />\n",
- $this->__toString(),
- htmlentities($eval)
- ));
-
- // Run the command
- eval($eval);
- }
-
- // Initialize compressor channel
- if (is_null($this->getCompressorChannel())) {
- // Set the compressor channel
- $this->setCompressorChannel(CompressorChannel::createCompressorChannel(sprintf("%s%s",
- PATH,
- $this->getConfigInstance()->readConfig('compressor_base_path')
- )));
- }
-
- // Initialize database middleware
- if (is_null($this->getDatabaseInstance())) {
- // Get the middleware instance
- $db = DatabaseConnection::getInstance();
- if (is_object($db)) {
- // Set the database middleware
- $this->setDatabaseInstance($db);
- }
- }
+ private final function initInstance () {
+ // Is this a system class?
+ if (!in_array($this->__toString(), $this->systemClasses)) {
+ // Add application helper to our class
+ $this->systemclasses[] = $this->getConfigInstance()->readConfig('app_helper_class');
+
+ // Set debug instance
+ $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->readConfig('debug_engine')));
+
+ // Get output instance and set it
+ $outputInstance = ObjectFactory::createObjectByConfiguredName('web_engine', array($this->getConfigInstance()->readConfig('web_content_type')));
+ $this->setWebOutputInstance($outputInstance);
+
+ // Set the compressor channel
+ $this->setCompressorChannel(CompressorChannel::createCompressorChannel(sprintf("%s%s",
+ PATH,
+ $this->getConfigInstance()->readConfig('compressor_base_path')
+ )));
+
+ // Initialization done! :D
+ Registry::isInitialized("OK");
+ } elseif ($this->__toString() == "DebugMiddleware") {
+ // Set configuration instance
+ $this->setConfigInstance(FrameworkConfiguration::createFrameworkConfiguration());
}
}
/**
* Setter for language instance
*
- * @param $configInstance The configuration instance which shall
- * be FrameworkConfiguration
+ * @param $configInstance The configuration instance which shall
+ * be FrameworkConfiguration
* @return void
*/
public final function setConfigInstance (FrameworkConfiguration $configInstance) {
- self::$cfgInstance = $configInstance;
+ Registry::getRegistry()->addInstance('config', $configInstance);
}
/**
* @return $cfhInstance - Configuration instance
*/
protected final function getConfigInstance () {
- return self::$cfgInstance;
+ return Registry::getRegistry()->getInstance('config');
}
/**
* @return void
*/
public final function setDebugInstance (DebugMiddleware $debugInstance) {
- self::$debug = $debugInstance;
+ Registry::getRegistry()->addInstance('debug', $debugInstance);
}
/**
* @return $debug - Instance to class DebugConsoleOutput or DebugWebOutput
*/
public final function getDebugInstance () {
- return self::$debug;
+ return Registry::getRegistry()->getInstance('debug');
}
/**
* @return void
*/
public final function setWebOutputInstance (OutputStreamer $webInstance) {
- self::$webOutput = $webInstance;
+ Registry::getRegistry()->addInstance('web_output', $webInstance);
}
/**
* @return $webOutput - Instance to class WebOutput
*/
public final function getWebOutputInstance () {
- return self::$webOutput;
+ return Registry::getRegistry()->getInstance('web_output');
}
/**
- * Static setter for database instance
+ * Setter for database instance
*
* @param $dbInstance The instance for the database connection
* (forced DatabaseConnection)
* @return void
*/
public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
- $this->dbInstance = $dbInstance;
+ Registry::getRegistry()->addInstance('dbInstance', $dbInstance);
+ }
+
+ /**
+ * Getter for database layer
+ *
+ * @return $dbInstance The database layer instance
+ */
+ public final function getDatabaseInstance () {
+ if ((class_exists('Registry')) && (Registry::isInitialized() === true)) {
+ return Registry::getRegistry()->getInstance('dbInstance');
+ } else {
+ return null;
+ }
+ }
+
+ /**
+ * Setter for compressor channel
+ *
+ * @param $compressorChannel An instance of CompressorChannel
+ * @return void
+ */
+ public final function setCompressorChannel (CompressorChannel $compressorChannel) {
+ Registry::getRegistry()->addInstance('compressor', $compressorChannel);
+ }
+
+ /**
+ * Getter for compressor channel
+ *
+ * @return $compressor The compressor channel
+ */
+ public final function getCompressorChannel () {
+ return Registry::getRegistry()->getInstance('compressor');
+ }
+
+ /**
+ * Protected getter for a manageable application helper class
+ *
+ * @return $applicationInstance An instance of a manageable application helper class
+ */
+ protected final function getApplicationInstance () {
+ return self::$applicationInstance;
+ }
+
+ /**
+ * Setter for a manageable application helper class
+ *
+ * @param $applicationInstance An instance of a manageable application helper class
+ * @return void
+ */
+ public final function setApplicationInstance (ManageableApplication $applicationInstance) {
+ self::$applicationInstance = $applicationInstance;
}
/**
*
* @return void
*/
- public final function createUniqueID () {
- // Existiert noch keine?
+ public final function generateUniqueId () {
+ // Is the id set for this class?
if (empty($this->uniqueID)) {
// Correct missing class name
$corrected = true;
}
- // Neue ID erstellen
+ // Cache datbase instance
+ $db = $this->getDatabaseInstance();
+
+ // Generate new id
$tempID = false;
while (true) {
// Generate a unique ID number
// Try to figure out if the ID number is not yet used
try {
- if (is_object($this->getDatabaseInstance())) {
- $isUsed = $this->getDatabaseInstance()->isUniqueIdUsed($tempID, true);
+ // Is this a registry?
+ if ($this->__toString() == "Registry") {
+ // Registry, then abort here
+ break;
+ } elseif (is_object($db)) {
+ $isUsed = $db->isUniqueIdUsed($tempID, true);
}
} catch (FrameworkException $e) {
// Catches all and ignores all ;-)
$tempID !== false
) && (
(
- $this->getDatabaseInstance() === null
+ $db === null
) || (
(
- is_object($this->getDatabaseInstance())
+ is_object($db)
) && (
!$isUsed
)
* Formats computer generated price values into human-understandable formats
* with thousand and decimal seperators.
*
- * @param $value The in computer format value for a price
- * @param $currency The currency symbol (use HTML-valid characters!)
- * @param $decNum Number of decimals after commata
- * @return $price The for the current language formated price string
+ * @param $value The in computer format value for a price
+ * @param $currency The currency symbol (use HTML-valid characters!)
+ * @param $decNum Number of decimals after commata
+ * @return $price The for the current language formated price string
* @throws MissingDecimalsThousandsSeperatorException If decimals or
* thousands seperator
* is missing
}
/**
- * Getter for database layer
+ * Private getter for language instance
*
- * @return $dbInstance The database layer instance
+ * @return $langInstance An instance to the language sub-system
*/
- public final function getDatabaseInstance () {
- return $this->dbInstance;
+ protected final function getLanguageInstance () {
+ return self::$langInstance;
}
/**
- * Setter for compressor channel
+ * Setter for language instance
*
- * @param $compressorChannel An instance of CompressorChannel
+ * @param $langInstance An instance to the language sub-system
* @return void
+ * @see LanguageSystem
*/
- public final function setCompressorChannel (CompressorChannel $compressorChannel) {
- self::$compressor = $compressorChannel;
- }
-
- /**
- * Getter for compressor channel
- *
- * @return $compressor The compressor channel
- */
- public final function getCompressorChannel () {
- return self::$compressor;
+ public final function setLanguageInstance (ManageableLanguage $langInstance) {
+ self::$langInstance = $langInstance;
}
/**
return $str;
}
- /**
- * Private getter for language instance
- *
- * @return $langInstance An instance to the language sub-system
- */
- protected final function getLanguageInstance () {
- return $this->langInstance;
- }
-
- /**
- * Setter for language instance
- *
- * @param $langInstance An instance to the language sub-system
- * @return void
- * @see LanguageSystem
- */
- public final function setLanguageInstance (ManageableLanguage $langInstance) {
- $this->langInstance = $langInstance;
- }
-
/**
* Private getter for file IO instance
*
$this->fileIOInstance = $fileIOInstance;
}
- /**
- * Protected getter for a manageable application helper class
- *
- * @return $applicationInstance An instance of a manageable application helper class
- */
- protected final function getApplicationInstance () {
- return $this->applicationInstance;
- }
-
- /**
- * Setter for a manageable application helper class
- *
- * @param $applicationInstance An instance of a manageable application helper class
- * @return void
- */
- public final function setApplicationInstance (ManageableApplication $applicationInstance) {
- $this->applicationInstance = $applicationInstance;
- }
-
/**
* Prepare the template engine (TemplateEngine by default) for a given
* application helper instance (ApplicationHelper by default).
}
// Initialize the template engine
- $tplEngine = null;
- $eval = sprintf("\$tplEngine = %s::create%s(
- \"%s\",
- \$appInstance->getLanguageInstance(),
- \$appInstance->getFileIoInstance()
-);",
- $this->getConfigInstance()->readConfig('tpl_engine'),
- $this->getConfigInstance()->readConfig('tpl_engine'),
- $fqfn
- );
-
- // Debug message
- if ((!is_null($this->getDebugInstance())) && (defined('DEBUG_EVAL'))) {
- $this->getDebugInstance()->output(sprintf("[%s:] Constructed PHP command: <pre><em>%s</em></pre><br />\n",
- $this->__toString(),
- htmlentities($eval)
- ));
- }
-
- // Run the command
- eval($eval);
-
- // Is it a valid instance?
- if (is_null($tplEngine)) {
- // No class returned
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } elseif (!$tplEngine instanceof CompileableTemplate) {
- // Not an object! ;-(
- throw new UnsupportedTemplateEngineException($tplEngine, self::EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED);
- }
+ $tplEngine = ObjectFactory::createObjectByConfiguredName('tpl_engine', array($fqfn, $appInstance->getLanguageInstance(), $appInstance->getFileIoInstance()));
// Return the prepared instance
return $tplEngine;
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class FrameworkArrayObject extends ArrayObject {
+ /**
+ * Real class name
+ */
+ private $realClass = "";
+
+ /**
+ * Public constructor for setting real class name
+ *
+ * @param $className Real class name
+ * @return void
+ */
+ public function __construct ($className) {
+ $this->realClass = (string) $className;
+ }
+
/**
* Get real class' name back
*
* @return $realClass The class' real name
*/
public function __toString () {
- return get_class($this);
+ return $this->realClass;
}
}
$this->setObjectDescription("");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeSystemArray();
$this->setObjectDescription("Command for handling forms on a centralized place");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeSystemArray();
$this->setObjectDescription("Command for the "home" page");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeSystemArray();
$this->setObjectDescription("Command for the registration form");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeSystemArray();
$this->setObjectDescription("BZIP2 compressor");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
$this->setObjectDescription("GZIP compressor");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
$this->setObjectDescription("Null compressor");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
$this->setObjectDescription("General console tools");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
*/
class Controller extends BaseController implements Controller {
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
$this->setObjectDescription("Ein spezieller Controller");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeSystemArray();
$this->setObjectDescription("Default controller for all other requests");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
$this->setObjectDescription("Default controller with news");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
*/
class WebDoFormController extends BaseController implements Controller {
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
$this->setObjectDescription("Controller for handling forms");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
--- /dev/null
+<?php
+/**
+ * A set of data storeable in databases
+ *
+ * @see DatabaseFrontendInterface - An interface for database frontends (front-end to the application)
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class DataSetCriteria extends BaseFrameworkSystem implements StoreableCriteria {
+ /**
+ * Table name
+ */
+ private $tableName = "";
+
+ /**
+ * Table columns (criteria) to store
+ */
+ private $tableColumns = array();
+
+ /**
+ * Unique key
+ */
+ private $uniqueKey = "";
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ protected function __construct() {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set part description
+ $this->setObjectDescription("Storeable data set for databases");
+
+ // Create unique ID number
+ $this->generateUniqueId();
+
+ // Clean up a little
+ $this->removeNumberFormaters();
+ $this->removeSystemArray();
+ }
+
+ /**
+ * Creates an instance of this criteria
+ *
+ * @return $criteriaInstance An instance of this criteria
+ */
+ public final static function createDataSetCriteria () {
+ // Get a new instance
+ $criteriaInstance = new DataSetCriteria();
+
+ // Return the instance
+ return $criteriaInstance;
+ }
+
+ /**
+ * Add criteria
+ *
+ * @param $criteriaKey Criteria key
+ * @param $criteriaValue Criteria value
+ * @return void
+ */
+ public function addCriteria ($criteriaKey, $criteriaValue) {
+ $this->tableColumns[(string) $criteriaKey] = $criteriaValue;
+ }
+
+ /**
+ * Add configured criteria
+ *
+ * @param $criteriaKey Criteria key
+ * @param $configEntry Configuration entry
+ * @return void
+ */
+ public function addConfiguredCriteria ($criteriaKey, $configEntry) {
+ // Add configuration entry as criteria
+ $value = $this->getConfigInstance()->readConfig($configEntry);
+ $this->addCriteria($criteriaKey, $value);
+ }
+
+ /**
+ * Setter for table name
+ *
+ * @param $tableName Name of the table to set
+ * @return void
+ */
+ public final function setTableName ($tableName) {
+ $this->tableName = (string) $tableName;
+ }
+
+ /**
+ * Getter for table name
+ *
+ * @return $tableName Name of the table to set
+ */
+ public final function getTableName () {
+ return $this->tableName;
+ }
+
+ /**
+ * Setter for unique key
+ *
+ * @param $uniqueKey Column to use as unique key
+ * @return void
+ */
+ public final function setUniqueKey ($uniqueKey) {
+ $this->uniqueKey = (string) $uniqueKey;
+ }
+
+ /**
+ * Getter for unique key
+ *
+ * @return $uniqueKey Column to use as unique key
+ */
+ public final function getUniqueKey () {
+ return $this->uniqueKey;
+ }
+
+ /**
+ * Getter for unique key value
+ *
+ * @return $uniqueValue Value of the unique key
+ */
+ public final function getUniqueValue () {
+ return $this->tableColumns[$this->getUniqueKey()];
+ }
+
+ /**
+ * Getter for criteria array
+ *
+ * @return $tableColumns
+ */
+ public final function getCriteriaArray () {
+ return $this->tableColumns;
+ }
+}
+
+// [EOF]
+?>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class SearchCriteria extends BaseFrameworkSystem implements LocalCriteria {
+class SearchCriteria extends BaseFrameworkSystem implements LocalSearchCriteria {
/**
* Criteria to handle
*/
private $skip = 0;
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
$this->setObjectDescription("Search criteria class");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
}
/**
- * Add extra criteria
+ * Add criteria
*
* @param $criteriaKey Criteria key
* @param $criteriaValue Criteria value
$this->searchCriteria[$criteriaKey] = $criteriaValue;
}
+ /**
+ * Add configured criteria
+ *
+ * @param $criteriaKey Criteria key
+ * @param $configEntry Configuration entry
+ * @return void
+ */
+ public function addConfiguredCriteria ($criteriaKey, $configEntry) {
+ // Add the configuration entry as a criteria
+ $value = $this->getConfigInstance()->readConfig($configEntry);
+ $this->addCriteria($criteriaKey, $value);
+ }
+
/**
* Setter for limit
*
$this->limit = $limit;
}
+ /**
+ * Getter for limit
+ *
+ * @param
+ * @return $limit Search limit
+ */
+ public final function getLimit () {
+ return $this->limit;
+ }
+
/**
* Setter for skip
*
$this->skip = $skip;
}
+ /**
+ * Getter for skip
+ *
+ * @param
+ * @return $skip Search skip
+ */
+ public final function getSkip () {
+ return $this->skip;
+ }
+
/**
* "Getter" for a cache key
*
// Return the cache key
return $cacheKey;
}
+
+ /**
+ * Get criteria element or null if not found
+ *
+ * @param $criteria The criteria we want to have
+ * @return $value Wether the value of the critera or null
+ */
+ public function getCriteriaElemnent ($criteria) {
+ // Default is not found
+ $value = null;
+
+ // Is the criteria there?
+ if (isset($this->searchCriteria[$criteria])) {
+ // Then use it
+ $value = $this->searchCriteria[$criteria];
+ }
+
+ // Return the value
+ return $value;
+ }
}
// [EOF]
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * A helper class for cryptographical things like hashing passwords and so on
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.3.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.mxchange.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class CryptoHelper extends BaseFrameworkSystem {
+ /**
+ * An instance of this own clas
+ */
+ private static $selfInstance = null;
+
+ /**
+ * Instance of the random number generator
+ */
+ private $rngInstance = null;
+
+ /**
+ * Salt for hashing operations
+ */
+ private $salt = "";
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ protected function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set part description
+ $this->setObjectDescription("Cryptographical helper");
+
+ // Create unique ID number
+ $this->generateUniqueId();
+
+ // Clean up a little
+ $this->removeNumberFormaters();
+ $this->removeSystemArray();
+ }
+
+ /**
+ * Creates an instance of this class
+ *
+ * @return $cryptoInstance An instance of this crypto helper class
+ */
+ public final static function createCryptoHelper () {
+ // Get a new instance
+ $cryptoInstance = self::getInstance();
+
+ // Initialize the hasher
+ $cryptoInstance->initHasher();
+
+ // Return the instance
+ return $cryptoInstance;
+ }
+
+ /**
+ * Get a singleton instance of this class
+ *
+ * @return $selfInstance An instance of this crypto helper class
+ */
+ public final static function getInstance () {
+ // Is no instance there?
+ if (is_null(self::$selfInstance)) {
+ // Then get a new one
+ self::$selfInstance = new CryptoHelper();
+ }
+
+ // Return the instance
+ return self::$selfInstance;
+ }
+
+ /**
+ * Initializes the hasher for different purposes.
+ *
+ * @return void
+ */
+ protected function initHasher () {
+ // Initialize the random number generator which is required by some crypto methods
+ $this->rngInstance = ObjectFactory::createObjectByConfiguredName('rng_class');
+
+ // Generate a salt for the hasher
+ $this->generateSalt();
+ }
+
+ /**
+ * Generates the salt based on configured length
+ *
+ * @return void
+ */
+ private function generateSalt () {
+ // Get a random string from the RNG
+ $randomString = $this->rngInstance->makeRandomString();
+
+ // Get config entry for salt length
+ $length = $this->getConfigInstance()->readConfig('salt_length');
+
+ // Keep only defined number of characters
+ $this->salt = substr(sha1($randomString), -$length, $length);
+ }
+
+ /**
+ * Hashes a password with salt and returns the hash. If an old previous hash
+ * is supplied the method will use the first X chars of that hash for hashing
+ * the password. This is useful if you want to check if the password is
+ * identical for authorization purposes.
+ *
+ * @param $plainPassword The plain password to use
+ * @param $oldHash A previously hashed password
+ * @return $hashed The hashed and salted password
+ */
+ public function hashPassword ($plainPassword, $oldHash = "") {
+ // Is the old password set?
+ if (empty($oldHash)) {
+ // No, then use the current salt
+ $salt = $this->salt;
+ } else {
+ // Use the salt from hash, first get length
+ $length = $this->getConfigInstance()->readConfig('salt_length');
+
+ // Then extract the X first characters from the hash as our salt
+ $salt = substr($oldHash, 0, $length);
+ }
+
+ // Hash the password with salt
+ $hashed = $salt . md5(sprintf($this->getConfigInstance()->readConfig('hash_mask'),
+ $salt,
+ $this->rngInstance->getExtraSalt(),
+ $plainPassword
+ ));
+
+ // And return it
+ return $hashed;
+ }
+}
+
+// [EOF]
+?>
*
* @return void
*/
- protected function __construct($class) {
+ protected function __construct($class = __CLASS__) {
// Call parent constructor
- parent::constructor(__CLASS__);
+ parent::__construct($class);
// Set part description
$this->setObjectDescription("");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
abstract class BaseDatabaseFrontend extends BaseFrameworkSystem implements DatabaseFrontendInterface, LimitableObject {
+ // Constants for exceptions
+ const EXCEPTION_SQL_QUERY = 0xc00;
+
/**
* The limiter instance
*/
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class LocalFileDatabase extends BaseDatabaseFrontend implements DatabaseFrontendInterface {
+
+ // Constants for MySQL backward-compatiblity (PLEASE FIX THEM!)
+ const DB_CODE_TABLE_MISSING = 0x000;
+ const DB_CODE_TABLE_UNWRITEABLE = 0x001;
+
/**
* Save path for "file database"
*/
private $alreadyConnected = false;
/**
- * The private constructor. Do never instance from outside!
- * You need to set a local file path. The class will then validate it.
+ * Last error message
+ */
+ private $lastError = "";
+
+ /**
+ * Last exception
+ */
+ private $lastException = null;
+
+ /**
+ * The protected constructor. Do never instance from outside! You need to
+ * set a local file path. The class will then validate it.
*
* @return void
*/
$this->setObjectDescription("Class for local file databases");
// Create unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeSystemArray();
return $this->savePath;
}
+ /**
+ * Getter for last error message
+ *
+ * @return $lastError Last error message
+ */
+ public final function getLastError () {
+ return $this->lastError;
+ }
+
+ /**
+ * Getter for last exception
+ *
+ * @return $lastException Last thrown exception
+ */
+ public final function getLastException () {
+ return $this->lastException;
+ }
+
/**
* Saves a given object to the local file system by serializing and
* transparently compressing it
*
- * @param $object The object we shall save to the local file system
+ * @param $object The object we shall save to the local file system
* @return void
- * @throws NullPointerException If the object instance is null
- * @throws NoObjectException If the parameter $object is not
- * an object
*/
- public final function saveObject ($object) {
- // Some tests on the parameter...
- if (is_null($object)) {
- // Is null, throw exception
- throw new NullPointerException($object, self::EXCEPTION_IS_NULL_POINTER);
- } elseif (!is_object($object)) {
- // Is not an object, throw exception
- throw new NoObjectException($object, self::EXCEPTION_IS_NO_OBJECT);
- } elseif (!method_exists($object, '__toString')) {
- // A highly required method was not found... :-(
- throw new MissingMethodException(array($object, '__toString'), self::EXCEPTION_MISSING_METHOD);
- }
-
+ public final function saveObject (FrameworkInterface $object) {
// Get a string containing the serialized object. We cannot exchange
// $this and $object here because $object does not need to worry
// about it's limitations... ;-)
/**
* Get a serialized string from the given object
*
- * @param $object The object we want to serialize and transparently
- * compress
- * @return $serialized A string containing the serialzed/compressed object
+ * @param $object The object we want to serialize and transparently
+ * compress
+ * @return $serialized A string containing the serialzed/compressed object
* @see ObjectLimits An object holding limition information
* @see SerializationContainer A special container class for e.g.
- * attributes from limited objects
+ * attributes from limited objects
*/
- private function serializeObject ($object) {
+ private function serializeObject (FrameworkInterface $object) {
// If there is no limiter instance we serialize the whole object
// otherwise only in the limiter object (ObjectLimits) specified
// attributes summarized in a special container class
* Analyses if a unique ID has already been used or not by search in the
* local database folder.
*
- * @param $uniqueID A unique ID number which shall be checked
- * before it will be used
- * @param $inConstructor If we got called in a de/con-structor or
- * from somewhere else
+ * @param $uniqueID A unique ID number which shall be checked
+ * before it will be used
+ * @param $inConstructor If we got called in a de/con-structor or
+ * from somewhere else
* @return $isUnused true = The unique ID was not found in the database,
- * false = It is already in use by an other object
- * @throws NoArrayCreatedException If explode() fails to create an array
+ * false = It is already in use by an other object
+ * @throws NoArrayCreatedException If explode() fails to create an array
* @throws InvalidArrayCountException If the array contains less or
* more than two elements
*/
// Initialize the search loop
$isValid = false;
- while ($dataFile = $dirInstance->readDirectoryExcept(array(".", ".."))) {
+ while ($dataFile = $dirInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn"))) {
// Generate FQFN for testing
$fqfn = sprintf("%s/%s", $pathName, $dataFile);
$this->setLastFile($fqfn);
$this->lastFile = $fqfn;
}
+ /**
+ * Reset the last error and exception instance. This should be done after
+ * a successfull "query"
+ *
+ * @return void
+ */
+ private final function resetLastError () {
+ $this->lastError = "";
+ $this->lastException = null;
+ }
+
/**
* Getter for last read file
*
* @param $criteria Local search criteria class
* @return $resultData Result data of the query
* @throws UnsupportedCriteriaException If the criteria is unsupported
+ * @throws SqlException If an "SQL error" occurs
*/
public function querySelect ($resultType, $tableName, Criteria $criteriaInstance) {
+ // The result is null by any errors
+ $resultData = null;
+
// Is this criteria supported?
- if (!$criteriaInstance instanceof LocalCriteria) {
+ if (!$criteriaInstance instanceof LocalSearchCriteria) {
// Not supported by this database layer
throw new UnsupportedCriteriaException(array($this, $criteriaInstance), self::EXCEPTION_REQUIRED_INTERFACE_MISSING);
}
- // A "select" query on local files is not that easy, so begin slowly with it...
- $this->partialStub(sprintf("type=%s,table=%s,criteria=%s", $resultType, $tableName, $criteriaInstance));
+ // Create full path name
+ $pathName = $this->getSavePath() . $tableName . '/';
+
+ // A "select" query is not that easy on local files, so first try to
+ // find the "table" which is in fact a directory on the server
+ try {
+ // Get a directory pointer instance
+ $directoryInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($pathName);
+
+ // Initialize the result data, this need to be rewritten e.g. if a local file cannot be read
+ $resultData = array(
+ 'status' => "ok",
+ 'rows' => array()
+ );
+
+ // Initialize limit/skip
+ $limitFound = 0; $skipFound = 0;
+
+ // Read the directory with some exceptions
+ while (($dataFile = $directoryInstance->readDirectoryExcept(array(".", "..", ".htaccess", ".svn"))) && ($limitFound < $criteriaInstance->getLimit())) {
+ // Open this file for reading
+ $filePointer = FrameworkFileInputPointer::createFrameworkFileInputPointer($pathName . $dataFile);
+
+ // Get the raw data and BASE64-decode it
+ $compressedData = base64_decode($filePointer->readLinesFromFile());
+
+ // Close the file and throw the instance away
+ $filePointer->closeFile();
+ unset($filePointer);
+
+ // Decompress it
+ $serializedData = $this->getCompressorChannel()->getCompressor()->decompressStream($compressedData);
+
+ // Unserialize it
+ $dataArray = unserialize($serializedData);
+
+ // Is this an array?
+ if (is_array($dataArray)) {
+ // Search in the criteria with FMFW (First Matches, First Wins)
+ foreach ($dataArray as $key=>$value) {
+ // Get criteria element
+ $criteria = $criteriaInstance->getCriteriaElemnent($key);
+
+ // Is the criteria met?
+ if ((!is_null($criteria)) && ($criteria == $value)) {
+
+ // Shall we skip this entry?
+ if ($criteriaInstance->getSkip() > 0) {
+ // We shall skip some entries
+ if ($skipFound < $criteriaInstance->getSkip()) {
+ // Skip this entry
+ $skipFound++;
+ break;
+ } // END - if
+ } // END - if
+
+ // Entry found!
+ $resultData['rows'][] = $dataArray;
+ $limitFound++;
+ break;
+ } // END - if
+ } // END - foreach
+ } // END - if
+ } // END - while
+
+ // Close directory and throw the instance away
+ $directoryInstance->closeDirectory();
+ unset($directoryInstance);
+
+ // Reset last error message and exception
+ $this->resetLastError();
+ } catch (PathIsNoDirectoryException $e) {
+ // Path not found means "table not found" for real databases...
+ $this->lastException = $e;
+ $this->lastError = $e->getMessage();
+
+ // So throw an SqlException here with faked error message
+ throw new SqlException (array($this, sprintf("Table '%s' not found", $tableName), self::DB_CODE_TABLE_MISSING), self::EXCEPTION_SQL_QUERY);
+ } catch (FrameworkException $e) {
+ // Catch all exceptions and store them in last error
+ $this->lastException = $e;
+ $this->lastError = $e->getMessage();
+ }
+
+ // Return the gathered result
+ return $resultData;
+ }
+
+ /**
+ * "Inserts" a data set instance into a local file database folder
+ *
+ * @param $dataSetInstance A storeable data set
+ * @return void
+ * @throws SqlException If an SQL error occurs
+ */
+ public function insertDataSet (StoreableCriteria $dataSetInstance) {
+ // Create full path name
+ $fqfn = sprintf("%s%s/%s.%s",
+ $this->getSavePath(),
+ $dataSetInstance->getTableName(),
+ md5($dataSetInstance->getUniqueValue()),
+ $this->getFileExtension()
+ );
+
+ // Try to save the request away
+ try {
+ // Get a file pointer instance
+ $filePointer = FrameworkFileOutputPointer::createFrameworkFileOutputPointer($fqfn, 'w');
+
+ // Get the criteria array from the dataset
+ $criteriaArray = $dataSetInstance->getCriteriaArray();
+
+ // Serialize and compress it
+ $compressedData = $this->getCompressorChannel()->getCompressor()->compressStream(serialize($criteriaArray));
+
+ // Write this data BASE64 encoded to the file
+ $filePointer->writeToFile(base64_encode($compressedData));
+
+ // Close the file pointer
+ $filePointer->closeFile();
+
+ // Reset last error message and exception
+ $this->resetLastError();
+ } catch (FrameworkException $e) {
+ // Catch all exceptions and store them in last error
+ $this->lastException = $e;
+ $this->lastError = $e->getMessage();
+
+ // Throw an SQL exception
+ throw new SqlException (array($this, sprintf("Cannot write data to table '%s'", $tableName), self::DB_CODE_TABLE_UNWRITEABLE), self::EXCEPTION_SQL_QUERY);
+ }
}
}
// Constants for database columns
const DB_COLUMN_USERNAME = "username";
+ const DB_COLUMN_EMAIL = "email";
// Constants for database table names
const DB_TABLE_USER = "user";
$this->setObjectDescription("Database wrapper for user objects");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
// Now it's time to ask the database layer for this select statement
$result = $this->getDatabaseInstance()->doSelectByTableCriteria(self::DB_TABLE_USER, $criteriaInstance);
- // Cache the result
- $this->cacheInstance->offsetSet($cacheKey, $result);
+ // Cache the result if not null
+ if (!is_null($result)) {
+ // A valid result has returned from the database layer
+ $this->cacheInstance->offsetSet($cacheKey, $result);
+ } else {
+ // This invalid result must be wrapped
+ $result = array(
+ 'status' => "invalid",
+ 'exception' => $this->getDatabaseInstance()->getLastException()
+ );
+ }
}
// Create an instance of a DatabaseResult class with the given result
// And return the instance
return $resultInstance;
}
+
+ /**
+ * Handles inserting the registration data from a registration instance into the database
+ *
+ * @param $registrationInstance An instance of a registration class
+ * @return void
+ */
+ public function insertRegistrationObject (UserRegister $registrationInstance) {
+ // Generate a data set for the request
+ $dataSetInstance = ObjectFactory::createObjectByConfiguredName('dataset_criteria');
+ $dataSetInstance->setTableName(self::DB_TABLE_USER);
+
+ // Add registration elements to the dataset
+ $registrationInstance->addElementsToDataSet($dataSetInstance);
+
+ // "Insert" this request instance completely into the database
+ $this->getDatabaseInstance()->insertDataSet($dataSetInstance);
+ }
}
// [EOF]
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class DebugConsoleOutput extends BaseFrameworkSystem implements Debugger, OutputStreamer {
+class DebugConsoleOutput extends BaseFrameworkSystem implements Debugger, OutputStreamer, Registerable {
/**
* Protected constructor
*
$this->setObjectDescription("Debug output for the console");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
$this->setObjectDescription("Debug output to error_log()");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
$this->setObjectDescription("Debug output for webpages");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
$this->setObjectDescription("Class for "limiting" other classes. See description for details.");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
// Auto-initialization
if (is_null($this->limitArray)) {
// Initialize this array
- $this->limitArray = new FrameworkArrayObject();
+ $this->limitArray = new FrameworkArrayObject("FakedLimitArray");
}
// Add the object's name to it
// Auto-initialization
if (is_null($this->limitArray)) {
// Initialize this array
- $this->limitArray = new FrameworkArrayObject();
+ $this->limitArray = new FrameworkArrayObject("FakedLimitArray");
}
// Add the direct string to ArrayObject
*/
class SerializationContainer extends FrameworkArrayObject {
/**
- * Public constructor, if you like to have an object of this class...
+ * Protected constructor, must stay as public... *sigh*
*
* @return void
*/
* hold the attributed and their values which we have specified in
* the limitation object.
*
- * @param $limitInstance The instance to the object ObjectLimits
- * @param $object The origin object. We don't touch it here.
- * @return $containerInstance An instance of SerializationContainer
+ * @param $limitInstance The instance to the object ObjectLimits
+ * @param $object The origin object. We don't touch it here.
+ * @return $containerInstance An instance of SerializationContainer
* @throws GetterNotFoundException If a getter was not found
*/
public final static function createSerializationContainer (ObjectLimits $limitInstance, FrameworkInterface $object) {
// Is the required method available?
if (method_exists($object, sprintf("get%s", $curr))) {
- // Generate a command for getting it
- $eval = sprintf("\$value = \$object->get%s();",
- $curr
- );
-
- // Debug eval command
- if (defined('DEBUG_EVAL')) $limitInstance->getDebugInstance()->output(sprintf("[%s:] Constructed PHP command: <pre><em>%s</em></pre><br />\n",
- $this->__toString(),
- htmlentities($eval)
- ));
-
- // Run it
- eval($eval);
+ // Generate call-back function
+ $value = call_user_func_array(array($object, sprintf("get%s", $curr)));
// Add this item to the container list
$containerInstance->append(array(
$this->setObjectDescription("Factory for cache objects");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class ObjectFactory extends BaseFactory {
+ /**
+ * Total objects generated
+ */
+ private static $total = 0;
+
/**
* Protected constructor
*
$this->setObjectDescription("Simple generic object factory");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
* the class was not found. No parameters for the object are currently
* supported.
*
- * @param $className Name of the class we shall construct
- * @return $objectInstance An instance of the requested object
+ * @param $className Name of the class we shall construct
+ * @param $args Arguments in an indexed array
+ * @return $objectInstance An instance of the requested object
* @throws ClassNotFoundException If the requested class was not found
* @throws EmptyVariableException If a variable is empty unexpectly
*/
- public final static function createObjectByName ($className) {
+ public final static function createObjectByName ($className, array $args=array()) {
// First get an instance of this factory
$factoryInstance = new ObjectFactory();
throw new ClassNotFoundException(array($factoryInstance, $className), self::EXCEPTION_CLASS_NOT_FOUND);
}
- // Then Prepare the eval() command
- $eval = sprintf("\$objectInstance = %s::create%s();",
+ // Then Prepare the call-back function
+ $callback = sprintf("%s::create%s",
$className,
$className
);
- // Run the command
- eval($eval);
+ // Run the user function
+ $objectInstance = call_user_func_array($callback, $args);
+
+ // Count generated objects up
+ self::$total++;
// Return the prepared instance
return $objectInstance;
/**
* Creates an object by it's configured name
*
- * @param $configEnttry Configuration entry to read
- * @return $objectInstance An instance of the requested object
+ * @param $configEnttry Configuration entry to read
+ * @param $args Arguments in an indexed array
+ * @return $objectInstance An instance of the requested object
*/
- public final static function createObjectByConfiguredName ($configEntry) {
+ public final static function createObjectByConfiguredName ($configEntry, array $args=array()) {
// Read the configuration entry
$className = FrameworkConfiguration::getInstance()->readConfig($configEntry);
// Send this to the other factory...
- $objectInstance = self::createObjectByName($className);
+ $objectInstance = self::createObjectByName($className, $args);
// Return the instance
return $objectInstance;
}
+
+ /**
+ * Static getter for total object count
+ *
+ * @return $total Total amount of generated objects
+ */
+ public final static function getTotal () {
+ return self::$total;
+ }
}
// [EOF]
$this->setObjectDescription("Factory for webpages with news");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * A filter for checking if the user has accepted the rules. This is mainly
+ * used and done in registration process and should not be removed from your
+ * application.
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class RulesAcceptedFilter extends BaseFrameworkSystem implements Filterable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ protected function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set part description
+ $this->setObjectDescription("A filter for checking if rules where accepted");
+
+ // Create unique ID number
+ $this->generateUniqueId();
+
+ // Clean up a little
+ $this->removeNumberFormaters();
+ $this->removeSystemArray();
+ }
+
+ /**
+ * Creates an instance of this filter class
+ *
+ * @return $filterInstance An instance of this filter class
+ */
+ public final static function createRulesAcceptedFilter () {
+ // Get a new instance
+ $filterInstance = new RulesAcceptedFilter();
+
+ // Return the instance
+ return $filterInstance;
+ }
+
+ /**
+ * Executes the filter with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ // Get the "rules" value from request
+ $rules = $requestInstance->getRequestElement('rules');
+
+ // Was the "rules" value found in form? And is it set?
+ if (is_null($rules)) {
+ // Not found in form so stop processing here
+ $requestInstance->requestIsValid(false);
+
+ // Add a message to the response
+ $responseInstance->addFatalMessage('rules_unchecked');
+
+ // Abort here
+ return false;
+ }
+ }
+}
+
+// [EOF]
+?>
*/
class ???Filter extends BaseFrameworkSystem implements Filterable {
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
$this->setObjectDescription("A concrete filter");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
private $filterInstance = null;
/**
- * Private constructor
+ * Protected constructor
*
* @param $className Name of the real class' name
* @return void
private $filters = array();
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
$this->setObjectDescription("A filter chain class");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
--- /dev/null
+Deny from all
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * As the name said: A null filter does just pass through the data. This is
+ * useful to make other filters switch on/off-able.
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class NullFilter extends BaseFrameworkSystem implements Filterable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ protected function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set part description
+ $this->setObjectDescription("A null filter");
+
+ // Create unique ID number
+ $this->generateUniqueId();
+
+ // Clean up a little
+ $this->removeNumberFormaters();
+ $this->removeSystemArray();
+ }
+
+ /**
+ * Creates an instance of this filter class
+ *
+ * @return $filterInstance An instance of this filter class
+ */
+ public final static function createNullFilter () {
+ // Get a new instance
+ $filterInstance = new NullFilter();
+
+ // Return the instance
+ return $filterInstance;
+ }
+
+ /**
+ * Executes the filter with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ // Not implemented, just passing through
+ }
+}
+
+// [EOF]
+?>
--- /dev/null
+<?php
+/**
+ * A concrete filter for validating the email address. This filter may intercept
+ * the filter chain if no email address is given or if the supplied email has an
+ * invalid form. It could also intercept the filter chain if the email address
+ * is already used by some one if configuration requires this.
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class EmailValidatorFilter extends BaseFrameworkSystem implements Filterable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ protected function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set part description
+ $this->setObjectDescription("A filter for Email validation");
+
+ // Create unique ID number
+ $this->generateUniqueId();
+
+ // Clean up a little
+ $this->removeNumberFormaters();
+ $this->removeSystemArray();
+ }
+
+ /**
+ * Creates an instance of this filter class
+ *
+ * @return $filterInstance An instance of this filter class
+ */
+ public final static function createEmailValidatorFilter () {
+ // Get a new instance
+ $filterInstance = new EmailValidatorFilter();
+
+ // Return the instance
+ return $filterInstance;
+ }
+
+ /**
+ * Executes the filter with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ // Get Email from request
+ $email = $requestInstance->getRequestElement('email');
+
+ // Is the Email set?
+ if ((is_null($email)) || ($this->getConfigInstance()->readConfig('register_email_unique') == "Y")) {
+ // Try it again
+ $email1 = $requestInstance->getRequestElement('email1');
+ $email2 = $requestInstance->getRequestElement('email2');
+
+ // Is the email still not set?
+ if ((is_null($email1)) || (is_null($email2))) {
+ // Not found in form so stop the filtering process
+ $requestInstance->requestIsValid(false);
+
+ // Add a message to the response
+ $responseInstance->addFatalMessage('email_unset');
+
+ // Abort here
+ return false;
+ } elseif ((empty($email1)) || (empty($email2))) {
+ // Email is empty
+ $requestInstance->requestIsValid(false);
+
+ // Is the email empty?
+ if (empty($email1)) {
+ // Add a message to the response
+ $responseInstance->addFatalMessage('email1_empty');
+ } // END - if
+
+ // Is the confirmation empty?
+ if (empty($email2)) {
+ // Add a message to the response
+ $responseInstance->addFatalMessage('email2_empty');
+ } // END - if
+
+ // Abort here
+ return false;
+ } elseif ($this->ifEmailIsTaken($email1)) {
+ // Email is already taken
+ $requestInstance->requestIsValid(false);
+
+ // Add a message to the response
+ $responseInstance->addFatalMessage('email_taken');
+
+ // Abort here
+ return false;
+ } elseif ($email1 != $email2) {
+ // Emails didn't match
+ $requestInstance->requestIsValid(false);
+
+ // Add a message to the response
+ $responseInstance->addFatalMessage('emails_mismatch');
+
+ // Abort here
+ return false;
+ } // END - elseif
+ } elseif (empty($email)) {
+ // Empty field!
+ $requestInstance->requestIsValid(false);
+
+ // Add a message to the response
+ $responseInstance->addFatalMessage('email_empty');
+
+ // Abort here
+ return false;
+ } // END - elseif
+ }
+
+ /**
+ * Check wether the email as already been taken
+ *
+ * @param $email Email to check for existence
+ * @return $alreadyTaken Wether the email has been taken
+ */
+ private function ifEmailIsTaken ($email) {
+ // Default is already taken
+ $alreadyTaken = true;
+
+ // Initialize instance
+ $userInstance = null;
+
+ // Get a registry instance
+ $registry = Registry::getRegistry();
+
+ // Is the user already there?
+ if ($registry->instanceExists('user')) {
+ // Use the instance for checking for the email
+ $userInstance = $registry->getInstance('user');
+ $userInstance->setEmailAddress($email);
+ } else {
+ // If this instance is created then the username *does* exist
+ $userInstance = call_user_func_array(array($this->getConfigInstance()->readConfig('user_class'), "createUserByEmail"), array($email));
+
+ // Remember this user instance in our registry for later usage
+ $registry->addInstance('user', $userInstance);
+ }
+
+ // Does the email exist?
+ if (!$userInstance->ifEmailAddressExists()) {
+ // This email has not being used yet
+ $alreadyTaken = false;
+ }
+
+ // Return the result
+ return $alreadyTaken;
+ }
+}
+
+// [EOF]
+?>
--- /dev/null
+<?php
+/**
+ * A concrete filter for validating the password. This filter may intercept
+ * the filter chain if no password is given or if both passwords didn't match.
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.ship-simu.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class PasswordValidatorFilter extends BaseFrameworkSystem implements Filterable {
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ protected function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set part description
+ $this->setObjectDescription("A filter for Password validation");
+
+ // Create unique ID number
+ $this->generateUniqueId();
+
+ // Clean up a little
+ $this->removeNumberFormaters();
+ $this->removeSystemArray();
+ }
+
+ /**
+ * Creates an instance of this filter class
+ *
+ * @return $filterInstance An instance of this filter class
+ */
+ public final static function createPasswordValidatorFilter () {
+ // Get a new instance
+ $filterInstance = new PasswordValidatorFilter();
+
+ // Return the instance
+ return $filterInstance;
+ }
+
+ /**
+ * Executes the filter with given request and response objects
+ *
+ * @param $requestInstance An instance of a class with an Requestable interface
+ * @param $responseInstance An instance of a class with an Responseable interface
+ * @return void
+ */
+ public function execute (Requestable $requestInstance, Responseable $responseInstance) {
+ // Get passwords
+ $password1 = $requestInstance->getRequestElement('pass1');
+ $password2 = $requestInstance->getRequestElement('pass2');
+
+ // Is the password still not set?
+ if ((is_null($password1)) || (is_null($password2))) {
+ // Not found in form so stop the filtering process
+ $requestInstance->requestIsValid(false);
+
+ // Add a message to the response
+ $responseInstance->addFatalMessage('password_unset');
+
+ // Abort here
+ return false;
+ } elseif ((empty($password1)) || (empty($password2))) {
+ // Password is empty
+ $requestInstance->requestIsValid(false);
+
+ // Is the password empty?
+ if (empty($password1)) {
+ // Add a message to the response
+ $responseInstance->addFatalMessage('password1_empty');
+ } // END - if
+
+ // Is the confirmation empty?
+ if (empty($password2)) {
+ // Add a message to the response
+ $responseInstance->addFatalMessage('password2_empty');
+ } // END - if
+
+ // Abort here
+ return false;
+ } elseif ($password1 != $password2) {
+ // Passwords didn't match
+ $requestInstance->requestIsValid(false);
+
+ // Add a message to the response
+ $responseInstance->addFatalMessage('passwords_mismatching');
+
+ // Abort here
+ return false;
+ } // END - elseif
+ }
+}
+
+// [EOF]
+?>
*/
class UserNameValidatorFilter extends BaseFrameworkSystem implements Filterable {
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
$this->setObjectDescription("A filter for username validation");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
// Not found in form so stop the filtering process
$requestInstance->requestIsValid(false);
- // Set a message for the response
+ // Add a message to the response
$responseInstance->addFatalMessage('username_unset');
// Abort here
// Empty field!
$requestInstance->requestIsValid(false);
- // Set a message for the response
+ // Add a message to the response
$responseInstance->addFatalMessage('username_empty');
// Abort here
// Username is already taken
$requestInstance->requestIsValid(false);
- // Set a message for the response
+ // Add a message to the response
$responseInstance->addFatalMessage('username_taken');
// Abort here
// Default is already taken
$alreadyTaken = true;
- // Try to create a user instance
- try {
+ // Initialize instance
+ $userInstance = null;
+
+ // Get a registry instance
+ $registry = Registry::getRegistry();
+
+ // Is the user already there?
+ if ($registry->instanceExists('user')) {
+ // Use the instance for checking for the email
+ $userInstance = $registry->getInstance('user');
+ $userInstance->setUserName($userName);
+ } else {
// If this instance is created then the username *does* exist
- $userInstance = User::createUserByUsername($userName);
- } catch (UsernameMissingException $e) {
- // Okay, this user is missing!
+ try {
+ // Get a new instance
+ $userInstance = call_user_func_array(array($this->getConfigInstance()->readConfig('user_class'), "createUserByUsername"), array($userName));
+
+ // Remember this user instance in our registry for later usage
+ $registry->addInstance('user', $userInstance);
+ } catch (UsernameMissingException $e) {
+ // User was not found
+ }
+ }
+
+ // Does the username exist?
+ if ((is_null($userInstance)) || (!$userInstance->ifUsernameExists())) {
+ // This username is still available
$alreadyTaken = false;
}
*/
class extends BaseHelper {
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
private $content = "";
/**
- * Private constructor
+ * Protected constructor
*
* @param $className Real name of the class
* @return void
const EXCEPTION_UNEXPECTED_CLOSED_GROUP = 0xb03;
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
$this->setObjectDescription("Helper class for HTML forms");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
$this->setObjectDescription("Universal file I/O stream system");
// Create unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean-up a little
$this->removeNumberFormaters();
$this->setObjectDescription("Helper for handling directories");
// Create unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean-up a little
$this->removeNumberFormaters();
*
* @return string Directory and/or file names read from the current
* directory pointer
- * @throws NullPointerException If the directory pointer instance
- * is not set by setPointer()
- * @throws InvalidDirectoryResourceException If there is being set
- * an invalid directory resource
*/
public function readRawDirectory () {
- if (is_null($this->getPointer())) {
- // Pointer not initialized
- throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } elseif (!is_resource($this->getPointer())) {
- // Pointer is not a valid resource!
- throw new InvalidDirectoryResourceException($this, self::EXCEPTION_INVALID_DIRECTORY_POINTER);
- }
-
// Read data from the directory pointer and return it
return readdir($this->getPointer());
}
* to empty
*
* @return void
- * @throws NullPointerException If the directory pointer instance
- * is not set by setPointer()
- * @throws InvalidDirectoryResourceException If there is being set
*/
public function closeDirectory () {
- if (is_null($this->getPointer())) {
- // Pointer not initialized
- return;
- } elseif (!is_resource($this->getPointer())) {
- // Pointer is not a valid resource!
- throw new InvalidDirectoryResourceException($this, self::EXCEPTION_INVALID_DIRECTORY_POINTER);
- }
-
// Close the directory pointer and reset the instance variable
@closedir($this->getPointer());
$this->setPointer(null);
$this->setObjectDescription("Handler for reading from files");
// Create unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean-up a little
$this->removeNumberFormaters();
$this->setObjectDescription("Handler for writing to files");
// Create unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean-up a little
$this->removeNumberFormaters();
* Create a file pointer based on the given file. The file will also
* be verified here.
*
- * @param $fileName The file name we shall pass
- * to fopen()
- * @param $mode The output mode ('w', 'a' are valid)
+ * @param $fileName The file name we shall pass to fopen()
+ * @param $mode The output mode ('w', 'a' are valid)
* @throws FileIsEmptyException If the provided file name is empty.
* @throws FilePointerNotOpened If fopen() returns not a file
- * resource
+ * resource
* @return void
*/
public final static function createFrameworkFileOutputPointer ($fileName, $mode) {
/**
* Write data to a file pointer
*
- * @param $dataStream The data stream we shall write to the file
- * @return mixed The result of fwrite()
+ * @param $dataStream The data stream we shall write to the file
+ * @return mixed The result of fwrite()
* @throws NullPointerException If the file pointer instance
- * is not set by setPointer()
+ * is not set by setPointer()
* @throws InvalidFileResourceException If there is being set
- * an invalid file resource
+ * an invalid file resource
*/
public function writeToFile ($dataStream) {
if (is_null($this->getPointer())) {
*
* @return void
* @throws NullPointerException If the file pointer instance
- * is not set by setPointer()
+ * is not set by setPointer()
* @throws InvalidFileResourceException If there is being set
*/
public function closeFile () {
/**
* Setter for the file pointer
*
- * @param $filePointer File resource
+ * @param $filePointer File resource
* @return void
*/
public final function setPointer ($filePointer) {
* Getter for the file pointer
*
* @return $filePointer The file pointer which shall be a valid
- * file resource
+ * file resource
*/
public final function getPointer () {
return $this->filePointer;
/**
* Setter for file name
*
- * @param $fileName The new file name
+ * @param $fileName The new file name
* @return void
*/
public final function setFileName ($fileName) {
/**
* Getter for file name
*
- * @return $fileName The current file name
+ * @return $fileName The current file name
*/
public final function getFileName () {
return $this->fileName;
$this->setObjectDescription("Language sub-system");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
* @return void
*/
public function initLanguageStrings () {
- $this->langStrings = new FrameworkArrayObject();
+ $this->langStrings = new FrameworkArrayObject("FakedLanguageStrings");
}
/**
$this->setObjectDescription("Console output class");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class WebOutput extends BaseFrameworkSystem implements OutputStreamer {
+class WebOutput extends BaseFrameworkSystem implements OutputStreamer, Registerable {
/**
* The instance for the singleton design pattern
*/
$this->setObjectDescription("Class for web output e.g. XHTML code");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
}
/**
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * A general registration class
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.3.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.mxchange.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+abstract class BaseRegistration extends BaseFrameworkSystem implements UserRegister {
+ /**
+ * Instance of a request class
+ */
+ private $requestInstance = null;
+
+ /**
+ * Instance of a response class
+ */
+ private $responseInstance = null;
+
+ /**
+ * Pre-registration filter chain
+ */
+ private $preRegistrationFilter = null;
+
+ /**
+ * Pre-registration filter chain
+ */
+ private $postRegistrationFilter = null;
+
+ /**
+ * Protected constructor
+ *
+ * @param $className Name of the class
+ * @return void
+ */
+ protected function __construct ($className) {
+ // Call parent constructor
+ parent::__construct($className);
+
+ // Clean up a little
+ $this->removeNumberFormaters();
+ $this->removeSystemArray();
+ }
+
+ /**
+ * Initialize filters. This must be done before you can use them
+ *
+ * @return void
+ */
+ protected function initFilterChains () {
+ // Pre/post-registration filters
+ $this->preRegistrationFilter = ObjectFactory::createObjectByConfiguredName('filter_chain');
+ $this->postRegistrationFilter = ObjectFactory::createObjectByConfiguredName('filter_chain');
+ }
+
+ /**
+ * Setter for request instance
+ *
+ * @param $requestInstance An instance of a Requestable class
+ * @return void
+ */
+ public final function setRequestInstance (Requestable $requestInstance) {
+ $this->requestInstance = $requestInstance;
+ }
+
+ /**
+ * Getter for request instance
+ *
+ * @return $requestInstance An instance of a Requestable class
+ */
+ public final function getRequestInstance () {
+ return $this->requestInstance;
+ }
+
+ /**
+ * Setter for response instance
+ *
+ * @param $responseInstance An instance of a Responseable class
+ * @return void
+ */
+ public final function setResponseInstance (Responseable $responseInstance) {
+ $this->responseInstance = $responseInstance;
+ }
+
+ /**
+ * Getter for response instance
+ *
+ * @return $responseInstance An instance of a Responseable class
+ */
+ public final function getResponseInstance () {
+ return $this->responseInstance;
+ }
+
+ /**
+ * Adds a filter to the pre filter chain
+ *
+ * @param $filterInstance An instance of a filter
+ * @return void
+ */
+ public function addPreFilter (Filterable $filterInstance) {
+ // Add the pre filter
+ $this->preRegistrationFilter->addFilter($filterInstance);
+ }
+
+ /**
+ * Adds a filter to the post filter chain
+ *
+ * @param $filterInstance An instance of a filter
+ * @return void
+ */
+ public function addPostFilter (Filterable $filterInstance) {
+ // Add the post filter
+ $this->postRegistrationFilter->addFilter($filterInstance);
+ }
+
+ /**
+ * Executes all pre filters
+ *
+ * @return void
+ */
+ protected function executePreFilters () {
+ // Execute all pre filters
+ $this->preRegistrationFilter->processFilters($this->getRequestInstance(), $this->getResponseInstance());
+ }
+
+ /**
+ * Executes all post filters
+ *
+ * @return void
+ */
+ protected function executePostFilters () {
+ // Execute all post filters
+ $this->postRegistrationFilter->processFilters($this->requestInstance, $this->responseInstance);
+ }
+}
+
+// [EOF]
+?>
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * A registry for several data types
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.3.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.mxchange.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class Registry extends BaseFrameworkSystem implements Register {
+ /**
+ * Instance of this class
+ */
+ private static $selfInstance = null;
+
+ /**
+ * Wether the registry is initialized
+ */
+ private static $initialized = false;
+
+ /**
+ * Instance registry
+ */
+ private $instanceRegistry = array();
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ protected function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set part description
+ $this->setObjectDescription("Registry class");
+
+ // Create unique ID number
+ $this->generateUniqueId();
+
+ // Clean up a little
+ $this->removeNumberFormaters();
+ $this->removeSystemArray();
+ }
+
+ /**
+ * Singleton getter for self instance
+ *
+ * @return $selfInstance Instance of this class
+ */
+ public final static function getRegistry () {
+ // Is an instance there?
+ if (is_null(self::$selfInstance)) {
+ // Not yet, so create one
+ self::$selfInstance = new Registry();
+ }
+
+ // Return the instance
+ return self::$selfInstance;
+ }
+
+ /**
+ * Checks or sets wether the registry has been initialized. This had only be done once
+ *
+ * @param $initialized Wether the registry is initialized
+ * @return $initialized Wether the registry is initialized
+ */
+ public final static function isInitialized ($initialized = null) {
+ if (is_null($initialized)) {
+ // Get status if initialized
+ return self::$initialized;
+ } elseif (!is_null($initialized)) {
+ // Registry is initialized!
+ self::$initialized = true;
+ }
+ }
+
+ /**
+ * Checks wether an instance key was found
+ *
+ * @param $instanceKey The key holding an instance in the registry
+ * @return $exists Wether the key exists in the registry
+ */
+ public function instanceExists ($instanceKey) {
+ // Does this key exists?
+ $exists = (isset($this->instanceRegistry[$instanceKey]));
+
+ // Return the result
+ return $exists;
+ }
+
+ /**
+ * Adds/overwrites a new instance to the registry at the given key
+ *
+ * @param $instanceKey The key to identify the instance
+ * @param $objectInstance An instance we shall store
+ * @return void
+ */
+ public function addInstance ($instanceKey, Registerable $objectInstance) {
+ $this->instanceRegistry[$instanceKey] = $objectInstance;
+ }
+
+ /**
+ * Gets a registered instance or null if not found
+ *
+ * @param $instanceKey The key to identify the instance
+ * @return $objectInstance An instance we shall store
+ */
+ public function getInstance ($instanceKey) {
+ // By default the instance is not in the registry
+ $objectInstance = null;
+
+ // Is the instance there?
+ if ($this->instanceExists($instanceKey)) {
+ $objectInstance = $this->instanceRegistry[$instanceKey];
+ }
+
+ // Return the result
+ return $objectInstance;
+ }
+}
+
+// [EOF]
+?>
$this->setObjectDescription("HTTP request");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
return $value;
}
+ /**
+ * Setter for request elements
+ *
+ * @param $element Request element to se
+ * @param $value Value to set
+ * @return void
+ */
+ public function setRequestElement ($element, $value) {
+ $this->requestData[$element] = $value;
+ }
+
/**
* Wrapper method for array_key() function for the request data array
*
$this->setObjectDescription("Resolver for local web commands");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Set prefix to "Web"
$this->setCommandPrefix("Web");
}
// Initiate the command
- $eval = sprintf("\$commandInstance = %s::create%s(\$this);",
- $className,
- $className
- );
-
- // Run the command
- eval($eval);
-
- // Is the instance valid?
- if ((!is_object($commandInstance)) || (!$commandInstance instanceof Commandable)) {
- // Something is wrong
- $commandInstance = null;
- }
+ $commandInstance = ObjectFactory::createObjectByName($className, array($this));
// Return the result
return $commandInstance;
$this->setObjectDescription("Resolver for local web controllers");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Set prefix to "Web"
$this->setCommandPrefix("Web");
// Still not found?
throw new DefaultControllerException($this, self::EXCEPTION_DEFAUL_CONTROLLER_GONE);
}
- }
-
- // Initiate the controller
- $eval = sprintf("\$controllerInstance = %s::create%s(WebCommandResolver::createWebCommandResolver(\$commandName, \$this->getApplicationInstance()));",
- $class,
- $class
- );
+ } // END - if
- // Run the command
- eval($eval);
+ // Initiate the resolver and controller
+ $resolverInstance = ObjectFactory::createObjectByConfiguredName('web_cmd_resolver', array($commandName, $this->getApplicationInstance()));
+ $controllerInstance = ObjectFactory::createObjectByName($class, array($resolverInstance));
- // Is the instance valid?
- if ((!is_object($controllerInstance)) || (!$controllerInstance instanceof Controller)) {
- // Something is wrong
- $controllerInstance = null;
- }
+ // Remove resolver
+ unset($resolverInstance);
// Return the result
return $controllerInstance;
$this->setObjectDescription("HTTP response");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
$this->addHeader('Pragma:', 'no-cache'); // HTTP/1.0
// Define the charset to be used
- $this->addHeader('Content-Type:', 'text/html; charset=utf-8');
+ //$this->addHeader('Content-Type:', sprintf("text/html; charset=%s", $this->getConfigInstance()->readConfig('header_charset')));
foreach ($this->responseHeaders as $name=>$value) {
header("{$name}: {$value}");
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * A database result class
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.3.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.mxchange.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class DatabaseResult extends BaseFrameworkSystem {
+ /**
+ * Current position in array
+ */
+ private $currentPos = -1;
+
+ /**
+ * Current row
+ */
+ private $currentRow = null;
+
+ /**
+ * Result array
+ */
+ private $resultArray = array();
+
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
+ protected function __construct () {
+ // Call parent constructor
+ parent::__construct(__CLASS__);
+
+ // Set part description
+ $this->setObjectDescription("Database result");
+
+ // Create unique ID number
+ $this->generateUniqueId();
+
+ // Clean up a little
+ $this->removeNumberFormaters();
+ $this->removeSystemArray();
+ }
+
+ /**
+ * Creates an instance of this result by a provided result array
+ *
+ * @param $resultArray The array holding the result from query
+ * @return $resultInstance An instance of this class
+ */
+ public final static function createDatabaseResult (array $resultArray) {
+ // Get a new instance
+ $resultInstance = new DatabaseResult();
+
+ // Set the result array
+ $resultInstance->setResultArray($resultArray);
+
+ // Return the instance
+ return $resultInstance;
+ }
+
+ /**
+ * Setter for result array
+ *
+ * @param $resultArray The array holding the result from query
+ * @return void
+ */
+ protected final function setResultArray (array $resultArray) {
+ $this->resultArray = $resultArray;
+ }
+
+ /**
+ * "Iterator" method next() to advance to the next valid entry. This method
+ * does also check if the result is invalid
+ *
+ * @return $nextValid Wether the next entry is valid
+ */
+ public function next () {
+ // Default is not valid
+ $nextValid = false;
+
+ // Is the result valid?
+ if ($this->resultArray['status'] === "ok") {
+ // The status is fine so let's have a look for the next entry
+ if (isset($this->resultArray['rows'][($this->currentPos + 1)])) {
+ // Next entry found, so count one up and cache it
+ $this->currentPos++;
+ $this->currentRow = $this->resultArray['rows'][$this->currentPos];
+ $nextValid = true;
+ } // END - if
+ } // END - if
+
+ // Return the result
+ return $nextValid;
+ }
+}
+
+// [EOF]
+?>
--- /dev/null
+Deny from all
--- /dev/null
+<?php
+/**
+ * A standard random number generator
+ *
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.3.0
+ * @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
+ * @license GNU GPL 3.0 or any newer version
+ * @link http://www.mxchange.org
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+class RandomNumberGenerator extends BaseFrameworkSystem {
+ /**
+ * Prime number for better pseudo random numbers
+ */
+ private $prime = 0;
+
+ /**
+ * Add this calculated number to the rng
+ */
+ private $extraNumber = 0;
+
+ /**
+ * Extra salt for secured hashing
+ */
+ private $extraSalt = "";
+
+ /**
+ * Maximum length for random string
+ */
+ private $rndStrLen = 0;
+
+ /**
+ * Protected constructor
+ *
+ * @param $className Name of this class
+ * @return void
+ */
+ protected function __construct ($className = __CLASS__) {
+ // Call parent constructor
+ parent::__construct($className);
+
+ // Set part description
+ $this->setObjectDescription("Standard random number generator");
+
+ // Create unique ID number
+ $this->generateUniqueId();
+
+ // Clean up a little
+ $this->removeNumberFormaters();
+ $this->removeSystemArray();
+ }
+
+ /**
+ * Creates an instance of this class
+ *
+ * @return $rngInstance An instance of this random number generator
+ */
+ public final static function createRandomNumberGenerator () {
+ // Get a new instance
+ $rngInstance = new RandomNumberGenerator();
+
+ // Initialize the RNG now
+ $rngInstance->initRng();
+
+ // Return the instance
+ return $rngInstance;
+ }
+
+ /**
+ * Initializes the random number generator
+ *
+ * @return void
+ */
+ protected function initRng () {
+ // Seed mt_rand()
+ mt_srand((double) microtime() * 1000000);
+
+ // Get the prime number from config
+ $this->prime = $this->getConfigInstance()->readConfig('math_prime');
+
+ // Calculate the extra number which is always the same unless you give
+ // a better prime number
+ $this->extraNumber = ($this->prime * $this->prime / (pi() ^ 2));
+
+ // Set the server IP to cluster
+ $serverIp = "cluster";
+ // Do we have a single server?
+ if ($this->getConfigInstance()->readConfig('is_single_server') == "Y") {
+ // Then use that IP for extra security
+ $serverIp = getenv('SERVER_ADDR');
+ }
+
+ // One-way data we need for "extra-salting" the random number
+ // @TODO Add site for stronger salt!
+ $this->extraSalt = sha1($serverIp . ":" . getenv('SERVER_SOFTWARE') . ":" . $this->getConfigInstance()->readConfig('date_key') . ":" . serialize($this->getDatabaseInstance()->getConnectionData()));
+
+ // Get config entry for max salt length
+ $this->rndStrLen = $this->getConfigInstance()->readConfig('rnd_str_length');
+ }
+
+ /**
+ * Makes a pseudo-random string useable for salts
+ *
+ * @param $length Length of the string, default: 128
+ * @return $randomString The pseudo-random string
+ */
+ public function makeRandomString ($length = -1) {
+ // Is the number <1, then fix it to default length
+ if ($length < 1) $length = $this->rndStrLen;
+
+ // Initialize the string
+ $randomString = "";
+
+ // And generate it
+ for ($idx = 0; $idx < $length; $idx++) {
+ // Add a random character and add it to our string
+ $randomString .= chr($this->randomNumnber(0, 255));
+ }
+
+ // Return the random string mixed up
+ return str_shuffle($randomString);
+ }
+
+ /**
+ * Generate a pseudo-random integer number in a given range
+ *
+ * @param $min Min value to generate
+ * @param $max Max value to generate
+ * @return $num Pseudo-random number
+ */
+ public function randomNumnber ($min, $max) {
+ // @TODO I had a better random number generator here
+ return mt_rand($min, $max);
+ }
+
+ /**
+ * Getter for extra salt
+ *
+ * @return $extraSalt
+ */
+ public final function getExtraSalt () {
+ return $this->extraSalt;
+ }
+}
+
+// [EOF]
+?>
$this->setObjectDescription("Web template engine");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
* @return void
*/
public final function initVariableStack () {
- $this->varStack = new FrameworkArrayObject();
+ $this->varStack = new FrameworkArrayObject("FakedVariableStack");
}
/**
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class User extends BaseFrameworkSystem implements ManageableUser {
+class User extends BaseFrameworkSystem implements ManageableUser, Registerable {
/**
- * Username
+ * Username of current user
*/
- private $username = "";
+ private $userName = "";
+
+ /**
+ * Email of current user
+ */
+ private $email = "";
// Exceptions
- const EXCEPTION_USERNAME_NOT_FOUND = 0xd00;
+ const EXCEPTION_USERNAME_NOT_FOUND = 0xd00;
+ const EXCEPTION_USER_EMAIL_NOT_FOUND = 0xd01;
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
$this->setObjectDescription("Generic user class");
// Create unique ID number
- $this->createUniqueID();
+ $this->generateUniqueId();
// Clean up a little
$this->removeNumberFormaters();
* factory method will check if the username is already taken and if not
* so it will throw an exception.
*
- * @param $username Username we need a class instance for
+ * @param $userName Username we need a class instance for
* @return $userInstance An instance of this user class
* @throws UsernameMissingException If the username does not exist
*/
$userInstance = new User();
// Set the username
- $userInstance->setUsername($userName);
+ $userInstance->setUserName($userName);
// Check if the username exists
if (!$userInstance->ifUsernameExists()) {
return $userInstance;
}
+ /**
+ * Creates an instance of this user class by a provided email address. This
+ * factory method will not check if the email address is there.
+ *
+ * @param $email Email address of the user
+ * @return $userInstance An instance of this user class
+ */
+ public final static function createUserByEmail ($email) {
+ // Get a new instance
+ $userInstance = new User();
+
+ // Set the username
+ $userInstance->setEmail($email);
+
+ // Return the instance
+ return $userInstance;
+ }
+
/**
* Setter for username
*
* @param $userName The username to set
* @return void
*/
- protected final function setUsername ($userName) {
- $this->userNane = $userName;
+ public final function setUserName ($userName) {
+ $this->userName = $userName;
+ }
+
+ /**
+ * Setter for email
+ *
+ * @param $email The email to set
+ * @return void
+ */
+ protected final function setEmail ($email) {
+ $this->email = $email;
}
/**
* @return $userName The username to get
*/
public final function getUsername () {
- return $this->userNane;
+ return $this->userName;
+ }
+
+ /**
+ * Getter for email
+ *
+ * @return $email The email to get
+ */
+ public final function getEmail () {
+ return $this->email;
}
/**
*
* @return $exists Wether the username exists
*/
- protected function ifUsernameExists () {
+ public function ifUsernameExists () {
// By default the username does exist
$exists = true;
// Get a UserDatabaseWrapper instance
- $wrapperInstance = UserDatabaseWrapper::createUserDatabaseWrapper();
+ $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper');
// Create a search criteria
$criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria');
$result = $wrapperInstance->doSelectByCriteria($criteriaInstance);
// Search for it
- if ($result->next()) {
- // Entry found, so all is fine
- $exists = true;
- }
+ if (!$result->next()) {
+ // Entry not found
+ $exists = false;
+ } // END - if
+
+ // Return the status
+ return $exists;
+ }
+
+ /**
+ * Determines wether the email exists or not
+ *
+ * @return $exists Wether the email exists
+ */
+ public function ifEmailAddressExists () {
+ // By default the username does exist
+ $exists = true;
+
+ // Get a UserDatabaseWrapper instance
+ $wrapperInstance = ObjectFactory::createObjectByConfiguredName('user_db_wrapper');
+
+ // Create a search criteria
+ $criteriaInstance = ObjectFactory::createObjectByConfiguredName('search_criteria');
+
+ // Add the username as a criteria and set limit to one entry
+ $criteriaInstance->addCriteria(UserDatabaseWrapper::DB_COLUMN_EMAIL, $this->getEmail());
+ $criteriaInstance->setLimit(1);
+
+ // Get a search result
+ $result = $wrapperInstance->doSelectByCriteria($criteriaInstance);
+
+ // Search for it
+ if (!$result->next()) {
+ // Entry not found
+ $exists = false;
+ } // END - if
// Return the status
return $exists;
*/
class BaseMiddleware extends BaseFrameworkSystem {
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class CompressorChannel extends BaseMiddleware {
- // Output handler instance
+class CompressorChannel extends BaseMiddleware implements Registerable {
+ /**
+ * Real compressor instance
+ */
private $compressor = null;
- // Public constructor
+ /**
+ * Protected constructor
+ *
+ * @return void
+ */
protected function __construct () {
// Call parent constructor!
parent::__construct(__CLASS__);
$this->setObjectDescription("Komprimierungshandler");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
}
- // Create a new compressor channel based a given compression handler
+ /**
+ * Create a new compressor channel based a given base directory where
+ * we shall look for compressor classes
+ *
+ * @param $baseDir Directory which holds our compressor classes
+ * @return $cInstance A prepared instance of this class
+ */
public final static function createCompressorChannel ($baseDir) {
// Get new instance
$cInstance = new CompressorChannel();
$dirPointer = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($baseDir);
// Read all directories but no sub directories
- while ($dir = $dirPointer->readDirectoryExcept(array("..", ".", ".htaccess"))) {
+ while ($dir = $dirPointer->readDirectoryExcept(array("..", ".", ".htaccess", ".svn"))) {
// Is this a class file?
if ((substr($dir, 0, 6) == "class_") && (substr($dir, -4, 4) == FrameworkConfiguration::getInstance()->readConfig('php_extension'))) {
// Get the compressor's name. That's why you must name
// must keep on class in one file.
$class = substr($dir, 6, -4);
- // Create eval command
- $eval = sprintf("\$tempInstance = %s::create%s();",
- $class,
- $class
- );
-
- // Debug message
- if ((defined('DEBUG_EVAL')) || (defined('DEBUG_ALL'))) $cInstance->getDebugInstance()->output(sprintf("[%s:] Konstruierte PHP-Anweisung: <pre><em>%s</em></pre><br />\n",
- $cInstance->__toString(),
- htmlentities($eval)
- ));
-
- // Run it. This will create an instance to the current class
- eval($eval);
+ // Get an instance from our object factory
+ $tempInstance = ObjectFactory::createObjectByName($class);
- // Is the instance valid? We have the stream handler here
- if ((!is_null($tempInstance)) && (method_exists($tempInstance, 'compressStream')) && (method_exists($tempInstance, 'decompressStream'))) {
- // Okay, this handler is valid
- $cInstance->setCompressor($tempInstance);
+ // Set the compressor
+ $cInstance->setCompressor($tempInstance);
- // No more searches required because we have found a valid compressor stream
- break;
- }
- }
- }
+ // No more searches required because we have found a valid compressor stream
+ break;
+ } // END - if
+ } // END - while
// Close the directory
$dirPointer->closeDirectory();
- }
+ } // END - if
// Check again if there is a compressor
if (
) {
// Set the null compressor handler. This should not be configureable!
$cInstance->setCompressor(ObjectFactory::createObjectByName('NullCompressor'));
- }
+ } // END - if
// Return the compressor instance
return $cInstance;
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class DatabaseConnection extends BaseMiddleware implements DatabaseConnector, LimitableObject {
+class DatabaseConnection extends BaseMiddleware implements DatabaseConnector, Registerable {
/**
* Array for connection data
*/
$this->setObjectDescription("Datenbank-Mittelschicht");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
}
// Create new database connection layer
}
/**
- * Save a whole object or parts of it to the database or local file
+ * Getter for connection data
*
- * @param $object The object we shall save
- * @return void
+ * @return $connectData Connection data stored with this clas
*/
- public function saveObject ($object) {
- // Connect to the database
- $this->dbLayer->connectToDatabase();
-
- // For now just pipe it through to the database layer
- $this->dbLayer->saveObject($object);
+ public final function getConnectionData () {
+ return $this->connectData;
}
/**
- * Set a limitation for the saving process. This shall be done before
- * saveObject() is called else saveObject() shall save the whole object.
- *
- * @param $limitInstance An instance of ObjectLimits which contains
- * elements we shall exclusivly include in
- * saving process
+ * Setter for the real database layer
+ * @param $dbLayer An instance of the real database layer
* @return void
*/
- public function limitObject (ObjectLimits $limitInstance) {
- // Connect to the database
- $this->dbLayer->connectToDatabase();
-
- // For now we pipe this through to the real database instance
- $this->dbLayer->limitObject($limitInstance);
+ public final function setDatabaseLayer (DatabaseFrontendInterface $dbLayer) {
+ $this->dbLayer = $dbLayer;
}
/**
}
/**
- * Gets cached data from the database layer and if not found fetch it from
- * the database again. This method does not return the header stuff because
- * the underlaying database class will return only the requested content.
+ * Runs a "select" statement on the database layer with given table name
+ * and criteria. If this doesn't fail the result will be returned
*
- * @param $idNumber The ID number which we need for looking up
- * the requested data
- * @return $cachedArray The maybe cached data from the database
+ * @param $tableName Name of the "table" we shall query
+ * @param $criteriaInstance An instance of a Criteria class
+ * @return $result The result as an array
*/
- public function getObjectFromCachedData ($idNumber) {
+ public function doSelectByTableCriteria ($tableName, Criteria $criteriaInstance) {
// Connect to the database
$this->dbLayer->connectToDatabase();
- // Pass the returning result through
- return $this->dbLayer->getObjectFromCachedData($idNumber);
+ // Get result from query
+ $result = $this->dbLayer->querySelect("array", $tableName, $criteriaInstance);
+
+ // Return the result
+ return $result;
}
/**
- * Setter for the real database layer
- * @param $dbLayer An instance of the real database layer
- * @return void
+ * Getter for last exception
+ *
+ * @return $exceptionInstance Last thrown exception
*/
- public final function setDatabaseLayer (DatabaseFrontendInterface $dbLayer) {
- $this->dbLayer = $dbLayer;
+ public final function getLastException () {
+ $exceptionInstance = $this->dbLayer->getLastException();
+ return $exceptionInstance;
}
/**
- * Runs a "select" statement on the database layer with given table name
- * and criteria. If this doesn't fail the result will be returned
+ * "Inserts" a data set instance into a local file database folder
*
- * @param $tableName Name of the "table" we shall query
- * @param $criteriaInstance An instance of a Criteria class
- * @return $result The result as an array
+ * @param $dataSetInstance A storeable data set
+ * @return void
*/
- public function doSelectByTableCriteria ($tableName, Criteria $criteriaInstance) {
+ public function insertDataSet (StoreableCriteria $dataSetInstance) {
// Connect to the database
$this->dbLayer->connectToDatabase();
- // Get result from query
- $result = $this->dbLayer->querySelect("array", $tableName, $criteriaInstance);
-
- // Return the result
- return $result;
+ // Ask the database layer
+ $this->dbLayer->insertDataSet($dataSetInstance);
}
}
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class DebugMiddleware extends BaseMiddleware {
+class DebugMiddleware extends BaseMiddleware implements Registerable {
/**
* The concrete output instance
*/
- private $outputHandler = null;
+ private $outputInstance = null;
/**
* An instance of this class
private static $thisInstance = null;
/**
- * Private constructor
+ * Protected constructor
*
* @return void
*/
parent::__construct(__CLASS__);
// Set description
- $this->setObjectDescription("Debug-Ausgabe-Handler");
+ $this->setObjectDescription("Debug-Ausgabe-Instance");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
// Set own instance
self::$thisInstance = $this;
* If no output is given this class is currently being used for back-fall.
* This fall-back mechanism will become deprecated very soon.
*
- * @param $debuggerClass The class name which we shall use for
+ * @param $debuggerClass The class name which we shall use for
* registering the *real* debug output
- * @return $debugInstance An instance of this middleware class
+ * @return $debugInstance An instance of this middleware class
*/
public final static function createDebugMiddleware ($debuggerClass) {
// Create an instance if this middleware
$debugInstance = new DebugMiddleware();
- // Is there a valid output handler provided?
- if ((!is_null($debuggerClass)) && (is_object($debuggerClass)) && (method_exists($debuggerClass, 'outputStream'))) {
- // Use the given output system
- $debugInstance->setOutputHandler($debuggerClass);
+ // Is there a valid output instance provided?
+ if ((!is_null($debuggerClass)) && (is_object($debuggerClass)) && ($debuggerClass instanceof OutputStreamer)) {
+ // Use the given output instance
+ $debugInstance->setOutputInstance($debuggerClass);
} elseif ((!is_null($debuggerClass)) && (is_string($debuggerClass)) && (class_exists($debuggerClass))) {
// A name for a debug output class has been provided so we try to get it
- $eval = sprintf("\$debuggerClass = %s::create%s();",
- $debuggerClass,
- $debuggerClass
- );
+ $debuggerInstance = ObjectFactory::createObjectByName($debuggerClass);
- // Run the constructed name
- @eval($eval);
-
- // Was this successfull?
- if ((is_object($debuggerClass)) && (method_exists($debuggerClass, "outputStream"))) {
- // Set this as output class
- $debugInstance->setOutputHandler($debuggerClass);
- } else {
- // No object or method is missing use fall-back
- throw new MissingMethodException(array($debuggerClass, 'outputStream'), self::EXCEPTION_MISSING_METHOD);
- }
+ // Set this as output class
+ $debugInstance->setOutputInstance($debuggerInstance);
}
// Return instance
}
/**
- * Setter for output handler
+ * Setter for output instance
*
+ * @param $outputInstance The debug output instance
* @return void
*/
- public final function setOutputHandler ($outputHandler) {
- $this->outputHandler = $outputHandler;
+ public final function setOutputInstance (OutputStreamer $outputInstance) {
+ $this->outputInstance = $outputInstance;
}
/**
* This method shall send debug output which can be HTML code for the
* browser or debug lines for a log file, etc. to the registered debug
- * output handler.
+ * output instance.
*
+ * @param $outStream Data we shall "stream" out to the world
* @return void
*/
public final function output ($outStream) {
- // Check if the output handler is valid
- if (is_null($this->outputHandler)) {
- // Debug output handler was not set
+ // Check if the output instance is valid
+ if (is_null($this->outputInstance)) {
+ // Debug output instance was not set
throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
- } elseif (!is_object($this->outputHandler)) {
- // The debug output handler is not an object
- throw new NoObjectException($this->ouputHandler, self::EXCEPTION_IS_NO_OBJECT);
- } elseif (!method_exists($this->outputHandler, 'outputStream')) {
+ } elseif (!is_object($this->outputInstance)) {
+ // The debug output instance is not an object
+ throw new NoObjectException($this->ouputInstance, self::EXCEPTION_IS_NO_OBJECT);
+ } elseif (!method_exists($this->outputInstance, 'outputStream')) {
// The required method outputStream() is missing
- throw new MissingMethodException(array($this->outputHandler, 'outputStream'), self::EXCEPTION_MISSING_METHOD);
+ throw new MissingMethodException(array($this->outputInstance, 'outputStream'), self::EXCEPTION_MISSING_METHOD);
}
// Is the output stream set
return;
}
- // Use the output handler
- $this->outputHandler->outputStream($outStream);
+ // Use the output instance
+ $this->outputInstance->outputStream($outStream);
}
}
$this->setObjectDescription("Datei-Ein-/Ausgabe-Handler");
// Create an unique ID
- $this->createUniqueID();
+ $this->generateUniqueId();
// Set own instance
self::$thisInstance = $this;
*/
// Load the class from inc/config direktory
-@require_once(dirname(__FILE__) . '/config/class_FrameworkConfiguration.php');
+require_once(dirname(__FILE__) . '/classes/interfaces/class_FrameworkInterface.php');
+require_once(dirname(__FILE__) . '/classes/interfaces/registry/class_Registerable.php');
+require_once(dirname(__FILE__) . '/config/class_FrameworkConfiguration.php');
// Get a new configuration instance
$cfg = FrameworkConfiguration::createFrameworkConfiguration();
// CFG: WEB-CONTENT-TYPE
$cfg->setConfigEntry('web_content_type', "text/html");
+// CFG: HEADER-CHARSET
+$cfg->setConfigEntry('header_charset', "utf-8");
+
// CFG: VALID-TEMPLATE-VARIABLE
$cfg->setConfigEntry('tpl_valid_var', "content");
// CFG: SEARCH-CRITERIA
$cfg->setConfigEntry('search_criteria', "SearchCriteria");
+// CFG: DATASET-CRITERIA
+$cfg->setConfigEntry('dataset_criteria', "DataSetCriteria");
+
// CFG: FILE-IO-HANDLER
$cfg->setConfigEntry('file_io_handler', "FileIoHandler");
// CFG: FILE-OUTPUT-STREAM
$cfg->setConfigEntry('file_output_stream', "FileIoStream");
+// CFG: EMAIL-VALIDATOR
+$cfg->setConfigEntry('email_validator', "EmailValidatorFilter");
+
+// CFG: USERNAME-VALIDATOR
+$cfg->setConfigEntry('username_validator', "UserNameValidatorFilter");
+
+// CFG: PASSWORD-VALIDATOR
+$cfg->setConfigEntry('password_validator', "PasswordValidatorFilter");
+
+// CFG: RULES-ACCEPTED-FILTER
+$cfg->setConfigEntry('rules_accepted_filter', "RulesAcceptedFilter");
+
+// CFG: CRYPTO-HELPER
+$cfg->setConfigEntry('crypto_heler', "CryptoHelper");
+
+// CFG: RNG-CLASS
+$cfg->setConfigEntry('rng_class', "RandomNumberGenerator");
+
+// CFG: USER-DB-WRAPPER
+$cfg->setConfigEntry('user_db_wrapper', "UserDatabaseWrapper");
+
+// CFG: WEB-CMD-RESOLVER
+$cfg->setConfigEntry('web_cmd_resolver', "WebCommandResolver");
+
+// CFG: MATH-PRIME
+$cfg->setConfigEntry('math_prime', 591623);
+
+// CFG: DATE-KEY
+$cfg->setConfigEntry('date_key', date("d-m-Y (l-F-T)", time()));
+
+// CFG: SALT-LENGTH
+$cfg->setConfigEntry('salt_length', 10);
+
+// CFG: RND-STR-LENGTH
+$cfg->setConfigEntry('rnd_str_length', 128);
+
+// CFG: HASH-MASK
+$cfg->setConfigEntry('hash_mask', "%1s:%2s:%3s"); // 1=salt, 2=extra salt, 3=plain password
+
+// CFG: IS-SINGLE-SERVER
+$cfg->setConfigEntry('is_single_server', "Y");
+
+// CFG: POST-REGISTRATION-ACTION
+$cfg->setConfigEntry('post_registration_action', "LoginAfterRegistrationAction");
+
+// CFG: USER-CLASS
+$cfg->setConfigEntry('user_class', "User");
+
// [EOF]
?>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-class FrameworkConfiguration {
+class FrameworkConfiguration implements Registerable {
/**
* The framework's main configuration array which will be initialized with
* hard-coded configuration data and might be overwritten/extended by
/**
* Local configuration. Do not edit config.php! Better overwrite the configuration here:
*
- * @author Roland Haeder <webmaster@mxchange.org>
- * @version 0.3.0
+ * @author Roland Haeder <webmaster@ship-simu.org>
+ * @version 0.0.0
* @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
* @license GNU GPL 3.0 or any newer version
- * @link http://www.mxchange.org
+ * @link http://www.ship-simu.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-// Get the configuration instance
-$cfg = FrameworkConfiguration::getInstance();
-
// CFG: DEFAULT-APPLICATION
-$cfg->setConfigEntry("default_application", "mxchange");
+FrameworkConfiguration::getInstance()->setConfigEntry("default_application", "mxchange");
+FrameworkConfiguration::getInstance()->setConfigEntry("app_name", "mxchange");
// [EOF]
?>
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
+// Get config instance
+$cfg = FrameworkConfiguration::getInstance();
+
// Include the class loader function
-require(sprintf("%sinc/loader/class_ClassLoader%s", PATH, FrameworkConfiguration::getInstance()->readConfig('php_extension')));
+require(sprintf("%sinc/loader/class_ClassLoader%s", PATH, $cfg->readConfig('php_extension')));
+
+// Does the user has an application specified?
+if (!empty($_GET[$cfg->readConfig('app_selector_get')])) {
+ // Set the application from string
+ $application = (string) $_GET[$cfg->readConfig('app_selector_get')];
+} elseif (!empty($_SERVER['argv'][1])) {
+ // Set the application from string
+ $application = (string) $_SERVER['argv'][1];
+ $app = explode('=', trim($application));
+ if ($app[0] == $cfg->readConfig('app_selector_get')) {
+ // Application is valid!
+ $application = trim($app[1]);
+ } else {
+ // Invalid entry found, first must be "app"!
+ $application = $cfg->readConfig('default_application');
+ }
+} else {
+ // Set the "application selector" application
+ $application = $cfg->readConfig('default_application');
+}
+
+// Secure it, by keeping out tags
+$application = htmlentities(strip_tags($application), ENT_QUOTES);
+
+// Secure it a little more with a reg.exp.
+$application = preg_replace('/([^a-z_-])+/i', "", $application);
+
+// Set the application name for later usage
+$cfg->setConfigEntry('app_name', $application);
+
+/**
+ * Autoload-function
+ *
+ * @param $className Name of the class to load
+ * @return void
+ */
+function __autoload ($className) {
+ // Try to include this class
+ ClassLoader::getInstance()->includeClass($className);
+}
/**
* Is the devel package included?
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* ----------------------------------
+ * 1.2
+ * - ClassLoader rewritten to PHP SPL's own RecursiveIteratorIterator class
* 1.1
* - loadClasses rewritten to fix some notices
* 1.0
* ----------------------------------
*/
class ClassLoader {
+ /**
+ * Instance of this class
+ */
+ private static $selfInstance = null;
+
/**
* Configuration array
*/
private $cfg = array();
/**
- * An ArrayObject for found classes
+ * Array with all classes
+ */
+ private $classes = array();
+
+ /**
+ * List of loaded classes
*/
- private $classes = null;
+ private $loadedClasses = array();
/**
* Suffix with extension for all class files
/**
* Length of the suffix. Will be overwritten later.
*/
- private $sufLen = 0;
+ private $suffixLen = 0;
/**
* Length of the prefix. Will be overwritten later.
*/
- private $preLen = 0;
+ private $prefixLen = 0;
/**
* A list for directory names (no leading/trailing slashes!) which not be scanned by the path scanner
private $ignoreList = array();
/**
- * An ArrayList object for include directories
+ * Debug this class loader? (true = yes, false = no)
*/
- private $dirList = null;
+ private $debug = false;
/**
- * Debug this class loader? (true = yes, false = no)
+ * Wether the file list is cached or not
*/
- private $debug = false;
+ private $listCached = false;
/**
- * Counter for scanned directories (debug output)
+ * Wethe class content has been cached
*/
- private $dirCnt = 0;
+ private $classesCached = false;
/**
- * Counter for loaded classes (debug output)
+ * Filename for the list cache
*/
- private $classCnt = 0;
+ private $listCacheFQFN = "";
/**
- * Instance of this class
+ * Cache for class content
*/
- private static $thisInstance = null;
+ private $classCacheFQFN = "";
/**
* The *public* constructor
* @return void
*/
public function __construct (FrameworkConfiguration $cfgInstance) {
- // Init the array list
- $this->dirList = new ArrayObject();
+ // Set configuration instance
+ $this->cfgInstance = $cfgInstance;
+
+ // Construct the FQFN for the cache
+ if (!defined('DEVELOPER')) {
+ $this->listCacheFQFN = PATH . $this->cfgInstance->readConfig('local_db_path') . "list-" . $this->cfgInstance->readConfig('app_name') . ".cache";
+ $this->classCacheFQFN = PATH . $this->cfgInstance->readConfig('local_db_path') . "class-" . $this->cfgInstance->readConfig('app_name') . ".cache";
+ } // END - if
// Set suffix and prefix from configuration
$this->suffix = $cfgInstance->readConfig('class_suffix');
$this->prefix = $cfgInstance->readConfig('class_prefix');
// Estimate length of prefix and suffix for substr() function (cache)
- $this->sufLen = strlen($this->suffix);
- $this->preLen = strlen($this->prefix);
+ $this->suffixLen = strlen($this->suffix);
+ $this->prefixLen = strlen($this->prefix);
- // Set configuration instance
- $this->cfgInstance = $cfgInstance;
+ // Set own instance
+ self::$selfInstance = $this;
- // Initialize the classes list
- $this->classes = new ArrayObject();
+ // Skip here if no dev-mode
+ if (defined('DEVELOPER')) return;
- // Set own instance
- self::$thisInstance = $this;
+ // IS the cache there?
+ if (file_exists($this->listCacheFQFN)) {
+ // Get content
+ $cacheContent = file_get_contents($this->listCacheFQFN);
+
+ // And convert it
+ $this->classes = unserialize($cacheContent);
+
+ // List has been restored from cache!
+ $this->listCached = true;
+ } // END - if
+
+ // Does the class cache exist?
+ if (file_exists($this->classCacheFQFN)) {
+ // Then include it
+ require($this->classCacheFQFN);
+
+ // Mark the class cache as loaded
+ $this->classesCached = true;
+ } // END - if
+ }
+
+ /**
+ * The destructor makes it sure all caches got flushed
+ *
+ * @return void
+ */
+ public function __destruct () {
+ // Skip here if dev-mode
+ if (defined('DEVELOPER')) return;
+
+ // Skip here if already cached
+ if ($this->listCached === false) {
+ // Writes the cache file of our list away
+ $cacheContent = serialize($this->classes);
+ file_put_contents($this->listCacheFQFN, $cacheContent);
+ } // END - if
+
+ // Skip here if already cached
+ if ($this->classesCached === false) {
+ // Generate a full-cache of all classes
+ $cacheContent = "";
+ foreach ($this->loadedClasses as $fqfn) {
+ // Load the file
+ $cacheContent .= file_get_contents($fqfn);
+ } // END - foreach
+
+ // And write it away
+ file_put_contents($this->classCacheFQFN, $cacheContent);
+ } // END - if
}
/**
* Getter for an instance of this class
*
- * @return $thisInstance An instance of this class
+ * @return $selfInstance An instance of this class
*/
public final static function getInstance () {
- return self::$thisInstance;
+ // Is the instance there?
+ if (is_null(self::$selfInstance)) {
+ // Get a new one
+ self::$selfInstance = new ClassLoader(FrameworkConfiguration::getInstance());
+ } // END - if
+
+ // Return the instance
+ return self::$selfInstance;
}
/**
* @return void
*/
public function loadClasses ($basePath, $ignoreList = array() ) {
+ // Is a list has been restored from cache, don't read it again
+ if ($this->listCached === true) {
+ // Abort here
+ return;
+ }
+
// Convert string to array
if (!is_array($ignoreList)) $ignoreList = array($ignoreList);
$ignoreList[] = ".";
$ignoreList[] = "..";
$ignoreList[] = ".htaccess";
+ $ignoreList[] = ".svn";
// Keep it in class for later usage
$this->ignoreList = $ignoreList;
// If the basePath is false it is invalid
if ($basePath2 === false) {
// TODO: Do not die here.
+ debug_print_backtrace();
die("Cannot read {$basePath} !");
} else {
// Set base path
$basePath = $basePath2;
}
- // Load all super classes (backward, why ever this name... :-? )
- // We don't support sub directories here...
- $this->scanLocalPath($basePath);
-
- // While there are directories in our list scan them for classes
- $cnt = 0;
- while ($cnt != $this->dirList->count()) {
- for ($idx = $this->dirList->getIterator(); $idx->valid(); $idx->next()) {
- // Get current path
- $currPath = $idx->current();
-
- // Remove the current entry or else this will lead into a infinite loop
- $this->dirList->offsetSet($idx->key(), "");
-
- // Scan the directory
- $this->scanLocalPath($currPath);
- }
-
- // Check if we can leave
- $cnt = 0;
- for ($idx = $this->dirList->getIterator(); $idx->valid(); $idx->next()) {
- if ($idx->current() == "") $cnt++;
- }
- }
- }
-
- /**
- * The local path scanner. A found class will be loaded immediately
- * @param $localPath The local path which shall be recursively scanned for include files
- * @return void
- */
- private function scanLocalPath ($localPath) {
- // Empty path names will be silently ignored
- if (empty($localPath)) return;
-
- // TODO: No dies here, mayybe this should be rewritten to throw an exception?
- $dirInstance = FrameworkDirectoryPointer::createFrameworkDirectoryPointer($localPath);
- while ($dirClass = $dirInstance->readDirectoryExcept($this->ignoreList)) {
- // We need the relative dir name as an array index some lines below
- $dirClass2 = $dirClass;
-
- // A nice replacement for a simple dot ;)
- $dirClass = sprintf("%s/%s", $localPath, $dirClass);
-
- // Is a readable file with configured prefix and suffix? All other
- // files will silently be ignored!
- //* DEBUG: */ print "Prefix=".$this->prefix."(".substr($dirClass2, 0 , $this->preLen).")\n";
- //* DEBUG: */ print "Suffix=".$this->suffix."(".substr($dirClass2, -$this->sufLen, $this->sufLen).")\n";
- //* DEBUG: */ print "ENTRY={$dirClass}\n";
- if (
- (is_file($dirClass))
- && (is_readable($dirClass))
- && (substr($dirClass2, 0 , $this->preLen) == $this->prefix)
- && (substr($dirClass2, -$this->sufLen, $this->sufLen) == $this->suffix)
- ) {
- // Class found so load it instantly
- //* DEBUG: */ print "CLASS={$dirClass}\n";
- $this->classes->append($dirClass);
- $this->classCnt++;
- } elseif (is_dir($dirClass) && !in_array($dirClass2, $this->ignoreList)) {
- // Directory found and added to list
- //* DEBUG: */ print "DIR={$dirClass}\n";
- if ($dirClass2 == "interfaces") {
- $this->scanLocalPath($dirClass);
- } else {
- $this->dirList->append($dirClass);
- }
- $this->dirCnt++;
- }
- //* DEBUG: */ print "LOOP!\n";
- } // END - while
-
- // Close directory handler
- $dirInstance->closeDirectory();
-
- // Output counter in debug mode
- if (defined('DEBUG_MODE')) print(sprintf("[%s:] <strong>%d</strong> Klassendateien in <strong>%d</strong> Verzeichnissen gefunden und geladen.<br />\n",
- __CLASS__,
- $this->classCnt,
- $this->dirCnt
- ));
- }
-
- /**
- * Includes all found classes
- * @return void
- */
- public function includeAllClasses () {
- if (is_object($this->classes)) {
- // Load all classes
- for ($idx = $this->classes->getIterator(); $idx->valid(); $idx->next()) {
- // Load current class
- //* DEBUG: */ print "Class=".$idx->current()."\n";
- require_once($idx->current());
- }
-
- // Re-initialize the classes list
- $this->classes = new ArrayObject();
- }
+ // Get a new iterator
+ //* DEBUG: */ echo "<strong>Base path: {$basePath}</strong><br />\n";
+ $iterator = new RecursiveDirectoryIterator($basePath);
+ $recursive = new RecursiveIteratorIterator($iterator);
+ foreach ($recursive as $entry) {
+ // Get filename from iterator
+ $fileName = $entry->getFileName();
+
+ // Is this file wanted?
+ //* DEBUG: */ echo "FOUND:{$fileName}<br />\n";
+ if ((!in_array($fileName, $this->ignoreList)) && (substr($fileName, 0, $this->prefixLen) == $this->prefix) && (substr($fileName, -$this->suffixLen, $this->suffixLen) == $this->suffix)) {
+ // Get the FQFN and add it to our class list
+ $fqfn = $entry->getRealPath();
+ //* DEBUG: */ echo "ADD: {$fileName}<br />\n";
+ $this->classes[$fileName] = $fqfn;
+ } // END - if
+ } // END - foreach
}
/**
// Set new prefix (temporary!)
$this->prefix = "config-";
- $this->preLen = strlen($this->prefix);
+ $this->prefixLen = strlen($this->prefix);
// Set base directory
$basePath = sprintf("%sinc/config/", PATH);
// Load all classes from the config directory
$this->loadClasses($basePath);
+ // Include these extra configs now
+ $this->includeExtraConfigs();
+
// Set the prefix back
$this->prefix = $oldPrefix;
- $this->preLen = strlen($this->prefix);
+ $this->prefixLen = strlen($this->prefix);
+
}
-}
-// Initial load of core classes and the FrameworkDirectoryPointer class
-require_once(sprintf("%sinc/classes/interfaces/class_FrameworkInterface%s", PATH, FrameworkConfiguration::getInstance()->readConfig('php_extension')));
-require_once(sprintf("%sinc/classes/main/class_BaseFrameworkSystem%s", PATH, FrameworkConfiguration::getInstance()->readConfig('php_extension')));
-require_once(sprintf("%sinc/classes/main/io/class_FrameworkDirectoryPointer%s", PATH, FrameworkConfiguration::getInstance()->readConfig('php_extension')));
+ /**
+ * Tries to find the given class in our list. This method ignores silently
+ * missing classes or interfaces. So if you use class_exists() this method
+ * does not interrupt your program.
+ *
+ * @param $className The class we shall load
+ * @return void
+ */
+ public function includeClass ($className) {
+ // Create a name with prefix and suffix
+ $fileName = $this->prefix . $className . $this->suffix;
+
+ // Now look it up in our index
+ if (isset($this->classes[$fileName])) {
+ // File is found so load it only once
+ require($this->classes[$fileName]);
+
+ // Developer mode excludes caching (better debugging)
+ if (!defined('DEVELOPER')) {
+ // Mark this class as loaded
+ $this->loadedClasses[] = $this->classes[$fileName];
+
+ // Reset cache
+ $this->classesCached = false;
+ } // END - if
+ } // END - if
+ }
-// Initialize the class loader
-$loader = new ClassLoader(FrameworkConfiguration::getInstance());
+ /**
+ * Includes all extra config files
+ *
+ * @return void
+ */
+ private function includeExtraConfigs () {
+ // Run through all class names (should not be much)
+ foreach ($this->classes as $fileName=>$fqfn) {
+ // Is this a config?
+ if (substr($fileName, 0, $this->prefixLen) == $this->prefix) {
+ // Then include it
+ require($fqfn);
+
+ // Remove it from the list
+ unset($this->classes[$fileName]);
+ } // END - if
+ } // END - foreach
+ }
+}
// [EOF]
?>
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
-// Does the user has an application specified?
-if (!empty($_GET[FrameworkConfiguration::getInstance()->readConfig('app_selector_get')])) {
- // Set the application from string
- $application = (string) $_GET[FrameworkConfiguration::getInstance()->readConfig('app_selector_get')];
-} elseif (!empty($_SERVER['argv'][1])) {
- // Set the application from string
- $application = (string) $_SERVER['argv'][1];
- $app = explode('=', trim($application));
- if ($app[0] == FrameworkConfiguration::getInstance()->readConfig('app_selector_get')) {
- // Application is valid!
- $application = trim($app[1]);
- } else {
- // Invalid entry found, first must be "app"!
- $application = FrameworkConfiguration::getInstance()->readConfig('default_application');
- }
-} else {
- // Set the "application selector" application
- $application = FrameworkConfiguration::getInstance()->readConfig('default_application');
-}
-
-// Secure it, by keeping out tags
-$application = htmlentities(strip_tags($application), ENT_QUOTES);
-
-// Secure it a little more with a reg.exp.
-$application = preg_replace('/([^a-z_-])+/i', "", $application);
+// Get config instance
+$cfg = FrameworkConfiguration::getInstance();
// Try to load these includes in the given order
$configAppIncludes = array(
- sprintf("class_%s", FrameworkConfiguration::getInstance()->readConfig('app_helper_class')), // The ApplicationHelper class
+ sprintf("class_%s", $cfg->readConfig('app_helper_class')), // The ApplicationHelper class
"config", // The application's own configuration
"init", // The application initializer
"loader", // The application's class loader
// Generate a FQFN for the helper class
$fqfn = sprintf("%s%s/%s/%s%s",
PATH,
- FrameworkConfiguration::getInstance()->readConfig('application_path'),
- $application,
+ $cfg->readConfig('application_path'),
+ $cfg->readConfig('app_name'),
$inc,
- FrameworkConfiguration::getInstance()->readConfig('php_extension')
+ $cfg->readConfig('php_extension')
);
// Does the include file exists?
if ((file_exists($fqfn)) && (is_file($fqfn)) && (is_readable($fqfn))) {
// Load it
require_once($fqfn);
- } elseif (FrameworkConfiguration::getInstance()->readConfig('verbose_level') > 0) {
+ } elseif ($cfg->readConfig('verbose_level') > 0) {
// File is missing
trigger_error(sprintf("Cannot load application script %s! File is missing or read-protected.",
- $inc . FrameworkConfiguration::getInstance()->readConfig('php_extension')
+ $inc . $cfg->readConfig('php_extension')
));
}
}
<?php
+// Developer mode active? Comment out if no dev!
+define('DEVELOPER', true);
+
+//xdebug_start_trace();
/**
* The main class with the entry point to the whole application. This class
* "emulates" Java(tm)'s entry point call. Additionally it covers local
* But good little boys and girls would always initialize their variables... ;-)
*
* @author Roland Haeder <webmaster@mxchange.org>
- * @version 0.3.0
+ * @version 0.0.0
* @copyright Copyright(c) 2007, 2008 Roland Haeder, this is free software
* @license GNU GPL 3.0 or any newer version
- * @link http://www.mxchange.org
+ * @link http://www.ship-simu.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
- * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class ApplicationEntryPoint {
/**
* @return void
*/
private static $instances = array (
- 'cfg', // The configuration system
- 'loader', // The class loader system
+ 'cfg', // The configuration system
+ 'loader', // The class loader system
'debug', // Debug output
'db', // Database layer
'io', // Base I/O system (local file [or network])
* @return void
*/
public static function app_die ($message = "") {
+ // Is this method already called?
+ if (defined('EMERGENCY_EXIT_CALLED')) {
+ // Then output the text directly
+ die($message);
+ }
+
+ // This method shall not be called twice
+ define('EMERGENCY_EXIT_CALLED', true);
+
// Is a message set?
if (empty($message)) {
// No message provided
}
// Get some instances
- $tpl = FrameworkConfiguration::getInstance()->readConfig("tpl_engine");
+ $tpl = FrameworkConfiguration::getInstance()->readConfig('tpl_engine');
$lang = LanguageSystem::getInstance();
- $io = FileIOHandler::getInstance();
+ $io = FileIoHandler::getInstance();
// Is the template engine loaded?
if ((class_exists($tpl)) && (is_object($lang)) && (is_object($io))) {
// Use the template engine for putting out (nicer look) the message
try {
- $eval = sprintf("\$tplEngine = %s::create%s(\"%s%s\", LanguageSystem::getInstance(), FileIOHandler::getInstance());",
- FrameworkConfiguration::getInstance()->readConfig("tpl_engine"),
- FrameworkConfiguration::getInstance()->readConfig("tpl_engine"),
- PATH,
- FrameworkConfiguration::getInstance()->readConfig("tpl_base_path")
- );
- eval($eval);
+ // Get the template instance from our object factory
+ $tplEngine = ObjectFactory::createObjectByConfiguredName('tpl_engine', array(FrameworkConfiguration::getInstance()->readConfig('tpl_base_path'), $lang, $io));
} catch (BasePathIsEmptyException $e) {
- die(sprintf("[Main:] Die Template-Engine konnte nicht initialisieren. Grund: <strong>%s</strong>",
+ die(sprintf("[Main:] Could not initialize template engine for this reason: <strong>%s</strong>",
$e->getMessage()
));
} catch (InvalidBasePathStringException $e) {
- die(sprintf("[Main:] Die Template-Engine konnte nicht initialisieren. Grund: <strong>%s</strong>",
+ die(sprintf("[Main:] Could not initialize template engine for this reason: <strong>%s</strong>",
$e->getMessage()
));
} catch (BasePathIsNoDirectoryException $e) {
- die(sprintf("[Main:] Die Template-Engine konnte nicht initialisieren. Grund: <strong>%s</strong>",
+ die(sprintf("[Main:] Could not initialize template engine for this reason: <strong>%s</strong>",
$e->getMessage()
));
} catch (BasePathReadProtectedException $e) {
- die(sprintf("[Main:] Die Template-Engine konnte nicht initialisieren. Grund: <strong>%s</strong>",
+ die(sprintf("[Main:] Could not initialize template engine for this reason: <strong>%s</strong>",
$e->getMessage()
));
}
- // Assign message
- $tplEngine->assignVariable("message", $message);
+ // Backtrace holen und aufbereiten
+ $backtraceArray = debug_backtrace();
+ $backtrace = "";
+ foreach ($backtraceArray as $key=>$trace) {
+ if (!isset($trace['file'])) $trace['file'] = __FILE__;
+ if (!isset($trace['line'])) $trace['line'] = 5;
+ if (!isset($trace['args'])) $trace['args'] = array();
+ $backtrace .= "<span class=\"backtrace_file\">".basename($trace['file'])."</span>:".$trace['line'].", <span class=\"backtrace_function\">".$trace['function']."(".count($trace['args']).")</span><br />";
+ }
+
+ // Assign variables
+ $tplEngine->assignVariable('message', $message);
+ $tplEngine->assignVariable('backtrace', $backtrace);
+ $tplEngine->assignVariable('total_objects', ObjectFactory::getTotal());
// Load the template
- $tplEngine->loadCodeTemplate("emergency_exit");
+ $tplEngine->loadCodeTemplate('emergency_exit');
// Compile the template
$tplEngine->compileTemplate();
exit();
} else {
// Output message and die
- die(sprintf("[Main:] Emergency exit reached: <strong>%s</strong>",
+ die(sprintf("[Main:] Emergency exit reached: <span class=\"emergency_span\">%s</span>",
$message
));
}
global $_SERVER;
// Load config file
- require(dirname(__FILE__) . "/inc/config.php");
+ require(dirname(__FILE__) . '/inc/config.php');
// Load all include files
- require(PATH . "inc/includes.php");
+ require(PATH . 'inc/includes.php');
// Load all framework classes
- require(PATH . "inc/classes.php");
+ require(PATH . 'inc/classes.php');
// Include the application selector
- require(PATH . "inc/selector.php");
+ require(PATH . 'inc/selector.php');
} // END - main()