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 source
139 private $sourceInstance = null;
142 * The real class name
144 private $realClass = 'BaseFrameworkSystem';
147 * Thousands seperator
149 private $thousands = '.'; // German
154 private $decimals = ','; // German
159 private $socketResource = false;
164 private $packageData = array();
166 /***********************
167 * Exception codes.... *
168 ***********************/
169 // @todo Try to clean these constants up
170 const EXCEPTION_IS_NULL_POINTER = 0x001;
171 const EXCEPTION_IS_NO_OBJECT = 0x002;
172 const EXCEPTION_IS_NO_ARRAY = 0x003;
173 const EXCEPTION_MISSING_METHOD = 0x004;
174 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
175 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
176 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
177 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
178 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
179 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
180 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
181 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
182 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
183 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
184 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
185 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
186 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
187 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
188 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
189 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
190 const EXCEPTION_PATH_NOT_FOUND = 0x015;
191 const EXCEPTION_INVALID_PATH_NAME = 0x016;
192 const EXCEPTION_READ_PROTECED_PATH = 0x017;
193 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
194 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
195 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
196 const EXCEPTION_INVALID_RESOURCE = 0x01b;
197 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
198 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
199 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
200 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
201 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
202 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
203 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
204 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
205 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
206 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
207 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
208 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
209 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
210 const EXCEPTION_INVALID_STRING = 0x029;
211 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
212 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
213 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
214 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
215 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
216 const EXCEPTION_MISSING_ELEMENT = 0x030;
217 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
218 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
219 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
220 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
221 const EXCEPTION_FATAL_ERROR = 0x035;
222 const EXCEPTION_FILE_NOT_FOUND = 0x036;
223 const EXCEPTION_ASSERTION_FAILED = 0x037;
224 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
225 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
226 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x040;
228 // Hexadecimal->Decimal translation array
229 private static $hexdec = array(
248 // Decimal->hexadecimal translation array
249 private static $dechex = array(
269 * Protected super constructor
271 * @param $className Name of the class
274 protected function __construct ($className) {
276 $this->setRealClass($className);
278 // Set configuration instance if no registry ...
279 if (!$this instanceof Register) {
280 // ... because registries doesn't need to be configured
281 $this->setConfigInstance(FrameworkConfiguration::getInstance());
286 * Destructor reached...
290 public function __destruct() {
291 // Flush any updated entries to the database
292 $this->flushPendingUpdates();
294 // Is this object already destroyed?
295 if ($this->__toString() != 'DestructedObject') {
296 // Destroy all informations about this class but keep some text about it alive
297 $this->setRealClass('DestructedObject');
298 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
299 // Already destructed object
300 $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
308 * The __call() method where all non-implemented methods end up
310 * @param $methodName Name of the missing method
311 * @args $args Arguments passed to the method
314 public final function __call ($methodName, $args) {
315 // Implode all given arguments
319 $argsString = 'NULL';
320 } elseif (is_array($args)) {
321 // Some arguments are there
322 foreach ($args as $arg) {
324 $argsString .= $this->replaceControlCharacters($arg) . ' (' . gettype($arg);
326 // Add length if type is string
327 if (is_string($arg)) {
328 $argsString .= ', '.strlen($arg);
332 $argsString .= '), ';
336 if (substr($argsString, -2, 1) == ',') {
337 $argsString = substr($argsString, 0, -2);
340 // Invalid arguments!
341 $argsString = '!INVALID:' . gettype($args) . '!';
344 // Output stub message
345 $this->debugOutput(sprintf("[%s->%s] Stub! Args: %s",
356 * Getter for $realClass
358 * @return $realClass The name of the real class (not BaseFrameworkSystem)
360 public function __toString () {
361 return $this->realClass;
365 * Magic function to catch setting of missing but set class fields/attributes
367 * @param $name Name of the field/attribute
368 * @param $value Value to store
371 public final function __set ($name, $value) {
372 $this->debugBackTrace(sprintf("Tried to set a missing field. name=%s, value[%s]=%s",
380 * Magic function to catch getting of missing fields/attributes
382 * @param $name Name of the field/attribute
385 public final function __get ($name) {
386 $this->debugBackTrace(sprintf("Tried to get a missing field. name=%s",
392 * Magic function to catch unsetting of missing fields/attributes
394 * @param $name Name of the field/attribute
397 public final function __unset ($name) {
398 $this->debugBackTrace(sprintf("Tried to unset a missing field. name=%s",
404 * Setter for database result instance
406 * @param $resultInstance An instance of a database result class
408 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
410 protected final function setResultInstance (SearchableResult $resultInstance) {
411 $this->resultInstance = $resultInstance;
415 * Getter for database result instance
417 * @return $resultInstance An instance of a database result class
419 public final function getResultInstance () {
420 return $this->resultInstance;
424 * Setter for template engine instances
426 * @param $templateInstance An instance of a template engine class
429 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
430 $this->templateInstance = $templateInstance;
434 * Getter for template engine instances
436 * @return $templateInstance An instance of a template engine class
438 protected final function getTemplateInstance () {
439 return $this->templateInstance;
443 * Setter for search instance
445 * @param $searchInstance Searchable criteria instance
448 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
449 $this->searchInstance = $searchInstance;
453 * Getter for search instance
455 * @return $searchInstance Searchable criteria instance
457 public final function getSearchInstance () {
458 return $this->searchInstance;
462 * Setter for update instance
464 * @param $updateInstance Searchable criteria instance
467 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
468 $this->updateInstance = $updateInstance;
472 * Getter for update instance
474 * @return $updateInstance Updateable criteria instance
476 public final function getUpdateInstance () {
477 return $this->updateInstance;
481 * Setter for resolver instance
483 * @param $resolverInstance Instance of a command resolver class
486 public final function setResolverInstance (Resolver $resolverInstance) {
487 $this->resolverInstance = $resolverInstance;
491 * Getter for resolver instance
493 * @return $resolverInstance Instance of a command resolver class
495 public final function getResolverInstance () {
496 return $this->resolverInstance;
500 * Setter for language instance
502 * @param $configInstance The configuration instance which shall
503 * be FrameworkConfiguration
506 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
507 Registry::getRegistry()->addInstance('config', $configInstance);
511 * Getter for configuration instance
513 * @return $configInstance Configuration instance
515 public final function getConfigInstance () {
516 $configInstance = Registry::getRegistry()->getInstance('config');
517 return $configInstance;
521 * Setter for debug instance
523 * @param $debugInstance The instance for debug output class
526 public final function setDebugInstance (DebugMiddleware $debugInstance) {
527 Registry::getRegistry()->addInstance('debug', $debugInstance);
531 * Getter for debug instance
533 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
535 public final function getDebugInstance () {
536 // Get debug instance
537 $debugInstance = Registry::getRegistry()->getInstance('debug');
540 return $debugInstance;
544 * Setter for web output instance
546 * @param $webInstance The instance for web output class
549 public final function setWebOutputInstance (OutputStreamer $webInstance) {
550 Registry::getRegistry()->addInstance('web_output', $webInstance);
554 * Getter for web output instance
556 * @return $webOutputInstance - Instance to class WebOutput
558 public final function getWebOutputInstance () {
559 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
560 return $webOutputInstance;
564 * Setter for database instance
566 * @param $dbInstance The instance for the database connection (forced DatabaseConnection)
569 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
570 Registry::getRegistry()->addInstance('db_instance', $dbInstance);
574 * Getter for database layer
576 * @return $dbInstance The database layer instance
578 public final function getDatabaseInstance () {
580 $dbInstance = Registry::getRegistry()->getInstance('db_instance');
587 * Setter for compressor channel
589 * @param $compressorInstance An instance of CompressorChannel
592 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
593 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
597 * Getter for compressor channel
599 * @return $compressorInstance The compressor channel
601 public final function getCompressorChannel () {
602 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
603 return $compressorInstance;
607 * Protected getter for a manageable application helper class
609 * @return $applicationInstance An instance of a manageable application helper class
611 protected final function getApplicationInstance () {
612 $applicationInstance = Registry::getRegistry()->getInstance('application');
613 return $applicationInstance;
617 * Setter for a manageable application helper class
619 * @param $applicationInstance An instance of a manageable application helper class
622 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
623 Registry::getRegistry()->addInstance('application', $applicationInstance);
627 * Setter for request instance
629 * @param $requestInstance An instance of a Requestable class
632 public final function setRequestInstance (Requestable $requestInstance) {
633 $this->requestInstance = $requestInstance;
637 * Getter for request instance
639 * @return $requestInstance An instance of a Requestable class
641 public final function getRequestInstance () {
642 return $this->requestInstance;
646 * Setter for response instance
648 * @param $responseInstance An instance of a Responseable class
651 public final function setResponseInstance (Responseable $responseInstance) {
652 $this->responseInstance = $responseInstance;
656 * Getter for response instance
658 * @return $responseInstance An instance of a Responseable class
660 public final function getResponseInstance () {
661 return $this->responseInstance;
665 * Setter for the real class name
667 * @param $realClass Class name (string)
670 public final function setRealClass ($realClass) {
672 $realClass = (string) $realClass;
675 $this->realClass = $realClass;
679 * Checks wether an object equals this object. You should overwrite this
680 * method to implement own equality checks
682 * @param $objectInstance An instance of a FrameworkInterface object
683 * @return $equals Wether both objects equals
685 public function equals (FrameworkInterface $objectInstance) {
688 $this->__toString() == $objectInstance->__toString()
690 $this->hashCode() == $objectInstance->hashCode()
698 * Generates a generic hash code of this class. You should really overwrite
699 * this method with your own hash code generator code. But keep KISS in mind.
701 * @return $hashCode A generic hash code respresenting this whole class
703 public function hashCode () {
705 return crc32($this->__toString());
709 * Formats computer generated price values into human-understandable formats
710 * with thousand and decimal seperators.
712 * @param $value The in computer format value for a price
713 * @param $currency The currency symbol (use HTML-valid characters!)
714 * @param $decNum Number of decimals after commata
715 * @return $price The for the current language formated price string
716 * @throws MissingDecimalsThousandsSeperatorException If decimals or
717 * thousands seperator
720 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
721 // Are all required attriutes set?
722 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
723 // Throw an exception
724 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
728 $value = (float) $value;
730 // Reformat the US number
731 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
733 // Return as string...
738 * Private getter for language instance
740 * @return $langInstance An instance to the language sub-system
742 protected final function getLanguageInstance () {
743 $langInstance = Registry::getRegistry()->getInstance('language');
744 return $langInstance;
748 * Setter for language instance
750 * @param $langInstance An instance to the language sub-system
752 * @see LanguageSystem
754 public final function setLanguageInstance (ManageableLanguage $langInstance) {
755 Registry::getRegistry()->addInstance('language', $langInstance);
759 * Appends a trailing slash to a string
761 * @param $str A string (maybe) without trailing slash
762 * @return $str A string with an auto-appended trailing slash
764 public final function addMissingTrailingSlash ($str) {
765 // Is there a trailing slash?
766 if (substr($str, -1, 1) != '/') {
770 // Return string with trailing slash
775 * Private getter for file IO instance
777 * @return $fileIoInstance An instance to the file I/O sub-system
779 protected final function getFileIoInstance () {
780 return $this->fileIoInstance;
784 * Setter for file I/O instance
786 * @param $fileIoInstance An instance to the file I/O sub-system
789 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
790 $this->fileIoInstance = $fileIoInstance;
794 * Prepare the template engine (WebTemplateEngine by default) for a given
795 * application helper instance (ApplicationHelper by default).
797 * @param $applicationInstance An application helper instance or
798 * null if we shall use the default
799 * @return $templateInstance The template engine instance
800 * @throws NullPointerException If the discovered application
801 * instance is still null
803 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = null) {
804 // Is the application instance set?
805 if (is_null($applicationInstance)) {
806 // Get the current instance
807 $applicationInstance = $this->getApplicationInstance();
810 if (is_null($applicationInstance)) {
811 // Thrown an exception
812 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
816 // Initialize the template engine
817 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
819 // Return the prepared instance
820 return $templateInstance;
824 * Debugs this instance by putting out it's full content
826 * @param $message Optional message to show in debug output
829 public final function debugInstance ($message = '') {
830 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
831 restore_error_handler();
837 if (!empty($message)) {
839 $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
842 // Generate the output
843 $content .= sprintf("<pre>%s</pre>",
852 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>",
855 ClassLoader::getInstance()->getPrintableIncludeList()
860 * Replaces control characters with printable output
862 * @param $str String with control characters
863 * @return $str Replaced string
865 protected function replaceControlCharacters ($str) {
868 "\r", '[r]', str_replace(
869 "\n", '[n]', str_replace(
879 * Output a partial stub message for the caller method
881 * @param $message An optional message to display
884 protected function partialStub ($message = '') {
886 $backtrace = debug_backtrace();
888 // Generate the class::method string
889 $methodName = 'UnknownClass->unknownMethod';
890 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
891 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
894 // Construct the full message
895 $stubMessage = sprintf("[%s:] Partial stub!",
899 // Is the extra message given?
900 if (!empty($message)) {
901 // Then add it as well
902 $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
905 // Debug instance is there?
906 if (!is_null($this->getDebugInstance())) {
907 // Output stub message
908 $this->debugOutput($stubMessage);
911 trigger_error($stubMessage . "<br />\n");
916 * Outputs a debug backtrace and stops further script execution
918 * @param $message An optional message to output
921 public function debugBackTrace ($message = '') {
922 // Sorry, there is no other way getting this nice backtrace
923 if (!empty($message)) {
925 printf("Message: %s<br />\n", $message);
929 debug_print_backtrace();
935 * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
937 * @param $message Message we shall send out...
938 * @param $doPrint Wether we shall print or die here which first is the default
941 public function debugOutput ($message, $doPrint = true) {
942 // Get debug instance
943 $debugInstance = $this->getDebugInstance();
945 // Is the debug instance there?
946 if (is_object($debugInstance)) {
947 // Use debug output handler
948 $debugInstance->output($message);
950 if ($doPrint === false) {
951 // Die here if not printed
956 if ($doPrint === true) {
959 // DO NOT REWRITE THIS TO app_die() !!!
966 * Converts e.g. a command from URL to a valid class by keeping out bad characters
968 * @param $str The string, what ever it is needs to be converted
969 * @return $className Generated class name
971 public function convertToClassName ($str) {
975 // Convert all dashes in underscores
976 $str = $this->convertDashesToUnderscores($str);
978 // Now use that underscores to get classname parts for hungarian style
979 foreach (explode('_', $str) as $strPart) {
980 // Make the class name part lower case and first upper case
981 $className .= ucfirst(strtolower($strPart));
989 * Converts dashes to underscores, e.g. useable for configuration entries
991 * @param $str The string with maybe dashes inside
992 * @return $str The converted string with no dashed, but underscores
994 public final function convertDashesToUnderscores ($str) {
996 $str = str_replace('-', '_', $str);
998 // Return converted string
1003 * Marks up the code by adding e.g. line numbers
1005 * @param $phpCode Unmarked PHP code
1006 * @return $markedCode Marked PHP code
1008 public function markupCode ($phpCode) {
1013 $errorArray = error_get_last();
1015 // Init the code with error message
1016 if (is_array($errorArray)) {
1018 $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>",
1019 basename($errorArray['file']),
1020 $errorArray['line'],
1021 $errorArray['message'],
1026 // Add line number to the code
1027 foreach (explode("\n", $phpCode) as $lineNo => $code) {
1029 $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
1031 htmlentities($code, ENT_QUOTES)
1040 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1041 * beatiful for web-based front-ends. If null is given a message id
1042 * null_timestamp will be resolved and returned.
1044 * @param $timestamp Timestamp to prepare (filter) for display
1045 * @return $readable A readable timestamp
1047 public function doFilterFormatTimestamp ($timestamp) {
1048 // Default value to return
1051 // Is the timestamp null?
1052 if (is_null($timestamp)) {
1053 // Get a message string
1054 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1056 switch ($this->getLanguageInstance()->getLanguageCode()) {
1057 case 'de': // German format is a bit different to default
1058 // Split the GMT stamp up
1059 $dateTime = explode(' ', $timestamp );
1060 $dateArray = explode('-', $dateTime[0]);
1061 $timeArray = explode(':', $dateTime[1]);
1063 // Construct the timestamp
1064 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1074 default: // Default is pass-through
1075 $readable = $timestamp;
1085 * Filter a given number into a localized number
1087 * @param $value The raw value from e.g. database
1088 * @return $localized Localized value
1090 public function doFilterFormatNumber ($value) {
1091 // Generate it from config and localize dependencies
1092 switch ($this->getLanguageInstance()->getLanguageCode()) {
1093 case 'de': // German format is a bit different to default
1094 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1097 default: // US, etc.
1098 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1107 * "Getter" for databse entry
1109 * @return $entry An array with database entries
1110 * @throws NullPointerException If the database result is not found
1111 * @throws InvalidDatabaseResultException If the database result is invalid
1113 protected final function getDatabaseEntry () {
1114 // Is there an instance?
1115 if (is_null($this->getResultInstance())) {
1116 // Throw an exception here
1117 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1121 $this->getResultInstance()->rewind();
1123 // Do we have an entry?
1124 if ($this->getResultInstance()->valid() === false) {
1125 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1129 $this->getResultInstance()->next();
1132 $entry = $this->getResultInstance()->current();
1139 * Getter for field name
1141 * @param $fieldName Field name which we shall get
1142 * @return $fieldValue Field value from the user
1143 * @throws NullPointerException If the result instance is null
1145 public final function getField ($fieldName) {
1146 // Default field value
1149 // Get result instance
1150 $resultInstance = $this->getResultInstance();
1152 // Is this instance null?
1153 if (is_null($resultInstance)) {
1154 // Then the user instance is no longer valid (expired cookies?)
1155 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1158 // Get current array
1159 $fieldArray = $resultInstance->current();
1160 //* DEBUG: */ $this->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1162 // Does the field exist?
1163 if (isset($fieldArray[$fieldName])) {
1165 $fieldValue = $fieldArray[$fieldName];
1173 * Protected setter for user instance
1175 * @param $userInstance An instance of a user class
1178 protected final function setUserInstance (ManageableAccount $userInstance) {
1179 $this->userInstance = $userInstance;
1183 * Getter for user instance
1185 * @return $userInstance An instance of a user class
1187 public final function getUserInstance () {
1188 return $this->userInstance;
1192 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1194 * @param $controllerInstance An instance of the controller
1197 public final function setControllerInstance (Controller $controllerInstance) {
1198 $this->controllerInstance = $controllerInstance;
1202 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1204 * @return $controllerInstance An instance of the controller
1206 public final function getControllerInstance () {
1207 return $this->controllerInstance;
1211 * Flushs all pending updates to the database layer
1215 public function flushPendingUpdates () {
1216 // Get result instance
1217 $resultInstance = $this->getResultInstance();
1219 // Do we have data to update?
1220 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1221 // Get wrapper class name config entry
1222 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1224 // Create object instance
1225 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1227 // Yes, then send the whole result to the database layer
1228 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1233 * Outputs a deprecation warning to the developer.
1235 * @param $message The message we shall output to the developer
1237 * @todo Write a logging mechanism for productive mode
1239 public function deprecationWarning ($message) {
1240 // Is developer mode active?
1241 if (defined('DEVELOPER')) {
1242 // Debug instance is there?
1243 if (!is_null($this->getDebugInstance())) {
1244 // Output stub message
1245 $this->debugOutput($message);
1248 trigger_error($message . "<br />\n");
1251 // @TODO Finish this part!
1252 $this->partialStub('Developer mode inactive. Message:' . $message);
1257 * Checks wether the given PHP extension is loaded
1259 * @param $phpExtension The PHP extension we shall check
1260 * @return $isLoaded Wether the PHP extension is loaded
1262 public final function isPhpExtensionLoaded ($phpExtension) {
1264 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1271 * Setter for RNG instance
1273 * @param $rngInstance An instance of a random number generator (RNG)
1276 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1277 $this->rngInstance = $rngInstance;
1281 * Getter for RNG instance
1283 * @return $rngInstance An instance of a random number generator (RNG)
1285 public final function getRngInstance () {
1286 return $this->rngInstance;
1290 * Setter for Cryptable instance
1292 * @param $cryptoInstance An instance of a Cryptable class
1295 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1296 $this->cryptoInstance = $cryptoInstance;
1300 * Getter for Cryptable instance
1302 * @return $cryptoInstance An instance of a Cryptable class
1304 public final function getCryptoInstance () {
1305 return $this->cryptoInstance;
1309 * Setter for Iterator instance
1311 * @param $iteratorInstance An instance of an Iterator
1314 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1315 $this->iteratorInstance = $iteratorInstance;
1319 * Getter for Iterator instance
1321 * @return $iteratorInstance An instance of an Iterator
1323 public final function getIteratorInstance () {
1324 return $this->iteratorInstance;
1328 * "Getter" as a time() replacement but with milliseconds. You should use this
1329 * method instead of the encapsulated getimeofday() function.
1331 * @return $milliTime Timestamp with milliseconds
1333 public function getMilliTime () {
1334 // Get the time of day as float
1335 $milliTime = gettimeofday(true);
1342 * Idles (sleeps) for given milliseconds
1344 * @return $hasSlept Wether it goes fine
1346 public function idle ($milliSeconds) {
1347 // Sleep is fine by default
1350 // Idle so long with found function
1351 if (function_exists('time_sleep_until')) {
1352 // Get current time and add idle time
1353 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1355 // New PHP 5.1.0 function found
1356 $hasSlept = time_sleep_until($sleepUntil);
1358 // My Sun Station doesn't have that function even with latest PHP
1360 usleep($milliSeconds * 1000);
1368 * Setter for the list instance
1370 * @param $listInstance A list of Listable
1373 protected final function setListInstance (Listable $listInstance) {
1374 $this->listInstance = $listInstance;
1378 * Getter for the list instance
1380 * @return $listInstance A list of Listable
1382 protected final function getListInstance () {
1383 return $this->listInstance;
1387 * Setter for the menu instance
1389 * @param $menuInstance A RenderableMenu instance
1392 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1393 $this->menuInstance = $menuInstance;
1397 * Getter for the menu instance
1399 * @return $menuInstance A RenderableMenu instance
1401 protected final function getMenuInstance () {
1402 return $this->menuInstance;
1406 * Setter for image instance
1408 * @param $imageInstance An instance of an image
1411 public final function setImageInstance (BaseImage $imageInstance) {
1412 $this->imageInstance = $imageInstance;
1416 * Getter for image instance
1418 * @return $imageInstance An instance of an image
1420 public final function getImageInstance () {
1421 return $this->imageInstance;
1425 * Setter for stacker instance
1427 * @param $stackerInstance An instance of an stacker
1430 public final function setStackerInstance (Stackable $stackerInstance) {
1431 $this->stackerInstance = $stackerInstance;
1435 * Getter for stacker instance
1437 * @return $stackerInstance An instance of an stacker
1439 public final function getStackerInstance () {
1440 return $this->stackerInstance;
1444 * Setter for compressor instance
1446 * @param $compressorInstance An instance of an compressor
1449 public final function setCompressorInstance (Compressor $compressorInstance) {
1450 $this->compressorInstance = $compressorInstance;
1454 * Getter for compressor instance
1456 * @return $compressorInstance An instance of an compressor
1458 public final function getCompressorInstance () {
1459 return $this->compressorInstance;
1463 * Setter for Parseable instance
1465 * @param $parserInstance An instance of an Parseable
1468 public final function setParserInstance (Parseable $parserInstance) {
1469 $this->parserInstance = $parserInstance;
1473 * Getter for Parseable instance
1475 * @return $parserInstance An instance of an Parseable
1477 public final function getParserInstance () {
1478 return $this->parserInstance;
1482 * Setter for ProtocolHandler instance
1484 * @param $protocolInstance An instance of an ProtocolHandler
1487 public final function setProtocolInstance (ProtocolHandler $protocolInstance) {
1488 $this->protocolInstance = $protocolInstance;
1492 * Getter for ProtocolHandler instance
1494 * @return $protocolInstance An instance of an ProtocolHandler
1496 public final function getProtocolInstance () {
1497 return $this->protocolInstance;
1501 * Setter for BaseDatabaseWrapper instance
1503 * @param $wrapperInstance An instance of an BaseDatabaseWrapper
1506 public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
1507 $this->wrapperInstance = $wrapperInstance;
1511 * Getter for BaseDatabaseWrapper instance
1513 * @return $wrapperInstance An instance of an BaseDatabaseWrapper
1515 public final function getWrapperInstance () {
1516 return $this->wrapperInstance;
1520 * Setter for socket resource
1522 * @param $socketResource A valid socket resource
1525 public final function setSocketResource ($socketResource) {
1526 $this->socketResource = $socketResource;
1530 * Getter for socket resource
1532 * @return $socketResource A valid socket resource
1534 public function getSocketResource () {
1535 return $this->socketResource;
1539 * Setter for helper instance
1541 * @param $helperInstance An instance of a helper class
1544 protected final function setHelperInstance (Helper $helperInstance) {
1545 $this->helperInstance = $helperInstance;
1549 * Getter for helper instance
1551 * @return $helperInstance An instance of a helper class
1553 public final function getHelperInstance () {
1554 return $this->helperInstance;
1558 * Setter for a Sourceable instance
1560 * @param $sourceInstance The Sourceable instance
1563 protected final function setSourceInstance (Sourceable $sourceInstance) {
1564 $this->sourceInstance = $sourceInstance;
1568 * Getter for a Sourceable instance
1570 * @param $sourceInstance The Sourceable instance
1572 protected final function getSourceInstance () {
1573 return $this->sourceInstance;
1577 * Setter for raw package Data
1579 * @param $packageData Raw package Data
1582 public final function setPackageData (array $packageData) {
1583 $this->packageData = $packageData;
1587 * Getter for raw package Data
1589 * @return $packageData Raw package Data
1591 public function getPackageData () {
1592 return $this->packageData;
1596 * Converts a hexadecimal string, even with negative sign as first string to
1597 * a decimal number using BC functions.
1599 * This work is based on comment #86673 on php.net documentation page at:
1600 * <http://de.php.net/manual/en/function.dechex.php#86673>
1602 * @param $hex Hexadecimal string
1603 * @return $dec Decimal number
1605 public final function hex2dec ($hex) {
1606 // Convert to all lower-case
1607 $hex = strtolower($hex);
1609 // Detect sign (negative/positive numbers)
1611 if (substr($hex, 0, 1) == '-') {
1613 $hex = substr($hex, 1);
1616 // Decode the hexadecimal string into a decimal number
1618 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1619 $factor = self:$hexdec[substr($hex, $i, 1)];
1620 $dec = bcadd($dec, bcmul($factor, $e));
1623 // Return the decimal number
1624 return $sign . $dec;
1628 * Converts even very large decimal numbers, also with negative sign, to a
1629 * hexadecimal string.
1631 * This work is based on comment #97756 on php.net documentation page at:
1632 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1634 * @param $dec Decimal number, even with negative sign
1635 * @return $hex Hexadecimal string
1637 public final function dec2hex ($dec) {
1638 // Detect sign (negative/positive numbers)
1645 // Encode the decimal number into a hexadecimal string
1648 $hex = self:$dechex[($dec % 16)] . $hex;
1650 } while ($dec >= 1);
1652 // Return the hexadecimal string
1653 return $sign . $hex;
1657 * Converts a ASCII string (0 to 255) into a decimal number.
1659 * @param $asc The ASCII string to be converted
1660 * @return $dec Decimal number
1662 public final function asc2dec ($asc) {
1663 // Convert it into a hexadecimal number
1664 $hex = bin2hex($asc);
1666 // And back into a decimal number
1667 $dec = $this->hex2dec($hex);
1674 * Converts a decimal number into an ASCII string.
1676 * @param $dec Decimal number
1677 * @return $asc An ASCII string
1679 public final function dec2asc ($deg) {
1680 // First convert the number into a hexadecimal string
1681 $hex = $this->dec2hex($deg);
1683 // Then convert it into the ASCII string
1684 $asc = $this->hex2asc($hex);
1691 * Converts a hexadecimal number into an ASCII string. Negative numbers
1694 * @param $hex Hexadecimal string
1695 * @return $asc An ASCII string
1697 public final function hex2asc ($hex) {
1698 // Check for length, it must be devideable by 2
1699 assert((strlen($hex) % 2) == 0);
1703 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
1704 // Get the decimal number of the chunk
1705 $part = hexdec(substr($hex, $idx, 2));
1706 $this->debugOutput(__FUNCTION__ . ': part(' . strlen($part) . ')=' . $part);
1708 // Add it to the final string
1712 // Return the final string