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;
229 * Protected super constructor
231 * @param $className Name of the class
234 protected function __construct ($className) {
236 $this->setRealClass($className);
238 // Set configuration instance if no registry ...
239 if (!$this instanceof Register) {
240 // ... because registries doesn't need to be configured
241 $this->setConfigInstance(FrameworkConfiguration::getInstance());
246 * Destructor reached...
250 public function __destruct() {
251 // Flush any updated entries to the database
252 $this->flushPendingUpdates();
254 // Is this object already destroyed?
255 if ($this->__toString() != 'DestructedObject') {
256 // Destroy all informations about this class but keep some text about it alive
257 $this->setRealClass('DestructedObject');
258 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
259 // Already destructed object
260 $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
268 * The __call() method where all non-implemented methods end up
270 * @param $methodName Name of the missing method
271 * @args $args Arguments passed to the method
274 public final function __call ($methodName, $args) {
275 // Implode all given arguments
279 $argsString = 'NULL';
280 } elseif (is_array($args)) {
281 // Some arguments are there
282 foreach ($args as $arg) {
284 $argsString .= $this->replaceControlCharacters($arg) . ' (' . gettype($arg);
286 // Add length if type is string
287 if (is_string($arg)) {
288 $argsString .= ', '.strlen($arg);
292 $argsString .= '), ';
296 if (substr($argsString, -2, 1) == ',') {
297 $argsString = substr($argsString, 0, -2);
300 // Invalid arguments!
301 $argsString = '!INVALID:' . gettype($args) . '!';
304 // Output stub message
305 $this->debugOutput(sprintf("[%s->%s] Stub! Args: %s",
316 * Getter for $realClass
318 * @return $realClass The name of the real class (not BaseFrameworkSystem)
320 public function __toString () {
321 return $this->realClass;
325 * Magic function to catch setting of missing but set class fields/attributes
327 * @param $name Name of the field/attribute
328 * @param $value Value to store
331 public final function __set ($name, $value) {
332 $this->debugBackTrace(sprintf("Tried to set a missing field. name=%s, value[%s]=%s",
340 * Magic function to catch getting of missing fields/attributes
342 * @param $name Name of the field/attribute
345 public final function __get ($name) {
346 $this->debugBackTrace(sprintf("Tried to get a missing field. name=%s",
352 * Magic function to catch unsetting of missing fields/attributes
354 * @param $name Name of the field/attribute
357 public final function __unset ($name) {
358 $this->debugBackTrace(sprintf("Tried to unset a missing field. name=%s",
364 * Setter for database result instance
366 * @param $resultInstance An instance of a database result class
368 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
370 protected final function setResultInstance (SearchableResult $resultInstance) {
371 $this->resultInstance = $resultInstance;
375 * Getter for database result instance
377 * @return $resultInstance An instance of a database result class
379 public final function getResultInstance () {
380 return $this->resultInstance;
384 * Setter for template engine instances
386 * @param $templateInstance An instance of a template engine class
389 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
390 $this->templateInstance = $templateInstance;
394 * Getter for template engine instances
396 * @return $templateInstance An instance of a template engine class
398 protected final function getTemplateInstance () {
399 return $this->templateInstance;
403 * Setter for search instance
405 * @param $searchInstance Searchable criteria instance
408 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
409 $this->searchInstance = $searchInstance;
413 * Getter for search instance
415 * @return $searchInstance Searchable criteria instance
417 public final function getSearchInstance () {
418 return $this->searchInstance;
422 * Setter for update instance
424 * @param $updateInstance Searchable criteria instance
427 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
428 $this->updateInstance = $updateInstance;
432 * Getter for update instance
434 * @return $updateInstance Updateable criteria instance
436 public final function getUpdateInstance () {
437 return $this->updateInstance;
441 * Setter for resolver instance
443 * @param $resolverInstance Instance of a command resolver class
446 public final function setResolverInstance (Resolver $resolverInstance) {
447 $this->resolverInstance = $resolverInstance;
451 * Getter for resolver instance
453 * @return $resolverInstance Instance of a command resolver class
455 public final function getResolverInstance () {
456 return $this->resolverInstance;
460 * Setter for language instance
462 * @param $configInstance The configuration instance which shall
463 * be FrameworkConfiguration
466 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
467 Registry::getRegistry()->addInstance('config', $configInstance);
471 * Getter for configuration instance
473 * @return $configInstance Configuration instance
475 public final function getConfigInstance () {
476 $configInstance = Registry::getRegistry()->getInstance('config');
477 return $configInstance;
481 * Setter for debug instance
483 * @param $debugInstance The instance for debug output class
486 public final function setDebugInstance (DebugMiddleware $debugInstance) {
487 Registry::getRegistry()->addInstance('debug', $debugInstance);
491 * Getter for debug instance
493 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
495 public final function getDebugInstance () {
496 // Get debug instance
497 $debugInstance = Registry::getRegistry()->getInstance('debug');
500 return $debugInstance;
504 * Setter for web output instance
506 * @param $webInstance The instance for web output class
509 public final function setWebOutputInstance (OutputStreamer $webInstance) {
510 Registry::getRegistry()->addInstance('web_output', $webInstance);
514 * Getter for web output instance
516 * @return $webOutputInstance - Instance to class WebOutput
518 public final function getWebOutputInstance () {
519 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
520 return $webOutputInstance;
524 * Setter for database instance
526 * @param $dbInstance The instance for the database connection (forced DatabaseConnection)
529 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
530 Registry::getRegistry()->addInstance('db_instance', $dbInstance);
534 * Getter for database layer
536 * @return $dbInstance The database layer instance
538 public final function getDatabaseInstance () {
540 $dbInstance = Registry::getRegistry()->getInstance('db_instance');
547 * Setter for compressor channel
549 * @param $compressorInstance An instance of CompressorChannel
552 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
553 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
557 * Getter for compressor channel
559 * @return $compressorInstance The compressor channel
561 public final function getCompressorChannel () {
562 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
563 return $compressorInstance;
567 * Protected getter for a manageable application helper class
569 * @return $applicationInstance An instance of a manageable application helper class
571 protected final function getApplicationInstance () {
572 $applicationInstance = Registry::getRegistry()->getInstance('application');
573 return $applicationInstance;
577 * Setter for a manageable application helper class
579 * @param $applicationInstance An instance of a manageable application helper class
582 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
583 Registry::getRegistry()->addInstance('application', $applicationInstance);
587 * Setter for request instance
589 * @param $requestInstance An instance of a Requestable class
592 public final function setRequestInstance (Requestable $requestInstance) {
593 $this->requestInstance = $requestInstance;
597 * Getter for request instance
599 * @return $requestInstance An instance of a Requestable class
601 public final function getRequestInstance () {
602 return $this->requestInstance;
606 * Setter for response instance
608 * @param $responseInstance An instance of a Responseable class
611 public final function setResponseInstance (Responseable $responseInstance) {
612 $this->responseInstance = $responseInstance;
616 * Getter for response instance
618 * @return $responseInstance An instance of a Responseable class
620 public final function getResponseInstance () {
621 return $this->responseInstance;
625 * Setter for the real class name
627 * @param $realClass Class name (string)
630 public final function setRealClass ($realClass) {
632 $realClass = (string) $realClass;
635 $this->realClass = $realClass;
639 * Checks wether an object equals this object. You should overwrite this
640 * method to implement own equality checks
642 * @param $objectInstance An instance of a FrameworkInterface object
643 * @return $equals Wether both objects equals
645 public function equals (FrameworkInterface $objectInstance) {
648 $this->__toString() == $objectInstance->__toString()
650 $this->hashCode() == $objectInstance->hashCode()
658 * Generates a generic hash code of this class. You should really overwrite
659 * this method with your own hash code generator code. But keep KISS in mind.
661 * @return $hashCode A generic hash code respresenting this whole class
663 public function hashCode () {
665 return crc32($this->__toString());
669 * Formats computer generated price values into human-understandable formats
670 * with thousand and decimal seperators.
672 * @param $value The in computer format value for a price
673 * @param $currency The currency symbol (use HTML-valid characters!)
674 * @param $decNum Number of decimals after commata
675 * @return $price The for the current language formated price string
676 * @throws MissingDecimalsThousandsSeperatorException If decimals or
677 * thousands seperator
680 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
681 // Are all required attriutes set?
682 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
683 // Throw an exception
684 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
688 $value = (float) $value;
690 // Reformat the US number
691 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
693 // Return as string...
698 * Private getter for language instance
700 * @return $langInstance An instance to the language sub-system
702 protected final function getLanguageInstance () {
703 $langInstance = Registry::getRegistry()->getInstance('language');
704 return $langInstance;
708 * Setter for language instance
710 * @param $langInstance An instance to the language sub-system
712 * @see LanguageSystem
714 public final function setLanguageInstance (ManageableLanguage $langInstance) {
715 Registry::getRegistry()->addInstance('language', $langInstance);
719 * Appends a trailing slash to a string
721 * @param $str A string (maybe) without trailing slash
722 * @return $str A string with an auto-appended trailing slash
724 public final function addMissingTrailingSlash ($str) {
725 // Is there a trailing slash?
726 if (substr($str, -1, 1) != '/') {
730 // Return string with trailing slash
735 * Private getter for file IO instance
737 * @return $fileIoInstance An instance to the file I/O sub-system
739 protected final function getFileIoInstance () {
740 return $this->fileIoInstance;
744 * Setter for file I/O instance
746 * @param $fileIoInstance An instance to the file I/O sub-system
749 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
750 $this->fileIoInstance = $fileIoInstance;
754 * Prepare the template engine (WebTemplateEngine by default) for a given
755 * application helper instance (ApplicationHelper by default).
757 * @param $applicationInstance An application helper instance or
758 * null if we shall use the default
759 * @return $templateInstance The template engine instance
760 * @throws NullPointerException If the discovered application
761 * instance is still null
763 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = null) {
764 // Is the application instance set?
765 if (is_null($applicationInstance)) {
766 // Get the current instance
767 $applicationInstance = $this->getApplicationInstance();
770 if (is_null($applicationInstance)) {
771 // Thrown an exception
772 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
776 // Initialize the template engine
777 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
779 // Return the prepared instance
780 return $templateInstance;
784 * Debugs this instance by putting out it's full content
786 * @param $message Optional message to show in debug output
789 public final function debugInstance ($message = '') {
790 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
791 restore_error_handler();
797 if (!empty($message)) {
799 $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
802 // Generate the output
803 $content .= sprintf("<pre>%s</pre>",
812 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>",
815 ClassLoader::getInstance()->getPrintableIncludeList()
820 * Replaces control characters with printable output
822 * @param $str String with control characters
823 * @return $str Replaced string
825 protected function replaceControlCharacters ($str) {
828 "\r", '[r]', str_replace(
829 "\n", '[n]', str_replace(
839 * Output a partial stub message for the caller method
841 * @param $message An optional message to display
844 protected function partialStub ($message = '') {
846 $backtrace = debug_backtrace();
848 // Generate the class::method string
849 $methodName = 'UnknownClass->unknownMethod';
850 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
851 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
854 // Construct the full message
855 $stubMessage = sprintf("[%s:] Partial stub!",
859 // Is the extra message given?
860 if (!empty($message)) {
861 // Then add it as well
862 $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
865 // Debug instance is there?
866 if (!is_null($this->getDebugInstance())) {
867 // Output stub message
868 $this->debugOutput($stubMessage);
871 trigger_error($stubMessage . "<br />\n");
876 * Outputs a debug backtrace and stops further script execution
878 * @param $message An optional message to output
881 public function debugBackTrace ($message = '') {
882 // Sorry, there is no other way getting this nice backtrace
883 if (!empty($message)) {
885 printf("Message: %s<br />\n", $message);
889 debug_print_backtrace();
895 * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
897 * @param $message Message we shall send out...
898 * @param $doPrint Wether we shall print or die here which first is the default
901 public function debugOutput ($message, $doPrint = true) {
902 // Get debug instance
903 $debugInstance = $this->getDebugInstance();
905 // Is the debug instance there?
906 if (is_object($debugInstance)) {
907 // Use debug output handler
908 $debugInstance->output($message);
910 if ($doPrint === false) {
911 // Die here if not printed
916 if ($doPrint === true) {
919 // DO NOT REWRITE THIS TO app_die() !!!
926 * Converts e.g. a command from URL to a valid class by keeping out bad characters
928 * @param $str The string, what ever it is needs to be converted
929 * @return $className Generated class name
931 public function convertToClassName ($str) {
935 // Convert all dashes in underscores
936 $str = $this->convertDashesToUnderscores($str);
938 // Now use that underscores to get classname parts for hungarian style
939 foreach (explode('_', $str) as $strPart) {
940 // Make the class name part lower case and first upper case
941 $className .= ucfirst(strtolower($strPart));
949 * Converts dashes to underscores, e.g. useable for configuration entries
951 * @param $str The string with maybe dashes inside
952 * @return $str The converted string with no dashed, but underscores
954 public final function convertDashesToUnderscores ($str) {
956 $str = str_replace('-', '_', $str);
958 // Return converted string
963 * Marks up the code by adding e.g. line numbers
965 * @param $phpCode Unmarked PHP code
966 * @return $markedCode Marked PHP code
968 public function markupCode ($phpCode) {
973 $errorArray = error_get_last();
975 // Init the code with error message
976 if (is_array($errorArray)) {
978 $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>",
979 basename($errorArray['file']),
981 $errorArray['message'],
986 // Add line number to the code
987 foreach (explode("\n", $phpCode) as $lineNo => $code) {
989 $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
991 htmlentities($code, ENT_QUOTES)
1000 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1001 * beatiful for web-based front-ends. If null is given a message id
1002 * null_timestamp will be resolved and returned.
1004 * @param $timestamp Timestamp to prepare (filter) for display
1005 * @return $readable A readable timestamp
1007 public function doFilterFormatTimestamp ($timestamp) {
1008 // Default value to return
1011 // Is the timestamp null?
1012 if (is_null($timestamp)) {
1013 // Get a message string
1014 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1016 switch ($this->getLanguageInstance()->getLanguageCode()) {
1017 case 'de': // German format is a bit different to default
1018 // Split the GMT stamp up
1019 $dateTime = explode(' ', $timestamp );
1020 $dateArray = explode('-', $dateTime[0]);
1021 $timeArray = explode(':', $dateTime[1]);
1023 // Construct the timestamp
1024 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1034 default: // Default is pass-through
1035 $readable = $timestamp;
1045 * Filter a given number into a localized number
1047 * @param $value The raw value from e.g. database
1048 * @return $localized Localized value
1050 public function doFilterFormatNumber ($value) {
1051 // Generate it from config and localize dependencies
1052 switch ($this->getLanguageInstance()->getLanguageCode()) {
1053 case 'de': // German format is a bit different to default
1054 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1057 default: // US, etc.
1058 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1067 * "Getter" for databse entry
1069 * @return $entry An array with database entries
1070 * @throws NullPointerException If the database result is not found
1071 * @throws InvalidDatabaseResultException If the database result is invalid
1073 protected final function getDatabaseEntry () {
1074 // Is there an instance?
1075 if (is_null($this->getResultInstance())) {
1076 // Throw an exception here
1077 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1081 $this->getResultInstance()->rewind();
1083 // Do we have an entry?
1084 if ($this->getResultInstance()->valid() === false) {
1085 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1089 $this->getResultInstance()->next();
1092 $entry = $this->getResultInstance()->current();
1099 * Getter for field name
1101 * @param $fieldName Field name which we shall get
1102 * @return $fieldValue Field value from the user
1103 * @throws NullPointerException If the result instance is null
1105 public final function getField ($fieldName) {
1106 // Default field value
1109 // Get result instance
1110 $resultInstance = $this->getResultInstance();
1112 // Is this instance null?
1113 if (is_null($resultInstance)) {
1114 // Then the user instance is no longer valid (expired cookies?)
1115 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1118 // Get current array
1119 $fieldArray = $resultInstance->current();
1120 //* DEBUG: */ $this->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1122 // Does the field exist?
1123 if (isset($fieldArray[$fieldName])) {
1125 $fieldValue = $fieldArray[$fieldName];
1133 * Protected setter for user instance
1135 * @param $userInstance An instance of a user class
1138 protected final function setUserInstance (ManageableAccount $userInstance) {
1139 $this->userInstance = $userInstance;
1143 * Getter for user instance
1145 * @return $userInstance An instance of a user class
1147 public final function getUserInstance () {
1148 return $this->userInstance;
1152 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1154 * @param $controllerInstance An instance of the controller
1157 public final function setControllerInstance (Controller $controllerInstance) {
1158 $this->controllerInstance = $controllerInstance;
1162 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1164 * @return $controllerInstance An instance of the controller
1166 public final function getControllerInstance () {
1167 return $this->controllerInstance;
1171 * Flushs all pending updates to the database layer
1175 public function flushPendingUpdates () {
1176 // Get result instance
1177 $resultInstance = $this->getResultInstance();
1179 // Do we have data to update?
1180 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1181 // Get wrapper class name config entry
1182 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1184 // Create object instance
1185 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1187 // Yes, then send the whole result to the database layer
1188 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1193 * Outputs a deprecation warning to the developer.
1195 * @param $message The message we shall output to the developer
1197 * @todo Write a logging mechanism for productive mode
1199 public function deprecationWarning ($message) {
1200 // Is developer mode active?
1201 if (defined('DEVELOPER')) {
1202 // Debug instance is there?
1203 if (!is_null($this->getDebugInstance())) {
1204 // Output stub message
1205 $this->debugOutput($message);
1208 trigger_error($message . "<br />\n");
1211 // @TODO Finish this part!
1212 $this->partialStub('Developer mode inactive. Message:' . $message);
1217 * Checks wether the given PHP extension is loaded
1219 * @param $phpExtension The PHP extension we shall check
1220 * @return $isLoaded Wether the PHP extension is loaded
1222 public final function isPhpExtensionLoaded ($phpExtension) {
1224 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1231 * Setter for RNG instance
1233 * @param $rngInstance An instance of a random number generator (RNG)
1236 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1237 $this->rngInstance = $rngInstance;
1241 * Getter for RNG instance
1243 * @return $rngInstance An instance of a random number generator (RNG)
1245 public final function getRngInstance () {
1246 return $this->rngInstance;
1250 * Setter for Cryptable instance
1252 * @param $cryptoInstance An instance of a Cryptable class
1255 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1256 $this->cryptoInstance = $cryptoInstance;
1260 * Getter for Cryptable instance
1262 * @return $cryptoInstance An instance of a Cryptable class
1264 public final function getCryptoInstance () {
1265 return $this->cryptoInstance;
1269 * Setter for Iterator instance
1271 * @param $iteratorInstance An instance of an Iterator
1274 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1275 $this->iteratorInstance = $iteratorInstance;
1279 * Getter for Iterator instance
1281 * @return $iteratorInstance An instance of an Iterator
1283 public final function getIteratorInstance () {
1284 return $this->iteratorInstance;
1288 * "Getter" as a time() replacement but with milliseconds. You should use this
1289 * method instead of the encapsulated getimeofday() function.
1291 * @return $milliTime Timestamp with milliseconds
1293 public function getMilliTime () {
1294 // Get the time of day as float
1295 $milliTime = gettimeofday(true);
1302 * Idles (sleeps) for given milliseconds
1304 * @return $hasSlept Wether it goes fine
1306 public function idle ($milliSeconds) {
1307 // Sleep is fine by default
1310 // Idle so long with found function
1311 if (function_exists('time_sleep_until')) {
1312 // Get current time and add idle time
1313 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1315 // New PHP 5.1.0 function found
1316 $hasSlept = time_sleep_until($sleepUntil);
1318 // My Sun Station doesn't have that function even with latest PHP
1320 usleep($milliSeconds * 1000);
1328 * Setter for the list instance
1330 * @param $listInstance A list of Listable
1333 protected final function setListInstance (Listable $listInstance) {
1334 $this->listInstance = $listInstance;
1338 * Getter for the list instance
1340 * @return $listInstance A list of Listable
1342 protected final function getListInstance () {
1343 return $this->listInstance;
1347 * Setter for the menu instance
1349 * @param $menuInstance A RenderableMenu instance
1352 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1353 $this->menuInstance = $menuInstance;
1357 * Getter for the menu instance
1359 * @return $menuInstance A RenderableMenu instance
1361 protected final function getMenuInstance () {
1362 return $this->menuInstance;
1366 * Setter for image instance
1368 * @param $imageInstance An instance of an image
1371 public final function setImageInstance (BaseImage $imageInstance) {
1372 $this->imageInstance = $imageInstance;
1376 * Getter for image instance
1378 * @return $imageInstance An instance of an image
1380 public final function getImageInstance () {
1381 return $this->imageInstance;
1385 * Setter for stacker instance
1387 * @param $stackerInstance An instance of an stacker
1390 public final function setStackerInstance (Stackable $stackerInstance) {
1391 $this->stackerInstance = $stackerInstance;
1395 * Getter for stacker instance
1397 * @return $stackerInstance An instance of an stacker
1399 public final function getStackerInstance () {
1400 return $this->stackerInstance;
1404 * Setter for compressor instance
1406 * @param $compressorInstance An instance of an compressor
1409 public final function setCompressorInstance (Compressor $compressorInstance) {
1410 $this->compressorInstance = $compressorInstance;
1414 * Getter for compressor instance
1416 * @return $compressorInstance An instance of an compressor
1418 public final function getCompressorInstance () {
1419 return $this->compressorInstance;
1423 * Setter for Parseable instance
1425 * @param $parserInstance An instance of an Parseable
1428 public final function setParserInstance (Parseable $parserInstance) {
1429 $this->parserInstance = $parserInstance;
1433 * Getter for Parseable instance
1435 * @return $parserInstance An instance of an Parseable
1437 public final function getParserInstance () {
1438 return $this->parserInstance;
1442 * Setter for ProtocolHandler instance
1444 * @param $protocolInstance An instance of an ProtocolHandler
1447 public final function setProtocolInstance (ProtocolHandler $protocolInstance) {
1448 $this->protocolInstance = $protocolInstance;
1452 * Getter for ProtocolHandler instance
1454 * @return $protocolInstance An instance of an ProtocolHandler
1456 public final function getProtocolInstance () {
1457 return $this->protocolInstance;
1461 * Setter for BaseDatabaseWrapper instance
1463 * @param $wrapperInstance An instance of an BaseDatabaseWrapper
1466 public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
1467 $this->wrapperInstance = $wrapperInstance;
1471 * Getter for BaseDatabaseWrapper instance
1473 * @return $wrapperInstance An instance of an BaseDatabaseWrapper
1475 public final function getWrapperInstance () {
1476 return $this->wrapperInstance;
1480 * Setter for socket resource
1482 * @param $socketResource A valid socket resource
1485 public final function setSocketResource ($socketResource) {
1486 $this->socketResource = $socketResource;
1490 * Getter for socket resource
1492 * @return $socketResource A valid socket resource
1494 public function getSocketResource () {
1495 return $this->socketResource;
1499 * Setter for helper instance
1501 * @param $helperInstance An instance of a helper class
1504 protected final function setHelperInstance (Helper $helperInstance) {
1505 $this->helperInstance = $helperInstance;
1509 * Getter for helper instance
1511 * @return $helperInstance An instance of a helper class
1513 public final function getHelperInstance () {
1514 return $this->helperInstance;
1518 * Setter for a Sourceable instance
1520 * @param $sourceInstance The Sourceable instance
1523 protected final function setSourceInstance (Sourceable $sourceInstance) {
1524 $this->sourceInstance = $sourceInstance;
1528 * Getter for a Sourceable instance
1530 * @param $sourceInstance The Sourceable instance
1532 protected final function getSourceInstance () {
1533 return $this->sourceInstance;
1537 * Setter for raw package Data
1539 * @param $packageData Raw package Data
1542 public final function setPackageData (array $packageData) {
1543 $this->packageData = $packageData;
1547 * Getter for raw package Data
1549 * @return $packageData Raw package Data
1551 public function getPackageData () {
1552 return $this->packageData;
1556 * Converts a hexadecimal string, even with negative sign as first string to
1557 * a decimal number using BC functions.
1559 * This work is based on comment #86673 on php.net documentation page at:
1560 * <http://de.php.net/manual/en/function.dechex.php#86673>
1562 * @param $hex Hexadecimal string
1563 * @return $dec Decimal number
1565 function hex2dec ($hex) {
1566 // Convert to all lower-case
1567 $hex = strtolower($hex);
1569 // Hexadecimal->Decimal translation array
1589 // Detect sign (negative/positive numbers)
1591 if (substr($hex, 0, 1) == '-') {
1593 $hex = substr($hex, 1);
1596 // Decode the hexadecimal string into a decimal number
1598 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1599 $factor = $hexdec[substr($hex, $i, 1)];
1600 $dec = bcadd($dec, bcmul($factor, $e));
1603 // Return the decimal number
1604 return $sign . $dec;
1608 * Converts even very large decimal numbers, also with negative sign, to a
1609 * hexadecimal string.
1611 * This work is based on comment #97756 on php.net documentation page at:
1612 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1614 * @param $dec Decimal number, even with negative sign
1615 * @return $hex Hexadecimal string
1617 function dec2hex ($dec) {
1618 // Detect sign (negative/positive numbers)
1625 // Decimal->hexadecimal translation array
1626 $hexAlphabet = array(
1645 // Encode the decimal number into a hexadecimal string
1648 $hex = $hexAlphabet[($dec % 16)] . $hex;
1650 } while( $dec >= 1 );
1652 // Return the hexadecimal string
1653 return $sign . $hex;