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 - 2011 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 a crypto helper
84 private $cryptoInstance = null;
87 * Instance of an Iterator class
89 private $iteratorInstance = null;
92 * Instance of the list
94 private $listInstance = null;
99 private $menuInstance = null;
102 * Instance of the image
104 private $imageInstance = null;
107 * Instance of the stacker
109 private $stackerInstance = null;
112 * A Compressor instance
114 private $compressorInstance = null;
117 * A Parseable instance
119 private $parserInstance = null;
122 * A ProtocolHandler instance
124 private $protocolInstance = null;
127 * A database wrapper instance
129 private $databaseInstance = null;
132 * A helper instance for the form
134 private $helperInstance = null;
137 * An instance of a Sourceable class
139 private $sourceInstance = null;
142 * An instance of a InputStreamable class
144 private $inputStreamInstance = null;
147 * An instance of a OutputStreamable class
149 private $outputStreamInstance = null;
152 * The real class name
154 private $realClass = 'BaseFrameworkSystem';
157 * An instance of a database wrapper class
159 private $wrapperInstance = null;
162 * Thousands seperator
164 private $thousands = '.'; // German
169 private $decimals = ','; // German
174 private $socketResource = false;
179 private $packageData = array();
181 /***********************
182 * Exception codes.... *
183 ***********************/
185 // @todo Try to clean these constants up
186 const EXCEPTION_IS_NULL_POINTER = 0x001;
187 const EXCEPTION_IS_NO_OBJECT = 0x002;
188 const EXCEPTION_IS_NO_ARRAY = 0x003;
189 const EXCEPTION_MISSING_METHOD = 0x004;
190 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
191 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
192 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
193 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
194 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
195 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
196 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
197 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
198 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
199 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
200 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
201 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
202 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
203 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
204 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
205 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
206 const EXCEPTION_PATH_NOT_FOUND = 0x015;
207 const EXCEPTION_INVALID_PATH_NAME = 0x016;
208 const EXCEPTION_READ_PROTECED_PATH = 0x017;
209 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
210 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
211 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
212 const EXCEPTION_INVALID_RESOURCE = 0x01b;
213 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
214 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
215 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
216 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
217 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
218 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
219 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
220 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
221 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
222 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
223 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
224 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
225 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
226 const EXCEPTION_INVALID_STRING = 0x029;
227 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
228 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
229 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
230 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
231 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
232 const EXCEPTION_MISSING_ELEMENT = 0x030;
233 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
234 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
235 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
236 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
237 const EXCEPTION_FATAL_ERROR = 0x035;
238 const EXCEPTION_FILE_NOT_FOUND = 0x036;
239 const EXCEPTION_ASSERTION_FAILED = 0x037;
240 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
241 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
242 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x040;
244 // Hexadecimal->Decimal translation array
245 private static $hexdec = array(
264 // Decimal->hexadecimal translation array
265 private static $dechex = array(
285 * Protected super constructor
287 * @param $className Name of the class
290 protected function __construct ($className) {
292 $this->setRealClass($className);
294 // Set configuration instance if no registry ...
295 if (!$this instanceof Register) {
296 // ... because registries doesn't need to be configured
297 $this->setConfigInstance(FrameworkConfiguration::getInstance());
302 * Destructor reached...
306 public function __destruct() {
307 // Flush any updated entries to the database
308 $this->flushPendingUpdates();
310 // Is this object already destroyed?
311 if ($this->__toString() != 'DestructedObject') {
312 // Destroy all informations about this class but keep some text about it alive
313 $this->setRealClass('DestructedObject');
314 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
315 // Already destructed object
316 $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
324 * The __call() method where all non-implemented methods end up
326 * @param $methodName Name of the missing method
327 * @args $args Arguments passed to the method
330 public final function __call ($methodName, $args) {
331 // Implode all given arguments
335 $argsString = 'NULL';
336 } elseif (is_array($args)) {
337 // Some arguments are there
338 foreach ($args as $arg) {
340 $argsString .= $this->replaceControlCharacters($arg) . ' (' . gettype($arg);
342 // Add length if type is string
343 if (is_string($arg)) {
344 $argsString .= ', '.strlen($arg);
348 $argsString .= '), ';
352 if (substr($argsString, -2, 1) == ',') {
353 $argsString = substr($argsString, 0, -2);
356 // Invalid arguments!
357 $argsString = '!INVALID:' . gettype($args) . '!';
360 // Output stub message
361 $this->debugOutput(sprintf("[%s->%s] Stub! Args: %s",
372 * Getter for $realClass
374 * @return $realClass The name of the real class (not BaseFrameworkSystem)
376 public function __toString () {
377 return $this->realClass;
381 * Magic function to catch setting of missing but set class fields/attributes
383 * @param $name Name of the field/attribute
384 * @param $value Value to store
387 public final function __set ($name, $value) {
388 $this->debugBackTrace(sprintf("Tried to set a missing field. name=%s, value[%s]=%s",
396 * Magic function to catch getting of missing fields/attributes
398 * @param $name Name of the field/attribute
401 public final function __get ($name) {
402 $this->debugBackTrace(sprintf("Tried to get a missing field. name=%s",
408 * Magic function to catch unsetting of missing fields/attributes
410 * @param $name Name of the field/attribute
413 public final function __unset ($name) {
414 $this->debugBackTrace(sprintf("Tried to unset a missing field. name=%s",
420 * Setter for database result instance
422 * @param $resultInstance An instance of a database result class
424 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
426 protected final function setResultInstance (SearchableResult $resultInstance) {
427 $this->resultInstance = $resultInstance;
431 * Getter for database result instance
433 * @return $resultInstance An instance of a database result class
435 public final function getResultInstance () {
436 return $this->resultInstance;
440 * Setter for template engine instances
442 * @param $templateInstance An instance of a template engine class
445 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
446 $this->templateInstance = $templateInstance;
450 * Getter for template engine instances
452 * @return $templateInstance An instance of a template engine class
454 protected final function getTemplateInstance () {
455 return $this->templateInstance;
459 * Setter for search instance
461 * @param $searchInstance Searchable criteria instance
464 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
465 $this->searchInstance = $searchInstance;
469 * Getter for search instance
471 * @return $searchInstance Searchable criteria instance
473 public final function getSearchInstance () {
474 return $this->searchInstance;
478 * Setter for update instance
480 * @param $updateInstance Searchable criteria instance
483 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
484 $this->updateInstance = $updateInstance;
488 * Getter for update instance
490 * @return $updateInstance Updateable criteria instance
492 public final function getUpdateInstance () {
493 return $this->updateInstance;
497 * Setter for resolver instance
499 * @param $resolverInstance Instance of a command resolver class
502 public final function setResolverInstance (Resolver $resolverInstance) {
503 $this->resolverInstance = $resolverInstance;
507 * Getter for resolver instance
509 * @return $resolverInstance Instance of a command resolver class
511 public final function getResolverInstance () {
512 return $this->resolverInstance;
516 * Setter for language instance
518 * @param $configInstance The configuration instance which shall
519 * be FrameworkConfiguration
522 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
523 Registry::getRegistry()->addInstance('config', $configInstance);
527 * Getter for configuration instance
529 * @return $configInstance Configuration instance
531 public final function getConfigInstance () {
532 $configInstance = Registry::getRegistry()->getInstance('config');
533 return $configInstance;
537 * Setter for debug instance
539 * @param $debugInstance The instance for debug output class
542 public final function setDebugInstance (DebugMiddleware $debugInstance) {
543 Registry::getRegistry()->addInstance('debug', $debugInstance);
547 * Getter for debug instance
549 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
551 public final function getDebugInstance () {
552 // Get debug instance
553 $debugInstance = Registry::getRegistry()->getInstance('debug');
556 return $debugInstance;
560 * Setter for web output instance
562 * @param $webInstance The instance for web output class
565 public final function setWebOutputInstance (OutputStreamer $webInstance) {
566 Registry::getRegistry()->addInstance('web_output', $webInstance);
570 * Getter for web output instance
572 * @return $webOutputInstance - Instance to class WebOutput
574 public final function getWebOutputInstance () {
575 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
576 return $webOutputInstance;
580 * Setter for database instance
582 * @param $dbInstance The instance for the database connection (forced DatabaseConnection)
585 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
586 Registry::getRegistry()->addInstance('db_instance', $dbInstance);
590 * Getter for database layer
592 * @return $dbInstance The database layer instance
594 public final function getDatabaseInstance () {
596 $dbInstance = Registry::getRegistry()->getInstance('db_instance');
603 * Setter for compressor channel
605 * @param $compressorInstance An instance of CompressorChannel
608 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
609 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
613 * Getter for compressor channel
615 * @return $compressorInstance The compressor channel
617 public final function getCompressorChannel () {
618 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
619 return $compressorInstance;
623 * Protected getter for a manageable application helper class
625 * @return $applicationInstance An instance of a manageable application helper class
627 protected final function getApplicationInstance () {
628 $applicationInstance = Registry::getRegistry()->getInstance('application');
629 return $applicationInstance;
633 * Setter for a manageable application helper class
635 * @param $applicationInstance An instance of a manageable application helper class
638 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
639 Registry::getRegistry()->addInstance('application', $applicationInstance);
643 * Setter for request instance
645 * @param $requestInstance An instance of a Requestable class
648 public final function setRequestInstance (Requestable $requestInstance) {
649 $this->requestInstance = $requestInstance;
653 * Getter for request instance
655 * @return $requestInstance An instance of a Requestable class
657 public final function getRequestInstance () {
658 return $this->requestInstance;
662 * Setter for response instance
664 * @param $responseInstance An instance of a Responseable class
667 public final function setResponseInstance (Responseable $responseInstance) {
668 $this->responseInstance = $responseInstance;
672 * Getter for response instance
674 * @return $responseInstance An instance of a Responseable class
676 public final function getResponseInstance () {
677 return $this->responseInstance;
681 * Setter for the real class name
683 * @param $realClass Class name (string)
686 public final function setRealClass ($realClass) {
688 $realClass = (string) $realClass;
691 $this->realClass = $realClass;
695 * Checks wether an object equals this object. You should overwrite this
696 * method to implement own equality checks
698 * @param $objectInstance An instance of a FrameworkInterface object
699 * @return $equals Wether both objects equals
701 public function equals (FrameworkInterface $objectInstance) {
704 $this->__toString() == $objectInstance->__toString()
706 $this->hashCode() == $objectInstance->hashCode()
714 * Generates a generic hash code of this class. You should really overwrite
715 * this method with your own hash code generator code. But keep KISS in mind.
717 * @return $hashCode A generic hash code respresenting this whole class
719 public function hashCode () {
721 return crc32($this->__toString());
725 * Formats computer generated price values into human-understandable formats
726 * with thousand and decimal seperators.
728 * @param $value The in computer format value for a price
729 * @param $currency The currency symbol (use HTML-valid characters!)
730 * @param $decNum Number of decimals after commata
731 * @return $price The for the current language formated price string
732 * @throws MissingDecimalsThousandsSeperatorException If decimals or
733 * thousands seperator
736 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
737 // Are all required attriutes set?
738 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
739 // Throw an exception
740 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
744 $value = (float) $value;
746 // Reformat the US number
747 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
749 // Return as string...
754 * Private getter for language instance
756 * @return $langInstance An instance to the language sub-system
758 protected final function getLanguageInstance () {
759 $langInstance = Registry::getRegistry()->getInstance('language');
760 return $langInstance;
764 * Setter for language instance
766 * @param $langInstance An instance to the language sub-system
768 * @see LanguageSystem
770 public final function setLanguageInstance (ManageableLanguage $langInstance) {
771 Registry::getRegistry()->addInstance('language', $langInstance);
775 * Appends a trailing slash to a string
777 * @param $str A string (maybe) without trailing slash
778 * @return $str A string with an auto-appended trailing slash
780 public final function addMissingTrailingSlash ($str) {
781 // Is there a trailing slash?
782 if (substr($str, -1, 1) != '/') {
786 // Return string with trailing slash
791 * Private getter for file IO instance
793 * @return $fileIoInstance An instance to the file I/O sub-system
795 protected final function getFileIoInstance () {
796 return $this->fileIoInstance;
800 * Setter for file I/O instance
802 * @param $fileIoInstance An instance to the file I/O sub-system
805 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
806 $this->fileIoInstance = $fileIoInstance;
810 * Prepare the template engine (WebTemplateEngine by default) for a given
811 * application helper instance (ApplicationHelper by default).
813 * @param $applicationInstance An application helper instance or
814 * null if we shall use the default
815 * @return $templateInstance The template engine instance
816 * @throws NullPointerException If the discovered application
817 * instance is still null
819 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = null) {
820 // Is the application instance set?
821 if (is_null($applicationInstance)) {
822 // Get the current instance
823 $applicationInstance = $this->getApplicationInstance();
826 if (is_null($applicationInstance)) {
827 // Thrown an exception
828 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
832 // Initialize the template engine
833 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
835 // Return the prepared instance
836 return $templateInstance;
840 * Debugs this instance by putting out it's full content
842 * @param $message Optional message to show in debug output
845 public final function debugInstance ($message = '') {
846 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
847 restore_error_handler();
853 if (!empty($message)) {
855 $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
858 // Generate the output
859 $content .= sprintf("<pre>%s</pre>",
868 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>",
871 ClassLoader::getInstance()->getPrintableIncludeList()
876 * Replaces control characters with printable output
878 * @param $str String with control characters
879 * @return $str Replaced string
881 protected function replaceControlCharacters ($str) {
884 "\r", '[r]', str_replace(
885 "\n", '[n]', str_replace(
895 * Output a partial stub message for the caller method
897 * @param $message An optional message to display
900 protected function partialStub ($message = '') {
902 $backtrace = debug_backtrace();
904 // Generate the class::method string
905 $methodName = 'UnknownClass->unknownMethod';
906 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
907 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
910 // Construct the full message
911 $stubMessage = sprintf("[%s:] Partial stub!",
915 // Is the extra message given?
916 if (!empty($message)) {
917 // Then add it as well
918 $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
921 // Debug instance is there?
922 if (!is_null($this->getDebugInstance())) {
923 // Output stub message
924 $this->debugOutput($stubMessage);
927 trigger_error($stubMessage . "<br />\n");
932 * Outputs a debug backtrace and stops further script execution
934 * @param $message An optional message to output
937 public function debugBackTrace ($message = '') {
938 // Sorry, there is no other way getting this nice backtrace
939 if (!empty($message)) {
941 printf("Message: %s<br />\n", $message);
945 debug_print_backtrace();
951 * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
953 * @param $message Message we shall send out...
954 * @param $doPrint Wether we shall print or die here which first is the default
957 public function debugOutput ($message, $doPrint = true) {
958 // Get debug instance
959 $debugInstance = $this->getDebugInstance();
961 // Is the debug instance there?
962 if (is_object($debugInstance)) {
963 // Use debug output handler
964 $debugInstance->output($message);
966 if ($doPrint === false) {
967 // Die here if not printed
972 if ($doPrint === true) {
975 // DO NOT REWRITE THIS TO app_die() !!!
982 * Converts e.g. a command from URL to a valid class by keeping out bad characters
984 * @param $str The string, what ever it is needs to be converted
985 * @return $className Generated class name
987 public function convertToClassName ($str) {
991 // Convert all dashes in underscores
992 $str = $this->convertDashesToUnderscores($str);
994 // Now use that underscores to get classname parts for hungarian style
995 foreach (explode('_', $str) as $strPart) {
996 // Make the class name part lower case and first upper case
997 $className .= ucfirst(strtolower($strPart));
1000 // Return class name
1005 * Converts dashes to underscores, e.g. useable for configuration entries
1007 * @param $str The string with maybe dashes inside
1008 * @return $str The converted string with no dashed, but underscores
1010 public final function convertDashesToUnderscores ($str) {
1012 $str = str_replace('-', '_', $str);
1014 // Return converted string
1019 * Marks up the code by adding e.g. line numbers
1021 * @param $phpCode Unmarked PHP code
1022 * @return $markedCode Marked PHP code
1024 public function markupCode ($phpCode) {
1029 $errorArray = error_get_last();
1031 // Init the code with error message
1032 if (is_array($errorArray)) {
1034 $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>",
1035 basename($errorArray['file']),
1036 $errorArray['line'],
1037 $errorArray['message'],
1042 // Add line number to the code
1043 foreach (explode("\n", $phpCode) as $lineNo => $code) {
1045 $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
1047 htmlentities($code, ENT_QUOTES)
1056 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1057 * beatiful for web-based front-ends. If null is given a message id
1058 * null_timestamp will be resolved and returned.
1060 * @param $timestamp Timestamp to prepare (filter) for display
1061 * @return $readable A readable timestamp
1063 public function doFilterFormatTimestamp ($timestamp) {
1064 // Default value to return
1067 // Is the timestamp null?
1068 if (is_null($timestamp)) {
1069 // Get a message string
1070 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1072 switch ($this->getLanguageInstance()->getLanguageCode()) {
1073 case 'de': // German format is a bit different to default
1074 // Split the GMT stamp up
1075 $dateTime = explode(' ', $timestamp );
1076 $dateArray = explode('-', $dateTime[0]);
1077 $timeArray = explode(':', $dateTime[1]);
1079 // Construct the timestamp
1080 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1090 default: // Default is pass-through
1091 $readable = $timestamp;
1101 * Filter a given number into a localized number
1103 * @param $value The raw value from e.g. database
1104 * @return $localized Localized value
1106 public function doFilterFormatNumber ($value) {
1107 // Generate it from config and localize dependencies
1108 switch ($this->getLanguageInstance()->getLanguageCode()) {
1109 case 'de': // German format is a bit different to default
1110 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1113 default: // US, etc.
1114 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1123 * "Getter" for databse entry
1125 * @return $entry An array with database entries
1126 * @throws NullPointerException If the database result is not found
1127 * @throws InvalidDatabaseResultException If the database result is invalid
1129 protected final function getDatabaseEntry () {
1130 // Is there an instance?
1131 if (is_null($this->getResultInstance())) {
1132 // Throw an exception here
1133 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1137 $this->getResultInstance()->rewind();
1139 // Do we have an entry?
1140 if ($this->getResultInstance()->valid() === false) {
1141 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1145 $this->getResultInstance()->next();
1148 $entry = $this->getResultInstance()->current();
1155 * Getter for field name
1157 * @param $fieldName Field name which we shall get
1158 * @return $fieldValue Field value from the user
1159 * @throws NullPointerException If the result instance is null
1161 public final function getField ($fieldName) {
1162 // Default field value
1165 // Get result instance
1166 $resultInstance = $this->getResultInstance();
1168 // Is this instance null?
1169 if (is_null($resultInstance)) {
1170 // Then the user instance is no longer valid (expired cookies?)
1171 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1174 // Get current array
1175 $fieldArray = $resultInstance->current();
1176 //* DEBUG: */ $this->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1178 // Does the field exist?
1179 if (isset($fieldArray[$fieldName])) {
1181 $fieldValue = $fieldArray[$fieldName];
1189 * Protected setter for user instance
1191 * @param $userInstance An instance of a user class
1194 protected final function setUserInstance (ManageableAccount $userInstance) {
1195 $this->userInstance = $userInstance;
1199 * Getter for user instance
1201 * @return $userInstance An instance of a user class
1203 public final function getUserInstance () {
1204 return $this->userInstance;
1208 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1210 * @param $controllerInstance An instance of the controller
1213 public final function setControllerInstance (Controller $controllerInstance) {
1214 $this->controllerInstance = $controllerInstance;
1218 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1220 * @return $controllerInstance An instance of the controller
1222 public final function getControllerInstance () {
1223 return $this->controllerInstance;
1227 * Flushs all pending updates to the database layer
1231 public function flushPendingUpdates () {
1232 // Get result instance
1233 $resultInstance = $this->getResultInstance();
1235 // Do we have data to update?
1236 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1237 // Get wrapper class name config entry
1238 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1240 // Create object instance
1241 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1243 // Yes, then send the whole result to the database layer
1244 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1249 * Outputs a deprecation warning to the developer.
1251 * @param $message The message we shall output to the developer
1253 * @todo Write a logging mechanism for productive mode
1255 public function deprecationWarning ($message) {
1256 // Is developer mode active?
1257 if (defined('DEVELOPER')) {
1258 // Debug instance is there?
1259 if (!is_null($this->getDebugInstance())) {
1260 // Output stub message
1261 $this->debugOutput($message);
1264 trigger_error($message . "<br />\n");
1267 // @TODO Finish this part!
1268 $this->partialStub('Developer mode inactive. Message:' . $message);
1273 * Checks wether the given PHP extension is loaded
1275 * @param $phpExtension The PHP extension we shall check
1276 * @return $isLoaded Wether the PHP extension is loaded
1278 public final function isPhpExtensionLoaded ($phpExtension) {
1280 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1287 * Setter for RNG instance
1289 * @param $rngInstance An instance of a random number generator (RNG)
1292 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1293 $this->rngInstance = $rngInstance;
1297 * Getter for RNG instance
1299 * @return $rngInstance An instance of a random number generator (RNG)
1301 public final function getRngInstance () {
1302 return $this->rngInstance;
1306 * Setter for Cryptable instance
1308 * @param $cryptoInstance An instance of a Cryptable class
1311 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1312 $this->cryptoInstance = $cryptoInstance;
1316 * Getter for Cryptable instance
1318 * @return $cryptoInstance An instance of a Cryptable class
1320 public final function getCryptoInstance () {
1321 return $this->cryptoInstance;
1325 * Setter for Iterator instance
1327 * @param $iteratorInstance An instance of an Iterator
1330 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1331 $this->iteratorInstance = $iteratorInstance;
1335 * Getter for Iterator instance
1337 * @return $iteratorInstance An instance of an Iterator
1339 public final function getIteratorInstance () {
1340 return $this->iteratorInstance;
1344 * "Getter" as a time() replacement but with milliseconds. You should use this
1345 * method instead of the encapsulated getimeofday() function.
1347 * @return $milliTime Timestamp with milliseconds
1349 public function getMilliTime () {
1350 // Get the time of day as float
1351 $milliTime = gettimeofday(true);
1358 * Idles (sleeps) for given milliseconds
1360 * @return $hasSlept Wether it goes fine
1362 public function idle ($milliSeconds) {
1363 // Sleep is fine by default
1366 // Idle so long with found function
1367 if (function_exists('time_sleep_until')) {
1368 // Get current time and add idle time
1369 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1371 // New PHP 5.1.0 function found
1372 $hasSlept = time_sleep_until($sleepUntil);
1374 // My Sun Station doesn't have that function even with latest PHP
1376 usleep($milliSeconds * 1000);
1384 * Setter for the list instance
1386 * @param $listInstance A list of Listable
1389 protected final function setListInstance (Listable $listInstance) {
1390 $this->listInstance = $listInstance;
1394 * Getter for the list instance
1396 * @return $listInstance A list of Listable
1398 protected final function getListInstance () {
1399 return $this->listInstance;
1403 * Setter for the menu instance
1405 * @param $menuInstance A RenderableMenu instance
1408 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1409 $this->menuInstance = $menuInstance;
1413 * Getter for the menu instance
1415 * @return $menuInstance A RenderableMenu instance
1417 protected final function getMenuInstance () {
1418 return $this->menuInstance;
1422 * Setter for image instance
1424 * @param $imageInstance An instance of an image
1427 public final function setImageInstance (BaseImage $imageInstance) {
1428 $this->imageInstance = $imageInstance;
1432 * Getter for image instance
1434 * @return $imageInstance An instance of an image
1436 public final function getImageInstance () {
1437 return $this->imageInstance;
1441 * Setter for stacker instance
1443 * @param $stackerInstance An instance of an stacker
1446 public final function setStackerInstance (Stackable $stackerInstance) {
1447 $this->stackerInstance = $stackerInstance;
1451 * Getter for stacker instance
1453 * @return $stackerInstance An instance of an stacker
1455 public final function getStackerInstance () {
1456 return $this->stackerInstance;
1460 * Setter for compressor instance
1462 * @param $compressorInstance An instance of an compressor
1465 public final function setCompressorInstance (Compressor $compressorInstance) {
1466 $this->compressorInstance = $compressorInstance;
1470 * Getter for compressor instance
1472 * @return $compressorInstance An instance of an compressor
1474 public final function getCompressorInstance () {
1475 return $this->compressorInstance;
1479 * Setter for Parseable instance
1481 * @param $parserInstance An instance of an Parseable
1484 public final function setParserInstance (Parseable $parserInstance) {
1485 $this->parserInstance = $parserInstance;
1489 * Getter for Parseable instance
1491 * @return $parserInstance An instance of an Parseable
1493 public final function getParserInstance () {
1494 return $this->parserInstance;
1498 * Setter for ProtocolHandler instance
1500 * @param $protocolInstance An instance of an ProtocolHandler
1503 public final function setProtocolInstance (ProtocolHandler $protocolInstance) {
1504 $this->protocolInstance = $protocolInstance;
1508 * Getter for ProtocolHandler instance
1510 * @return $protocolInstance An instance of an ProtocolHandler
1512 public final function getProtocolInstance () {
1513 return $this->protocolInstance;
1517 * Setter for BaseDatabaseWrapper instance
1519 * @param $wrapperInstance An instance of an BaseDatabaseWrapper
1522 public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
1523 $this->wrapperInstance = $wrapperInstance;
1527 * Getter for BaseDatabaseWrapper instance
1529 * @return $wrapperInstance An instance of an BaseDatabaseWrapper
1531 public final function getWrapperInstance () {
1532 return $this->wrapperInstance;
1536 * Setter for socket resource
1538 * @param $socketResource A valid socket resource
1541 public final function setSocketResource ($socketResource) {
1542 $this->socketResource = $socketResource;
1546 * Getter for socket resource
1548 * @return $socketResource A valid socket resource
1550 public function getSocketResource () {
1551 return $this->socketResource;
1555 * Setter for helper instance
1557 * @param $helperInstance An instance of a helper class
1560 protected final function setHelperInstance (Helper $helperInstance) {
1561 $this->helperInstance = $helperInstance;
1565 * Getter for helper instance
1567 * @return $helperInstance An instance of a helper class
1569 public final function getHelperInstance () {
1570 return $this->helperInstance;
1574 * Setter for a Sourceable instance
1576 * @param $sourceInstance The Sourceable instance
1579 protected final function setSourceInstance (Sourceable $sourceInstance) {
1580 $this->sourceInstance = $sourceInstance;
1584 * Getter for a InputStreamable instance
1586 * @param $inputStreamInstance The InputStreamable instance
1588 protected final function getInputStreamInstance () {
1589 return $this->inputStreamInstance;
1593 * Setter for a InputStreamable instance
1595 * @param $inputStreamInstance The InputStreamable instance
1598 protected final function setInputStreamInstance (InputStreamable $inputStreamInstance) {
1599 $this->inputStreamInstance = $inputStreamInstance;
1603 * Getter for a OutputStreamable instance
1605 * @param $outputStreamInstance The OutputStreamable instance
1607 protected final function getOutputStreamInstance () {
1608 return $this->outputStreamInstance;
1612 * Setter for a OutputStreamable instance
1614 * @param $outputStreamInstance The OutputStreamable instance
1617 protected final function setOutputStreamInstance (OutputStreamable $outputStreamInstance) {
1618 $this->outputStreamInstance = $outputStreamInstance;
1622 * Setter for raw package Data
1624 * @param $packageData Raw package Data
1627 public final function setPackageData (array $packageData) {
1628 $this->packageData = $packageData;
1632 * Getter for raw package Data
1634 * @return $packageData Raw package Data
1636 public function getPackageData () {
1637 return $this->packageData;
1641 * Converts a hexadecimal string, even with negative sign as first string to
1642 * a decimal number using BC functions.
1644 * This work is based on comment #86673 on php.net documentation page at:
1645 * <http://de.php.net/manual/en/function.dechex.php#86673>
1647 * @param $hex Hexadecimal string
1648 * @return $dec Decimal number
1650 protected function hex2dec ($hex) {
1651 // Convert to all lower-case
1652 $hex = strtolower($hex);
1654 // Detect sign (negative/positive numbers)
1656 if (substr($hex, 0, 1) == '-') {
1658 $hex = substr($hex, 1);
1661 // Decode the hexadecimal string into a decimal number
1663 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1664 $factor = self::$hexdec[substr($hex, $i, 1)];
1665 $dec = bcadd($dec, bcmul($factor, $e));
1668 // Return the decimal number
1669 return $sign . $dec;
1673 * Converts even very large decimal numbers, also with negative sign, to a
1674 * hexadecimal string.
1676 * This work is based on comment #97756 on php.net documentation page at:
1677 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1679 * @param $dec Decimal number, even with negative sign
1680 * @param $maxLength Optional maximum length of the string
1681 * @return $hex Hexadecimal string
1683 protected function dec2hex ($dec, $maxLength = 0) {
1684 // maxLength can be zero or devideable by 2
1685 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1687 // Detect sign (negative/positive numbers)
1694 // Encode the decimal number into a hexadecimal string
1697 $hex = self::$dechex[($dec % 16)] . $hex;
1699 } while ($dec >= 1);
1702 * We need hexadecimal strings with leading zeros if the length cannot
1705 if ($maxLength > 0) {
1706 // Prepend more zeros
1707 $hex = $this->prependStringToString($hex, '0', $maxLength);
1708 } elseif ((strlen($hex) % 2) != 0) {
1712 // Return the hexadecimal string
1713 return $sign . $hex;
1717 * Converts a ASCII string (0 to 255) into a decimal number.
1719 * @param $asc The ASCII string to be converted
1720 * @return $dec Decimal number
1722 protected function asc2dec ($asc) {
1723 // Convert it into a hexadecimal number
1724 $hex = bin2hex($asc);
1726 // And back into a decimal number
1727 $dec = $this->hex2dec($hex);
1734 * Converts a decimal number into an ASCII string.
1736 * @param $dec Decimal number
1737 * @return $asc An ASCII string
1739 protected function dec2asc ($dec) {
1740 // First convert the number into a hexadecimal string
1741 $hex = $this->dec2hex($dec);
1743 // Then convert it into the ASCII string
1744 $asc = $this->hex2asc($hex);
1751 * Converts a hexadecimal number into an ASCII string. Negative numbers
1754 * @param $hex Hexadecimal string
1755 * @return $asc An ASCII string
1757 protected function hex2asc ($hex) {
1758 // Check for length, it must be devideable by 2
1759 //* DEBUG: */ $this->debugOutput('hex='.$hex);
1760 assert((strlen($hex) % 2) == 0);
1764 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
1765 // Get the decimal number of the chunk
1766 $part = hexdec(substr($hex, $idx, 2));
1768 // Add it to the final string
1772 // Return the final string
1777 * Prepends a given string $prepend to $str with a given total length
1779 * @param $str Given original string which should be prepended
1780 * @param $prepend The string to prepend
1781 * @param $length Total length of the final string
1782 * @return $strFinal Final prepended string
1784 protected function prependStringToString ($str, $prepend, $length) {
1785 // Set final string to original string by default
1789 if (strlen($str) < $length) {
1790 // Difference between total length and length of original string
1791 $diff = $length - strlen($str);
1793 // Prepend the string
1794 $prepend = str_repeat($prepend, ($diff / strlen($prepend) + 1));
1796 // Make sure it will definedly fit
1797 assert(strlen($prepend) >= $diff);
1799 // Cut it a little down
1800 $prepend = substr($prepend, 0, $diff);
1801 //* DEBUG: */ $this->debugOutput('prepend('.strlen($prepend).')='.$prepend.',diff='.$diff.',length='.$length);
1803 // Construct the final prepended string
1804 $strFinal = $prepend . $str;
1812 * Checks wether the given encoded data was encoded with Base64
1814 * @param $encodedData Encoded data we shall check
1815 * @return $isBase64 Wether the encoded data is Base64
1817 protected function isBase64Encoded ($encodedData) {
1819 $isBase64 = (@base64_decode($encodedData, true) !== false);