3 * The simulator system class is the super class of all other classes. This
4 * class handles saving of games etc.
6 * @author Roland Haeder <webmaster@ship-simu.org>
8 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 Core Developer Team
9 * @license GNU GPL 3.0 or any newer version
10 * @link http://www.ship-simu.org
12 * This program is free software: you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation, either version 3 of the License, or
15 * (at your option) any later version.
17 * This program is distributed in the hope that it will be useful,
18 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 * GNU General Public License for more details.
22 * You should have received a copy of the GNU General Public License
23 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
27 * Instance of a request class
29 private $requestInstance = null;
32 * Instance of a response class
34 private $responseInstance = null;
37 * Search criteria instance
39 private $searchInstance = null;
42 * Update criteria instance
44 private $updateInstance = null;
47 * The file I/O instance for the template loader
49 private $fileIoInstance = null;
54 private $resolverInstance = null;
57 * Template engine instance
59 private $templateInstance = null;
62 * Database result instance
64 private $resultInstance = null;
67 * Instance for user class
69 private $userInstance = null;
72 * A controller instance
74 private $controllerInstance = null;
79 private $rngInstance = null;
82 * Instance of an Iterator class
84 private $iteratorInstance = null;
89 private $realClass = 'BaseFrameworkSystem';
94 private $thousands = '.'; // German
99 private $decimals = ','; // German
101 /***********************
102 * Exception codes.... *
103 ***********************/
105 const EXCEPTION_IS_NULL_POINTER = 0x001;
106 const EXCEPTION_IS_NO_OBJECT = 0x002;
107 const EXCEPTION_IS_NO_ARRAY = 0x003;
108 const EXCEPTION_MISSING_METHOD = 0x004;
109 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
110 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
111 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
112 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
113 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
114 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
115 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
116 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
117 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
118 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
119 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
120 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
121 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
122 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
123 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
124 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
125 const EXCEPTION_PATH_NOT_FOUND = 0x015;
126 const EXCEPTION_INVALID_PATH_NAME = 0x016;
127 const EXCEPTION_READ_PROTECED_PATH = 0x017;
128 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
129 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
130 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
131 const EXCEPTION_INVALID_DIRECTORY_POINTER = 0x01b;
132 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
133 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
134 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
135 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
136 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
137 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
138 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
139 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
140 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
141 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
142 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
143 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
144 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
145 const EXCEPTION_INVALID_STRING = 0x029;
146 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
147 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
148 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
149 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
150 const EXCEPTION_MISSING_LANGUAGE_HANDLER = 0x02e;
151 const EXCEPTION_MISSING_FILE_IO_HANDLER = 0x02f;
152 const EXCEPTION_MISSING_ELEMENT = 0x030;
153 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
154 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
155 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
156 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
157 const EXCEPTION_FATAL_ERROR = 0x035;
158 const EXCEPTION_FILE_NOT_FOUND = 0x036;
159 const EXCEPTION_ASSERTION_FAILED = 0x037;
160 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
161 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
162 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x040;
165 * In the super constructor these system classes shall be ignored or else
166 * we would get an endless calling loop.
168 *---------------------------------------------------------------------*
169 * ATTENTION: IF YOU REMOVE ONE OF THEM YOU WILL RUN YOUR SERVER IN AN *
171 *---------------------------------------------------------------------*
173 private $systemClasses = array(
174 'DebugMiddleware', // Debug middleware output sub-system
175 'Registry', // Object registry
176 'ObjectFactory', // Object factory
177 'DebugWebOutput', // Debug web output sub-system
178 'WebOutput', // Web output sub-system
179 'CompressorChannel', // Compressor sub-system
180 'DebugConsoleOutput', // Debug console output sub-system
181 'DebugErrorLogOutput', // Debug error_log() output sub-system
182 'FrameworkDirectoryPointer', // Directory handler sub-system
183 'NullCompressor', // Null compressor
184 'Bzip2Compressor', // BZIP2 compressor
185 'GzipCompressor', // GZIP compressor
188 * Protected super constructor
190 * @param $className Name of the class
193 protected function __construct ($className) {
195 $this->setRealClass($className);
197 // Initialize the class if class Registry is there
198 if ((class_exists('Registry')) && (Registry::isInitialized() === false)) {
199 // Initialize the registry automatically
200 $this->initInstance();
205 * Destructor reached...
208 * @todo This is old code. Do we still need this old lost code?
210 public function __destruct() {
211 // Flush any updated entries to the database
212 $this->flushPendingUpdates();
214 // Is this object already destroyed?
215 if ($this->__toString() != 'DestructedObject') {
216 // Destroy all informations about this class but keep some text about it alive
217 $this->setRealClass('DestructedObject');
218 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
219 // Already destructed object
220 $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
228 * The call method where all non-implemented methods end up
232 public final function __call ($methodName, $args) {
233 // Implode all given arguments
237 $argsString = 'NULL';
238 } elseif (is_array($args)) {
239 // Some arguments are there
240 foreach ($args as $arg) {
242 $argsString .= $arg . ' (' . gettype($arg);
244 // Add length if type is string
245 if (gettype($arg) == 'string') $argsString .= ', '.strlen($arg);
248 $argsString .= '), ';
252 if (substr($argsString, -2, 1) == ',') {
253 $argsString = substr($argsString, 0, -2);
256 // Invalid arguments!
257 $argsString = '!INVALID:' . gettype($args) . '!';
260 // Output stub message
261 $this->debugOutput(sprintf("[%s->%s] Stub! Args: %s",
272 * Private initializer for this class
276 private final function initInstance () {
277 // Is this a system class?
278 if (!in_array($this->__toString(), $this->systemClasses)) {
279 // Set configuration instance
280 $this->setConfigInstance(FrameworkConfiguration::getInstance());
282 // Add application helper to our class
283 $this->systemclasses[] = $this->getConfigInstance()->getConfigEntry('app_helper_class');
285 // Set debug instance
286 $this->setDebugInstance(DebugMiddleware::createDebugMiddleware($this->getConfigInstance()->getConfigEntry('debug_class')));
288 // Get output instance and set it
289 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($this->getConfigInstance()->getConfigEntry('web_content_type')));
290 $this->setWebOutputInstance($outputInstance);
292 // Set the compressor channel
293 $this->setCompressorChannel(CompressorChannel::createCompressorChannel(
294 $this->getConfigInstance()->getConfigEntry('base_path').
295 $this->getConfigInstance()->getConfigEntry('compressor_base_path')
298 // Initialization done! :D
299 Registry::isInitialized('OK');
300 } elseif ($this->__toString() == 'DebugMiddleware') {
301 // Set configuration instance
302 $this->setConfigInstance(FrameworkConfiguration::getInstance());
307 * Setter for database result instance
309 * @param $resultInstance An instance of a database result class
311 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
313 protected final function setResultInstance (SearchableResult $resultInstance) {
314 $this->resultInstance = $resultInstance;
318 * Getter for database result instance
320 * @return $resultInstance An instance of a database result class
322 public final function getResultInstance () {
323 return $this->resultInstance;
327 * Setter for template engine instances
329 * @param $templateInstance An instance of a template engine class
332 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
333 $this->templateInstance = $templateInstance;
337 * Getter for template engine instances
339 * @return $templateInstance An instance of a template engine class
341 protected final function getTemplateInstance () {
342 return $this->templateInstance;
346 * Setter for search instance
348 * @param $searchInstance Searchable criteria instance
351 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
352 $this->searchInstance = $searchInstance;
356 * Getter for search instance
358 * @return $searchInstance Searchable criteria instance
360 public final function getSearchInstance () {
361 return $this->searchInstance;
365 * Setter for update instance
367 * @param $updateInstance Searchable criteria instance
370 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
371 $this->updateInstance = $updateInstance;
375 * Getter for update instance
377 * @return $updateInstance Updateable criteria instance
379 public final function getUpdateInstance () {
380 return $this->updateInstance;
384 * Setter for resolver instance
386 * @param $resolverInstance Instance of a command resolver class
389 public final function setResolverInstance (Resolver $resolverInstance) {
390 $this->resolverInstance = $resolverInstance;
394 * Getter for resolver instance
396 * @return $resolverInstance Instance of a command resolver class
398 public final function getResolverInstance () {
399 return $this->resolverInstance;
403 * Setter for language instance
405 * @param $configInstance The configuration instance which shall
406 * be FrameworkConfiguration
409 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
410 Registry::getRegistry()->addInstance('config', $configInstance);
414 * Getter for configuration instance
416 * @return $configInstance Configuration instance
418 public final function getConfigInstance () {
419 $configInstance = Registry::getRegistry()->getInstance('config');
420 return $configInstance;
424 * Setter for debug instance
426 * @param $debugInstance The instance for debug output class
429 public final function setDebugInstance (DebugMiddleware $debugInstance) {
430 Registry::getRegistry()->addInstance('debug', $debugInstance);
434 * Getter for debug instance
436 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
438 public final function getDebugInstance () {
439 $debugInstance = Registry::getRegistry()->getInstance('debug');
440 return $debugInstance;
444 * Setter for web output instance
446 * @param $webInstance The instance for web output class
449 public final function setWebOutputInstance (OutputStreamer $webInstance) {
450 Registry::getRegistry()->addInstance('web_output', $webInstance);
454 * Getter for web output instance
456 * @return $webOutputInstance - Instance to class WebOutput
458 public final function getWebOutputInstance () {
459 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
460 return $webOutputInstance;
464 * Setter for database instance
466 * @param $dbInstance The instance for the database connection
467 * (forced DatabaseConnection)
470 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
471 Registry::getRegistry()->addInstance('db_instance', $dbInstance);
475 * Getter for database layer
477 * @return $dbInstance The database layer instance
479 public final function getDatabaseInstance () {
480 // Default is invalid db instance
483 // Is the registry there and initialized?
484 if ((class_exists('Registry')) && (Registry::isInitialized() === true)) {
485 $dbInstance = Registry::getRegistry()->getInstance('db_instance');
493 * Setter for compressor channel
495 * @param $compressorInstance An instance of CompressorChannel
498 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
499 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
503 * Getter for compressor channel
505 * @return $compressorInstance The compressor channel
507 public final function getCompressorChannel () {
508 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
509 return $compressorInstance;
513 * Protected getter for a manageable application helper class
515 * @return $applicationInstance An instance of a manageable application helper class
517 protected final function getApplicationInstance () {
518 $applicationInstance = Registry::getRegistry()->getInstance('application');
519 return $applicationInstance;
523 * Setter for a manageable application helper class
525 * @param $applicationInstance An instance of a manageable application helper class
528 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
529 Registry::getRegistry()->addInstance('application', $applicationInstance);
533 * Setter for request instance
535 * @param $requestInstance An instance of a Requestable class
538 public final function setRequestInstance (Requestable $requestInstance) {
539 $this->requestInstance = $requestInstance;
543 * Getter for request instance
545 * @return $requestInstance An instance of a Requestable class
547 public final function getRequestInstance () {
548 return $this->requestInstance;
552 * Setter for response instance
554 * @param $responseInstance An instance of a Responseable class
557 public final function setResponseInstance (Responseable $responseInstance) {
558 $this->responseInstance = $responseInstance;
562 * Getter for response instance
564 * @return $responseInstance An instance of a Responseable class
566 public final function getResponseInstance () {
567 return $this->responseInstance;
571 * Getter for $realClass
573 * @return $realClass The name of the real class (not BaseFrameworkSystem)
575 public final function __toString () {
576 return $this->realClass;
580 * Setter for the real class name
582 * @param $realClass Class name (string)
585 public final function setRealClass ($realClass) {
587 $realClass = (string) $realClass;
590 $this->realClass = $realClass;
594 * Compare class name of this and given class name
596 * @param $className The class name as string from the other class
597 * @return boolean The result of comparing both class names
599 public final function isClass ($className) {
600 return ($this->__toString() == $className);
604 * Formats computer generated price values into human-understandable formats
605 * with thousand and decimal seperators.
607 * @param $value The in computer format value for a price
608 * @param $currency The currency symbol (use HTML-valid characters!)
609 * @param $decNum Number of decimals after commata
610 * @return $price The for the current language formated price string
611 * @throws MissingDecimalsThousandsSeperatorException If decimals or
612 * thousands seperator
615 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
616 // Are all required attriutes set?
617 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
618 // Throw an exception
619 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
623 $value = (float) $value;
625 // Reformat the US number
626 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
628 // Return as string...
633 * Removes number formating characters
637 public final function removeNumberFormaters () {
638 unset($this->thousands);
639 unset($this->decimals);
643 * Private getter for language instance
645 * @return $langInstance An instance to the language sub-system
647 protected final function getLanguageInstance () {
648 $langInstance = Registry::getRegistry()->getInstance('language');
649 return $langInstance;
653 * Setter for language instance
655 * @param $langInstance An instance to the language sub-system
657 * @see LanguageSystem
659 public final function setLanguageInstance (ManageableLanguage $langInstance) {
660 Registry::getRegistry()->addInstance('language', $langInstance);
664 * Remove the $systemClasses array from memory
668 public final function removeSystemArray () {
669 unset($this->systemClasses);
673 * Appends a trailing slash to a string
675 * @param $str A string (maybe) without trailing slash
676 * @return $str A string with an auto-appended trailing slash
678 public final function addMissingTrailingSlash ($str) {
679 // Is there a trailing slash?
680 if (substr($str, -1, 1) != '/') $str .= '/';
685 * Private getter for file IO instance
687 * @return $fileIoInstance An instance to the file I/O sub-system
689 protected final function getFileIoInstance () {
690 return $this->fileIoInstance;
694 * Setter for file I/O instance
696 * @param $fileIoInstance An instance to the file I/O sub-system
699 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
700 $this->fileIoInstance = $fileIoInstance;
704 * Prepare the template engine (WebTemplateEngine by default) for a given
705 * application helper instance (ApplicationHelper by default).
707 * @param $appInstance An application helper instance or
708 * null if we shall use the default
709 * @return $templateInstance The template engine instance
710 * @throws NullPointerException If the template engine could not
712 * @throws UnsupportedTemplateEngineException If $templateInstance is an
713 * unsupported template engine
714 * @throws MissingLanguageHandlerException If the language sub-system
715 * is not yet initialized
716 * @throws NullPointerException If the discovered application
717 * instance is still null
719 protected function prepareTemplateInstance (BaseFrameworkSystem $appInstance=null) {
720 // Is the application instance set?
721 if (is_null($appInstance)) {
722 // Get the current instance
723 $appInstance = $this->getApplicationInstance();
726 if (is_null($appInstance)) {
727 // Thrown an exception
728 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
732 // Are both instances set?
733 if ($appInstance->getLanguageInstance() === null) {
734 // Invalid language instance
735 throw new MissingLanguageHandlerException($appInstance, self::EXCEPTION_MISSING_LANGUAGE_HANDLER);
736 } elseif ($appInstance->getFileIoInstance() === null) {
737 // Invalid language instance
738 throw new MissingFileIoHandlerException($appInstance, self::EXCEPTION_MISSING_FILE_IO_HANDLER);
741 // Initialize the template engine
742 $templateInstance = ObjectFactory::createObjectByConfiguredName('template_class', array($appInstance));
744 // Return the prepared instance
745 return $templateInstance;
749 * Debugs this instance by putting out it's full content
751 * @param $message Optional message to show in debug output
754 public final function debugInstance ($message = '') {
755 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
756 restore_error_handler();
762 if (!empty($message)) {
764 $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
767 // Generate the output
768 $content .= sprintf("<pre>%s</pre>",
777 ApplicationEntryPoint::app_die(sprintf("<div class=\"debug_header\">%s debug output:</div><div class=\"debug_content\">%s</div>\nLoaded includes: <div class=\"debug_include_list\">%s</div>",
780 ClassLoader::getInstance()->getPrintableIncludeList()
785 * Output a partial stub message for the caller method
787 * @param $message An optional message to display
790 protected function partialStub ($message = '') {
792 $backtrace = debug_backtrace();
794 // Generate the class::method string
795 $methodName = 'UnknownClass->unknownMethod';
796 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
797 $methodName = $backtrace[1]['class']."->".$backtrace[1]['function'];
800 // Construct the full message
801 $stubMessage = sprintf("[%s:] Partial stub!",
805 // Is the extra message given?
806 if (!empty($message)) {
807 // Then add it as well
808 $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
811 // Debug instance is there?
812 if (!is_null($this->getDebugInstance())) {
813 // Output stub message
814 $this->debugOutput($stubMessage);
817 trigger_error($stubMessage."<br />\n");
822 * Outputs a debug backtrace and stops further script execution
826 public function debugBackTrace () {
827 // Sorry, there is no other way getting this nice backtrace
829 debug_print_backtrace();
835 * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
837 * @param $message Message we shall send out...
838 * @param $doPrint Wether we shall print or die here which first is the default
841 public function debugOutput ($message, $doPrint = true) {
842 // Get debug instance
843 $debugInstance = $this->getDebugInstance();
845 // Is the debug instance there?
846 if (is_object($debugInstance)) {
847 // Use debug output handler
848 $debugInstance->output($message);
849 if ($doPrint === false) die(); // Die here if not printed
852 if ($doPrint === true) {
855 // DO NOT REWRITE THIS TO app_die() !!!
862 * Converts e.g. a command from URL to a valid class by keeping out bad characters
864 * @param $str The string, what ever it is needs to be converted
865 * @return $className Generated class name
867 public function convertToClassName ($str) {
871 // Convert all dashes in underscores
872 $str = $this->convertDashesToUnderscores($str);
874 // Now use that underscores to get classname parts for hungarian style
875 foreach (explode('_', $str) as $strPart) {
876 // Make the class name part lower case and first upper case
877 $className .= ucfirst(strtolower($strPart));
885 * Converts dashes to underscores, e.g. useable for configuration entries
887 * @param $str The string with maybe dashes inside
888 * @return $str The converted string with no dashed, but underscores
890 public final function convertDashesToUnderscores ($str) {
892 $str = str_replace('-', '_', $str);
894 // Return converted string
899 * Marks up the code by adding e.g. line numbers
901 * @param $phpCode Unmarked PHP code
902 * @return $markedCode Marked PHP code
904 public function markupCode ($phpCode) {
909 $errorArray = error_get_last();
911 // Init the code with error message
912 if (is_array($errorArray)) {
914 $markedCode = sprintf("<div id=\"error_header\">File: <span id=\"error_data\">%s</span>, Line: <span id=\"error_data\">%s</span>, Message: <span id=\"error_data\">%s</span>, Type: <span id=\"error_data\">%s</span></div>",
915 basename($errorArray['file']),
917 $errorArray['message'],
922 // Add line number to the code
923 foreach (explode("\n", $phpCode) as $lineNo => $code) {
925 $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
927 htmlentities($code, ENT_QUOTES)
936 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
937 * beatiful for web-based front-ends. If null is given a message id
938 * null_timestamp will be resolved and returned.
940 * @param $timestamp Timestamp to prepare (filter) for display
941 * @return $readable A readable timestamp
943 public function doFilterFormatTimestamp ($timestamp) {
944 // Default value to return
947 // Is the timestamp null?
948 if (is_null($timestamp)) {
949 // Get a message string
950 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
952 switch ($this->getLanguageInstance()->getLanguageCode()) {
953 case "de": // German format is a bit different to default
954 // Split the GMT stamp up
955 $dateTime = explode(' ', $timestamp );
956 $dateArray = explode('-', $dateTime[0]);
957 $timeArray = explode(':', $dateTime[1]);
959 // Construct the timestamp
960 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
970 default: // Default is pass-through
971 $readable = $timestamp;
981 * "Getter" for databse entry
983 * @return $entry An array with database entries
984 * @throws NullPointerException If the database result is not found
985 * @throws InvalidDatabaseResultException If the database result is invalid
987 protected final function getDatabaseEntry () {
988 // Is there an instance?
989 if (is_null($this->getResultInstance())) {
990 // Throw an exception here
991 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
995 $this->getResultInstance()->rewind();
997 // Do we have an entry?
998 if ($this->getResultInstance()->valid() === false) {
999 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1003 $this->getResultInstance()->next();
1006 $entry = $this->getResultInstance()->current();
1013 * Getter for field name
1015 * @param $fieldName Field name which we shall get
1016 * @return $fieldValue Field value from the user
1017 * @throws NullPointerException If the result instance is null
1019 public final function getField ($fieldName) {
1020 // Default field value
1023 // Get result instance
1024 $resultInstance = $this->getResultInstance();
1026 // Is this instance null?
1027 if (is_null($resultInstance)) {
1028 // Then the user instance is no longer valid (expired cookies?)
1029 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1032 // Get current array
1033 $fieldArray = $resultInstance->current();
1035 // Does the field exist?
1036 if (isset($fieldArray[$fieldName])) {
1038 $fieldValue = $fieldArray[$fieldName];
1046 * Protected setter for user instance
1048 * @param $userInstance An instance of a user class
1051 protected final function setUserInstance (ManageableAccount $userInstance) {
1052 $this->userInstance = $userInstance;
1056 * Getter for user instance
1058 * @return $userInstance An instance of a user class
1060 public final function getUserInstance () {
1061 return $this->userInstance;
1065 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1067 * @param $controllerInstance An instance of the controller
1070 public final function setControllerInstance (Controller $controllerInstance) {
1071 $this->controllerInstance = $controllerInstance;
1075 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1077 * @return $controllerInstance An instance of the controller
1079 public final function getControllerInstance () {
1080 return $this->controllerInstance;
1084 * Flushs all pending updates to the database layer
1088 public function flushPendingUpdates () {
1089 // Get result instance
1090 $resultInstance = $this->getResultInstance();
1092 // Do we have data to update?
1093 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1094 // Get wrapper class name config entry
1095 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1097 // Create object instance
1098 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1100 // Yes, then send the whole result to the database layer
1101 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1106 * Outputs a deprecation warning to the developer.
1108 * @param $message The message we shall output to the developer
1110 * @todo Write a logging mechanism for productive mode
1112 public function deprecationWarning ($message) {
1113 // Is developer mode active?
1114 if (defined('DEVELOPER')) {
1115 // Debug instance is there?
1116 if (!is_null($this->getDebugInstance())) {
1117 // Output stub message
1118 $this->debugOutput($message);
1121 trigger_error($message."<br />\n");
1124 // @TODO Finish this part!
1125 $this->partialStub('Developer mode inactive. Message:' . $message);
1130 * Generates a generic hash code of this class. You should really overwrite
1131 * this method with your own hash code generator code. But keep KISS in mind.
1133 * @return $hashCode A generic hash code respresenting this whole class
1135 public function hashCode () {
1137 return crc32($this->__toString());
1141 * Checks wether the given PHP extension is loaded
1143 * @param $phpExtension The PHP extension we shall check
1144 * @return $isLoaded Wether the PHP extension is loaded
1146 public final function isPhpExtensionLoaded ($phpExtension) {
1148 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1155 * Setter for RNG instance
1157 * @param $rngInstance An instance of a random number generator (RNG)
1160 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1161 $this->rngInstance = $rngInstance;
1165 * Getter for RNG instance
1167 * @return $rngInstance An instance of a random number generator (RNG)
1169 public final function getRngInstance () {
1170 return $this->rngInstance;
1174 * Setter for Iterator instance
1176 * @param $iteratorInstance An instance of an Iterator
1179 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1180 $this->iteratorInstance = $iteratorInstance;
1184 * Getter for Iterator instance
1186 * @return $iteratorInstance An instance of an Iterator
1188 public final function getIteratorInstance () {
1189 return $this->iteratorInstance;