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 * Thousands seperator
159 private $thousands = '.'; // German
164 private $decimals = ','; // German
169 private $socketResource = false;
174 private $packageData = array();
176 /***********************
177 * Exception codes.... *
178 ***********************/
180 // @todo Try to clean these constants up
181 const EXCEPTION_IS_NULL_POINTER = 0x001;
182 const EXCEPTION_IS_NO_OBJECT = 0x002;
183 const EXCEPTION_IS_NO_ARRAY = 0x003;
184 const EXCEPTION_MISSING_METHOD = 0x004;
185 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
186 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
187 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
188 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
189 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
190 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
191 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
192 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
193 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
194 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
195 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
196 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
197 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
198 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
199 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
200 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
201 const EXCEPTION_PATH_NOT_FOUND = 0x015;
202 const EXCEPTION_INVALID_PATH_NAME = 0x016;
203 const EXCEPTION_READ_PROTECED_PATH = 0x017;
204 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
205 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
206 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
207 const EXCEPTION_INVALID_RESOURCE = 0x01b;
208 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
209 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
210 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
211 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
212 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
213 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
214 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
215 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
216 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
217 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
218 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
219 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
220 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
221 const EXCEPTION_INVALID_STRING = 0x029;
222 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
223 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
224 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
225 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
226 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
227 const EXCEPTION_MISSING_ELEMENT = 0x030;
228 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
229 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
230 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
231 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
232 const EXCEPTION_FATAL_ERROR = 0x035;
233 const EXCEPTION_FILE_NOT_FOUND = 0x036;
234 const EXCEPTION_ASSERTION_FAILED = 0x037;
235 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
236 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
237 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x040;
239 // Hexadecimal->Decimal translation array
240 private static $hexdec = array(
259 // Decimal->hexadecimal translation array
260 private static $dechex = array(
280 * Protected super constructor
282 * @param $className Name of the class
285 protected function __construct ($className) {
287 $this->setRealClass($className);
289 // Set configuration instance if no registry ...
290 if (!$this instanceof Register) {
291 // ... because registries doesn't need to be configured
292 $this->setConfigInstance(FrameworkConfiguration::getInstance());
297 * Destructor reached...
301 public function __destruct() {
302 // Flush any updated entries to the database
303 $this->flushPendingUpdates();
305 // Is this object already destroyed?
306 if ($this->__toString() != 'DestructedObject') {
307 // Destroy all informations about this class but keep some text about it alive
308 $this->setRealClass('DestructedObject');
309 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
310 // Already destructed object
311 $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
319 * The __call() method where all non-implemented methods end up
321 * @param $methodName Name of the missing method
322 * @args $args Arguments passed to the method
325 public final function __call ($methodName, $args) {
326 // Implode all given arguments
330 $argsString = 'NULL';
331 } elseif (is_array($args)) {
332 // Some arguments are there
333 foreach ($args as $arg) {
335 $argsString .= $this->replaceControlCharacters($arg) . ' (' . gettype($arg);
337 // Add length if type is string
338 if (is_string($arg)) {
339 $argsString .= ', '.strlen($arg);
343 $argsString .= '), ';
347 if (substr($argsString, -2, 1) == ',') {
348 $argsString = substr($argsString, 0, -2);
351 // Invalid arguments!
352 $argsString = '!INVALID:' . gettype($args) . '!';
355 // Output stub message
356 $this->debugOutput(sprintf("[%s->%s] Stub! Args: %s",
367 * Getter for $realClass
369 * @return $realClass The name of the real class (not BaseFrameworkSystem)
371 public function __toString () {
372 return $this->realClass;
376 * Magic function to catch setting of missing but set class fields/attributes
378 * @param $name Name of the field/attribute
379 * @param $value Value to store
382 public final function __set ($name, $value) {
383 $this->debugBackTrace(sprintf("Tried to set a missing field. name=%s, value[%s]=%s",
391 * Magic function to catch getting of missing fields/attributes
393 * @param $name Name of the field/attribute
396 public final function __get ($name) {
397 $this->debugBackTrace(sprintf("Tried to get a missing field. name=%s",
403 * Magic function to catch unsetting of missing fields/attributes
405 * @param $name Name of the field/attribute
408 public final function __unset ($name) {
409 $this->debugBackTrace(sprintf("Tried to unset a missing field. name=%s",
415 * Setter for database result instance
417 * @param $resultInstance An instance of a database result class
419 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
421 protected final function setResultInstance (SearchableResult $resultInstance) {
422 $this->resultInstance = $resultInstance;
426 * Getter for database result instance
428 * @return $resultInstance An instance of a database result class
430 public final function getResultInstance () {
431 return $this->resultInstance;
435 * Setter for template engine instances
437 * @param $templateInstance An instance of a template engine class
440 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
441 $this->templateInstance = $templateInstance;
445 * Getter for template engine instances
447 * @return $templateInstance An instance of a template engine class
449 protected final function getTemplateInstance () {
450 return $this->templateInstance;
454 * Setter for search instance
456 * @param $searchInstance Searchable criteria instance
459 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
460 $this->searchInstance = $searchInstance;
464 * Getter for search instance
466 * @return $searchInstance Searchable criteria instance
468 public final function getSearchInstance () {
469 return $this->searchInstance;
473 * Setter for update instance
475 * @param $updateInstance Searchable criteria instance
478 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
479 $this->updateInstance = $updateInstance;
483 * Getter for update instance
485 * @return $updateInstance Updateable criteria instance
487 public final function getUpdateInstance () {
488 return $this->updateInstance;
492 * Setter for resolver instance
494 * @param $resolverInstance Instance of a command resolver class
497 public final function setResolverInstance (Resolver $resolverInstance) {
498 $this->resolverInstance = $resolverInstance;
502 * Getter for resolver instance
504 * @return $resolverInstance Instance of a command resolver class
506 public final function getResolverInstance () {
507 return $this->resolverInstance;
511 * Setter for language instance
513 * @param $configInstance The configuration instance which shall
514 * be FrameworkConfiguration
517 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
518 Registry::getRegistry()->addInstance('config', $configInstance);
522 * Getter for configuration instance
524 * @return $configInstance Configuration instance
526 public final function getConfigInstance () {
527 $configInstance = Registry::getRegistry()->getInstance('config');
528 return $configInstance;
532 * Setter for debug instance
534 * @param $debugInstance The instance for debug output class
537 public final function setDebugInstance (DebugMiddleware $debugInstance) {
538 Registry::getRegistry()->addInstance('debug', $debugInstance);
542 * Getter for debug instance
544 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
546 public final function getDebugInstance () {
547 // Get debug instance
548 $debugInstance = Registry::getRegistry()->getInstance('debug');
551 return $debugInstance;
555 * Setter for web output instance
557 * @param $webInstance The instance for web output class
560 public final function setWebOutputInstance (OutputStreamer $webInstance) {
561 Registry::getRegistry()->addInstance('web_output', $webInstance);
565 * Getter for web output instance
567 * @return $webOutputInstance - Instance to class WebOutput
569 public final function getWebOutputInstance () {
570 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
571 return $webOutputInstance;
575 * Setter for database instance
577 * @param $dbInstance The instance for the database connection (forced DatabaseConnection)
580 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
581 Registry::getRegistry()->addInstance('db_instance', $dbInstance);
585 * Getter for database layer
587 * @return $dbInstance The database layer instance
589 public final function getDatabaseInstance () {
591 $dbInstance = Registry::getRegistry()->getInstance('db_instance');
598 * Setter for compressor channel
600 * @param $compressorInstance An instance of CompressorChannel
603 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
604 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
608 * Getter for compressor channel
610 * @return $compressorInstance The compressor channel
612 public final function getCompressorChannel () {
613 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
614 return $compressorInstance;
618 * Protected getter for a manageable application helper class
620 * @return $applicationInstance An instance of a manageable application helper class
622 protected final function getApplicationInstance () {
623 $applicationInstance = Registry::getRegistry()->getInstance('application');
624 return $applicationInstance;
628 * Setter for a manageable application helper class
630 * @param $applicationInstance An instance of a manageable application helper class
633 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
634 Registry::getRegistry()->addInstance('application', $applicationInstance);
638 * Setter for request instance
640 * @param $requestInstance An instance of a Requestable class
643 public final function setRequestInstance (Requestable $requestInstance) {
644 $this->requestInstance = $requestInstance;
648 * Getter for request instance
650 * @return $requestInstance An instance of a Requestable class
652 public final function getRequestInstance () {
653 return $this->requestInstance;
657 * Setter for response instance
659 * @param $responseInstance An instance of a Responseable class
662 public final function setResponseInstance (Responseable $responseInstance) {
663 $this->responseInstance = $responseInstance;
667 * Getter for response instance
669 * @return $responseInstance An instance of a Responseable class
671 public final function getResponseInstance () {
672 return $this->responseInstance;
676 * Setter for the real class name
678 * @param $realClass Class name (string)
681 public final function setRealClass ($realClass) {
683 $realClass = (string) $realClass;
686 $this->realClass = $realClass;
690 * Checks wether an object equals this object. You should overwrite this
691 * method to implement own equality checks
693 * @param $objectInstance An instance of a FrameworkInterface object
694 * @return $equals Wether both objects equals
696 public function equals (FrameworkInterface $objectInstance) {
699 $this->__toString() == $objectInstance->__toString()
701 $this->hashCode() == $objectInstance->hashCode()
709 * Generates a generic hash code of this class. You should really overwrite
710 * this method with your own hash code generator code. But keep KISS in mind.
712 * @return $hashCode A generic hash code respresenting this whole class
714 public function hashCode () {
716 return crc32($this->__toString());
720 * Formats computer generated price values into human-understandable formats
721 * with thousand and decimal seperators.
723 * @param $value The in computer format value for a price
724 * @param $currency The currency symbol (use HTML-valid characters!)
725 * @param $decNum Number of decimals after commata
726 * @return $price The for the current language formated price string
727 * @throws MissingDecimalsThousandsSeperatorException If decimals or
728 * thousands seperator
731 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
732 // Are all required attriutes set?
733 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
734 // Throw an exception
735 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
739 $value = (float) $value;
741 // Reformat the US number
742 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
744 // Return as string...
749 * Private getter for language instance
751 * @return $langInstance An instance to the language sub-system
753 protected final function getLanguageInstance () {
754 $langInstance = Registry::getRegistry()->getInstance('language');
755 return $langInstance;
759 * Setter for language instance
761 * @param $langInstance An instance to the language sub-system
763 * @see LanguageSystem
765 public final function setLanguageInstance (ManageableLanguage $langInstance) {
766 Registry::getRegistry()->addInstance('language', $langInstance);
770 * Appends a trailing slash to a string
772 * @param $str A string (maybe) without trailing slash
773 * @return $str A string with an auto-appended trailing slash
775 public final function addMissingTrailingSlash ($str) {
776 // Is there a trailing slash?
777 if (substr($str, -1, 1) != '/') {
781 // Return string with trailing slash
786 * Private getter for file IO instance
788 * @return $fileIoInstance An instance to the file I/O sub-system
790 protected final function getFileIoInstance () {
791 return $this->fileIoInstance;
795 * Setter for file I/O instance
797 * @param $fileIoInstance An instance to the file I/O sub-system
800 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
801 $this->fileIoInstance = $fileIoInstance;
805 * Prepare the template engine (WebTemplateEngine by default) for a given
806 * application helper instance (ApplicationHelper by default).
808 * @param $applicationInstance An application helper instance or
809 * null if we shall use the default
810 * @return $templateInstance The template engine instance
811 * @throws NullPointerException If the discovered application
812 * instance is still null
814 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = null) {
815 // Is the application instance set?
816 if (is_null($applicationInstance)) {
817 // Get the current instance
818 $applicationInstance = $this->getApplicationInstance();
821 if (is_null($applicationInstance)) {
822 // Thrown an exception
823 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
827 // Initialize the template engine
828 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
830 // Return the prepared instance
831 return $templateInstance;
835 * Debugs this instance by putting out it's full content
837 * @param $message Optional message to show in debug output
840 public final function debugInstance ($message = '') {
841 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
842 restore_error_handler();
848 if (!empty($message)) {
850 $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
853 // Generate the output
854 $content .= sprintf("<pre>%s</pre>",
863 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>",
866 ClassLoader::getInstance()->getPrintableIncludeList()
871 * Replaces control characters with printable output
873 * @param $str String with control characters
874 * @return $str Replaced string
876 protected function replaceControlCharacters ($str) {
879 "\r", '[r]', str_replace(
880 "\n", '[n]', str_replace(
890 * Output a partial stub message for the caller method
892 * @param $message An optional message to display
895 protected function partialStub ($message = '') {
897 $backtrace = debug_backtrace();
899 // Generate the class::method string
900 $methodName = 'UnknownClass->unknownMethod';
901 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
902 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
905 // Construct the full message
906 $stubMessage = sprintf("[%s:] Partial stub!",
910 // Is the extra message given?
911 if (!empty($message)) {
912 // Then add it as well
913 $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
916 // Debug instance is there?
917 if (!is_null($this->getDebugInstance())) {
918 // Output stub message
919 $this->debugOutput($stubMessage);
922 trigger_error($stubMessage . "<br />\n");
927 * Outputs a debug backtrace and stops further script execution
929 * @param $message An optional message to output
932 public function debugBackTrace ($message = '') {
933 // Sorry, there is no other way getting this nice backtrace
934 if (!empty($message)) {
936 printf("Message: %s<br />\n", $message);
940 debug_print_backtrace();
946 * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
948 * @param $message Message we shall send out...
949 * @param $doPrint Wether we shall print or die here which first is the default
952 public function debugOutput ($message, $doPrint = true) {
953 // Get debug instance
954 $debugInstance = $this->getDebugInstance();
956 // Is the debug instance there?
957 if (is_object($debugInstance)) {
958 // Use debug output handler
959 $debugInstance->output($message);
961 if ($doPrint === false) {
962 // Die here if not printed
967 if ($doPrint === true) {
970 // DO NOT REWRITE THIS TO app_die() !!!
977 * Converts e.g. a command from URL to a valid class by keeping out bad characters
979 * @param $str The string, what ever it is needs to be converted
980 * @return $className Generated class name
982 public function convertToClassName ($str) {
986 // Convert all dashes in underscores
987 $str = $this->convertDashesToUnderscores($str);
989 // Now use that underscores to get classname parts for hungarian style
990 foreach (explode('_', $str) as $strPart) {
991 // Make the class name part lower case and first upper case
992 $className .= ucfirst(strtolower($strPart));
1000 * Converts dashes to underscores, e.g. useable for configuration entries
1002 * @param $str The string with maybe dashes inside
1003 * @return $str The converted string with no dashed, but underscores
1005 public final function convertDashesToUnderscores ($str) {
1007 $str = str_replace('-', '_', $str);
1009 // Return converted string
1014 * Marks up the code by adding e.g. line numbers
1016 * @param $phpCode Unmarked PHP code
1017 * @return $markedCode Marked PHP code
1019 public function markupCode ($phpCode) {
1024 $errorArray = error_get_last();
1026 // Init the code with error message
1027 if (is_array($errorArray)) {
1029 $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>",
1030 basename($errorArray['file']),
1031 $errorArray['line'],
1032 $errorArray['message'],
1037 // Add line number to the code
1038 foreach (explode("\n", $phpCode) as $lineNo => $code) {
1040 $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
1042 htmlentities($code, ENT_QUOTES)
1051 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1052 * beatiful for web-based front-ends. If null is given a message id
1053 * null_timestamp will be resolved and returned.
1055 * @param $timestamp Timestamp to prepare (filter) for display
1056 * @return $readable A readable timestamp
1058 public function doFilterFormatTimestamp ($timestamp) {
1059 // Default value to return
1062 // Is the timestamp null?
1063 if (is_null($timestamp)) {
1064 // Get a message string
1065 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1067 switch ($this->getLanguageInstance()->getLanguageCode()) {
1068 case 'de': // German format is a bit different to default
1069 // Split the GMT stamp up
1070 $dateTime = explode(' ', $timestamp );
1071 $dateArray = explode('-', $dateTime[0]);
1072 $timeArray = explode(':', $dateTime[1]);
1074 // Construct the timestamp
1075 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1085 default: // Default is pass-through
1086 $readable = $timestamp;
1096 * Filter a given number into a localized number
1098 * @param $value The raw value from e.g. database
1099 * @return $localized Localized value
1101 public function doFilterFormatNumber ($value) {
1102 // Generate it from config and localize dependencies
1103 switch ($this->getLanguageInstance()->getLanguageCode()) {
1104 case 'de': // German format is a bit different to default
1105 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1108 default: // US, etc.
1109 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1118 * "Getter" for databse entry
1120 * @return $entry An array with database entries
1121 * @throws NullPointerException If the database result is not found
1122 * @throws InvalidDatabaseResultException If the database result is invalid
1124 protected final function getDatabaseEntry () {
1125 // Is there an instance?
1126 if (is_null($this->getResultInstance())) {
1127 // Throw an exception here
1128 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1132 $this->getResultInstance()->rewind();
1134 // Do we have an entry?
1135 if ($this->getResultInstance()->valid() === false) {
1136 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1140 $this->getResultInstance()->next();
1143 $entry = $this->getResultInstance()->current();
1150 * Getter for field name
1152 * @param $fieldName Field name which we shall get
1153 * @return $fieldValue Field value from the user
1154 * @throws NullPointerException If the result instance is null
1156 public final function getField ($fieldName) {
1157 // Default field value
1160 // Get result instance
1161 $resultInstance = $this->getResultInstance();
1163 // Is this instance null?
1164 if (is_null($resultInstance)) {
1165 // Then the user instance is no longer valid (expired cookies?)
1166 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1169 // Get current array
1170 $fieldArray = $resultInstance->current();
1171 //* DEBUG: */ $this->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1173 // Does the field exist?
1174 if (isset($fieldArray[$fieldName])) {
1176 $fieldValue = $fieldArray[$fieldName];
1184 * Protected setter for user instance
1186 * @param $userInstance An instance of a user class
1189 protected final function setUserInstance (ManageableAccount $userInstance) {
1190 $this->userInstance = $userInstance;
1194 * Getter for user instance
1196 * @return $userInstance An instance of a user class
1198 public final function getUserInstance () {
1199 return $this->userInstance;
1203 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1205 * @param $controllerInstance An instance of the controller
1208 public final function setControllerInstance (Controller $controllerInstance) {
1209 $this->controllerInstance = $controllerInstance;
1213 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1215 * @return $controllerInstance An instance of the controller
1217 public final function getControllerInstance () {
1218 return $this->controllerInstance;
1222 * Flushs all pending updates to the database layer
1226 public function flushPendingUpdates () {
1227 // Get result instance
1228 $resultInstance = $this->getResultInstance();
1230 // Do we have data to update?
1231 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1232 // Get wrapper class name config entry
1233 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1235 // Create object instance
1236 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1238 // Yes, then send the whole result to the database layer
1239 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1244 * Outputs a deprecation warning to the developer.
1246 * @param $message The message we shall output to the developer
1248 * @todo Write a logging mechanism for productive mode
1250 public function deprecationWarning ($message) {
1251 // Is developer mode active?
1252 if (defined('DEVELOPER')) {
1253 // Debug instance is there?
1254 if (!is_null($this->getDebugInstance())) {
1255 // Output stub message
1256 $this->debugOutput($message);
1259 trigger_error($message . "<br />\n");
1262 // @TODO Finish this part!
1263 $this->partialStub('Developer mode inactive. Message:' . $message);
1268 * Checks wether the given PHP extension is loaded
1270 * @param $phpExtension The PHP extension we shall check
1271 * @return $isLoaded Wether the PHP extension is loaded
1273 public final function isPhpExtensionLoaded ($phpExtension) {
1275 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1282 * Setter for RNG instance
1284 * @param $rngInstance An instance of a random number generator (RNG)
1287 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1288 $this->rngInstance = $rngInstance;
1292 * Getter for RNG instance
1294 * @return $rngInstance An instance of a random number generator (RNG)
1296 public final function getRngInstance () {
1297 return $this->rngInstance;
1301 * Setter for Cryptable instance
1303 * @param $cryptoInstance An instance of a Cryptable class
1306 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1307 $this->cryptoInstance = $cryptoInstance;
1311 * Getter for Cryptable instance
1313 * @return $cryptoInstance An instance of a Cryptable class
1315 public final function getCryptoInstance () {
1316 return $this->cryptoInstance;
1320 * Setter for Iterator instance
1322 * @param $iteratorInstance An instance of an Iterator
1325 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1326 $this->iteratorInstance = $iteratorInstance;
1330 * Getter for Iterator instance
1332 * @return $iteratorInstance An instance of an Iterator
1334 public final function getIteratorInstance () {
1335 return $this->iteratorInstance;
1339 * "Getter" as a time() replacement but with milliseconds. You should use this
1340 * method instead of the encapsulated getimeofday() function.
1342 * @return $milliTime Timestamp with milliseconds
1344 public function getMilliTime () {
1345 // Get the time of day as float
1346 $milliTime = gettimeofday(true);
1353 * Idles (sleeps) for given milliseconds
1355 * @return $hasSlept Wether it goes fine
1357 public function idle ($milliSeconds) {
1358 // Sleep is fine by default
1361 // Idle so long with found function
1362 if (function_exists('time_sleep_until')) {
1363 // Get current time and add idle time
1364 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1366 // New PHP 5.1.0 function found
1367 $hasSlept = time_sleep_until($sleepUntil);
1369 // My Sun Station doesn't have that function even with latest PHP
1371 usleep($milliSeconds * 1000);
1379 * Setter for the list instance
1381 * @param $listInstance A list of Listable
1384 protected final function setListInstance (Listable $listInstance) {
1385 $this->listInstance = $listInstance;
1389 * Getter for the list instance
1391 * @return $listInstance A list of Listable
1393 protected final function getListInstance () {
1394 return $this->listInstance;
1398 * Setter for the menu instance
1400 * @param $menuInstance A RenderableMenu instance
1403 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1404 $this->menuInstance = $menuInstance;
1408 * Getter for the menu instance
1410 * @return $menuInstance A RenderableMenu instance
1412 protected final function getMenuInstance () {
1413 return $this->menuInstance;
1417 * Setter for image instance
1419 * @param $imageInstance An instance of an image
1422 public final function setImageInstance (BaseImage $imageInstance) {
1423 $this->imageInstance = $imageInstance;
1427 * Getter for image instance
1429 * @return $imageInstance An instance of an image
1431 public final function getImageInstance () {
1432 return $this->imageInstance;
1436 * Setter for stacker instance
1438 * @param $stackerInstance An instance of an stacker
1441 public final function setStackerInstance (Stackable $stackerInstance) {
1442 $this->stackerInstance = $stackerInstance;
1446 * Getter for stacker instance
1448 * @return $stackerInstance An instance of an stacker
1450 public final function getStackerInstance () {
1451 return $this->stackerInstance;
1455 * Setter for compressor instance
1457 * @param $compressorInstance An instance of an compressor
1460 public final function setCompressorInstance (Compressor $compressorInstance) {
1461 $this->compressorInstance = $compressorInstance;
1465 * Getter for compressor instance
1467 * @return $compressorInstance An instance of an compressor
1469 public final function getCompressorInstance () {
1470 return $this->compressorInstance;
1474 * Setter for Parseable instance
1476 * @param $parserInstance An instance of an Parseable
1479 public final function setParserInstance (Parseable $parserInstance) {
1480 $this->parserInstance = $parserInstance;
1484 * Getter for Parseable instance
1486 * @return $parserInstance An instance of an Parseable
1488 public final function getParserInstance () {
1489 return $this->parserInstance;
1493 * Setter for ProtocolHandler instance
1495 * @param $protocolInstance An instance of an ProtocolHandler
1498 public final function setProtocolInstance (ProtocolHandler $protocolInstance) {
1499 $this->protocolInstance = $protocolInstance;
1503 * Getter for ProtocolHandler instance
1505 * @return $protocolInstance An instance of an ProtocolHandler
1507 public final function getProtocolInstance () {
1508 return $this->protocolInstance;
1512 * Setter for BaseDatabaseWrapper instance
1514 * @param $wrapperInstance An instance of an BaseDatabaseWrapper
1517 public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
1518 $this->wrapperInstance = $wrapperInstance;
1522 * Getter for BaseDatabaseWrapper instance
1524 * @return $wrapperInstance An instance of an BaseDatabaseWrapper
1526 public final function getWrapperInstance () {
1527 return $this->wrapperInstance;
1531 * Setter for socket resource
1533 * @param $socketResource A valid socket resource
1536 public final function setSocketResource ($socketResource) {
1537 $this->socketResource = $socketResource;
1541 * Getter for socket resource
1543 * @return $socketResource A valid socket resource
1545 public function getSocketResource () {
1546 return $this->socketResource;
1550 * Setter for helper instance
1552 * @param $helperInstance An instance of a helper class
1555 protected final function setHelperInstance (Helper $helperInstance) {
1556 $this->helperInstance = $helperInstance;
1560 * Getter for helper instance
1562 * @return $helperInstance An instance of a helper class
1564 public final function getHelperInstance () {
1565 return $this->helperInstance;
1569 * Setter for a Sourceable instance
1571 * @param $sourceInstance The Sourceable instance
1574 protected final function setSourceInstance (Sourceable $sourceInstance) {
1575 $this->sourceInstance = $sourceInstance;
1579 * Getter for a InputStreamable instance
1581 * @param $inputStreamInstance The InputStreamable instance
1583 protected final function getInputStreamInstance () {
1584 return $this->inputStreamInstance;
1588 * Setter for a InputStreamable instance
1590 * @param $inputStreamInstance The InputStreamable instance
1593 protected final function setInputStreamInstance (InputStreamable $inputStreamInstance) {
1594 $this->inputStreamInstance = $inputStreamInstance;
1598 * Getter for a OutputStreamable instance
1600 * @param $outputStreamInstance The OutputStreamable instance
1602 protected final function getOutputStreamInstance () {
1603 return $this->outputStreamInstance;
1607 * Setter for a OutputStreamable instance
1609 * @param $outputStreamInstance The OutputStreamable instance
1612 protected final function setOutputStreamInstance (OutputStreamable $outputStreamInstance) {
1613 $this->outputStreamInstance = $outputStreamInstance;
1617 * Setter for raw package Data
1619 * @param $packageData Raw package Data
1622 public final function setPackageData (array $packageData) {
1623 $this->packageData = $packageData;
1627 * Getter for raw package Data
1629 * @return $packageData Raw package Data
1631 public function getPackageData () {
1632 return $this->packageData;
1636 * Converts a hexadecimal string, even with negative sign as first string to
1637 * a decimal number using BC functions.
1639 * This work is based on comment #86673 on php.net documentation page at:
1640 * <http://de.php.net/manual/en/function.dechex.php#86673>
1642 * @param $hex Hexadecimal string
1643 * @return $dec Decimal number
1645 protected function hex2dec ($hex) {
1646 // Convert to all lower-case
1647 $hex = strtolower($hex);
1649 // Detect sign (negative/positive numbers)
1651 if (substr($hex, 0, 1) == '-') {
1653 $hex = substr($hex, 1);
1656 // Decode the hexadecimal string into a decimal number
1658 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1659 $factor = self::$hexdec[substr($hex, $i, 1)];
1660 $dec = bcadd($dec, bcmul($factor, $e));
1663 // Return the decimal number
1664 return $sign . $dec;
1668 * Converts even very large decimal numbers, also with negative sign, to a
1669 * hexadecimal string.
1671 * This work is based on comment #97756 on php.net documentation page at:
1672 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1674 * @param $dec Decimal number, even with negative sign
1675 * @param $maxLength Optional maximum length of the string
1676 * @return $hex Hexadecimal string
1678 protected function dec2hex ($dec, $maxLength = 0) {
1679 // maxLength can be zero or devideable by 2
1680 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1682 // Detect sign (negative/positive numbers)
1689 // Encode the decimal number into a hexadecimal string
1692 $hex = self::$dechex[($dec % 16)] . $hex;
1694 } while ($dec >= 1);
1697 * We need hexadecimal strings with leading zeros if the length cannot
1700 if ($maxLength > 0) {
1701 // Prepend more zeros
1702 $hex = $this->prependStringToString($hex, '0', $maxLength);
1703 } elseif ((strlen($hex) % 2) != 0) {
1707 // Return the hexadecimal string
1708 return $sign . $hex;
1712 * Converts a ASCII string (0 to 255) into a decimal number.
1714 * @param $asc The ASCII string to be converted
1715 * @return $dec Decimal number
1717 protected function asc2dec ($asc) {
1718 // Convert it into a hexadecimal number
1719 $hex = bin2hex($asc);
1721 // And back into a decimal number
1722 $dec = $this->hex2dec($hex);
1729 * Converts a decimal number into an ASCII string.
1731 * @param $dec Decimal number
1732 * @return $asc An ASCII string
1734 protected function dec2asc ($dec) {
1735 // First convert the number into a hexadecimal string
1736 $hex = $this->dec2hex($dec);
1738 // Then convert it into the ASCII string
1739 $asc = $this->hex2asc($hex);
1746 * Converts a hexadecimal number into an ASCII string. Negative numbers
1749 * @param $hex Hexadecimal string
1750 * @return $asc An ASCII string
1752 protected function hex2asc ($hex) {
1753 // Check for length, it must be devideable by 2
1754 //* DEBUG: */ $this->debugOutput('hex='.$hex);
1755 assert((strlen($hex) % 2) == 0);
1759 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
1760 // Get the decimal number of the chunk
1761 $part = hexdec(substr($hex, $idx, 2));
1763 // Add it to the final string
1767 // Return the final string
1772 * Prepends a given string $prepend to $str with a given total length
1774 * @param $str Given original string which should be prepended
1775 * @param $prepend The string to prepend
1776 * @param $length Total length of the final string
1777 * @return $strFinal Final prepended string
1779 protected function prependStringToString ($str, $prepend, $length) {
1780 // Set final string to original string by default
1784 if (strlen($str) < $length) {
1785 // Difference between total length and length of original string
1786 $diff = $length - strlen($str);
1788 // Prepend the string
1789 $prepend = str_repeat($prepend, ($diff / strlen($prepend) + 1));
1791 // Make sure it will definedly fit
1792 assert(strlen($prepend) >= $diff);
1794 // Cut it a little down
1795 $prepend = substr($prepend, 0, $diff);
1796 //* DEBUG: */ $this->debugOutput('prepend('.strlen($prepend).')='.$prepend.',diff='.$diff.',length='.$length);
1798 // Construct the final prepended string
1799 $strFinal = $prepend . $str;