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 * Networkable handler instance
154 private $handlerInstance = null;
157 * The real class name
159 private $realClass = 'BaseFrameworkSystem';
162 * An instance of a database wrapper class
164 private $wrapperInstance = null;
167 * Thousands seperator
169 private $thousands = '.'; // German
174 private $decimals = ','; // German
179 private $socketResource = false;
184 private $packageData = array();
186 /***********************
187 * Exception codes.... *
188 ***********************/
190 // @todo Try to clean these constants up
191 const EXCEPTION_IS_NULL_POINTER = 0x001;
192 const EXCEPTION_IS_NO_OBJECT = 0x002;
193 const EXCEPTION_IS_NO_ARRAY = 0x003;
194 const EXCEPTION_MISSING_METHOD = 0x004;
195 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
196 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
197 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
198 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
199 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
200 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
201 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
202 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
203 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
204 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
205 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
206 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
207 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
208 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
209 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
210 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
211 const EXCEPTION_PATH_NOT_FOUND = 0x015;
212 const EXCEPTION_INVALID_PATH_NAME = 0x016;
213 const EXCEPTION_READ_PROTECED_PATH = 0x017;
214 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
215 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
216 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
217 const EXCEPTION_INVALID_RESOURCE = 0x01b;
218 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
219 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
220 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
221 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
222 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
223 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
224 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
225 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
226 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
227 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
228 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
229 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
230 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
231 const EXCEPTION_INVALID_STRING = 0x029;
232 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
233 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
234 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
235 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
236 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
237 const EXCEPTION_MISSING_ELEMENT = 0x030;
238 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
239 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
240 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
241 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
242 const EXCEPTION_FATAL_ERROR = 0x035;
243 const EXCEPTION_FILE_NOT_FOUND = 0x036;
244 const EXCEPTION_ASSERTION_FAILED = 0x037;
245 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
246 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
247 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x040;
249 // Hexadecimal->Decimal translation array
250 private static $hexdec = array(
269 // Decimal->hexadecimal translation array
270 private static $dechex = array(
290 * Protected super constructor
292 * @param $className Name of the class
295 protected function __construct ($className) {
297 $this->setRealClass($className);
299 // Set configuration instance if no registry ...
300 if (!$this instanceof Register) {
301 // ... because registries doesn't need to be configured
302 $this->setConfigInstance(FrameworkConfiguration::getInstance());
307 * Destructor reached...
311 public function __destruct() {
312 // Flush any updated entries to the database
313 $this->flushPendingUpdates();
315 // Is this object already destroyed?
316 if ($this->__toString() != 'DestructedObject') {
317 // Destroy all informations about this class but keep some text about it alive
318 $this->setRealClass('DestructedObject');
319 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
320 // Already destructed object
321 $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
329 * The __call() method where all non-implemented methods end up
331 * @param $methodName Name of the missing method
332 * @args $args Arguments passed to the method
335 public final function __call ($methodName, $args) {
336 // Implode all given arguments
340 $argsString = 'NULL';
341 } elseif (is_array($args)) {
342 // Some arguments are there
343 foreach ($args as $arg) {
345 $argsString .= $this->replaceControlCharacters($arg) . ' (' . gettype($arg);
347 // Add length if type is string
348 if (is_string($arg)) {
349 $argsString .= ', '.strlen($arg);
353 $argsString .= '), ';
357 if (substr($argsString, -2, 1) == ',') {
358 $argsString = substr($argsString, 0, -2);
361 // Invalid arguments!
362 $argsString = '!INVALID:' . gettype($args) . '!';
365 // Output stub message
366 $this->debugOutput(sprintf("[%s->%s] Stub! Args: %s",
377 * Getter for $realClass
379 * @return $realClass The name of the real class (not BaseFrameworkSystem)
381 public function __toString () {
382 return $this->realClass;
386 * Magic function to catch setting of missing but set class fields/attributes
388 * @param $name Name of the field/attribute
389 * @param $value Value to store
392 public final function __set ($name, $value) {
393 $this->debugBackTrace(sprintf("Tried to set a missing field. name=%s, value[%s]=%s",
401 * Magic function to catch getting of missing fields/attributes
403 * @param $name Name of the field/attribute
406 public final function __get ($name) {
407 $this->debugBackTrace(sprintf("Tried to get a missing field. name=%s",
413 * Magic function to catch unsetting of missing fields/attributes
415 * @param $name Name of the field/attribute
418 public final function __unset ($name) {
419 $this->debugBackTrace(sprintf("Tried to unset a missing field. name=%s",
425 * Setter for database result instance
427 * @param $resultInstance An instance of a database result class
429 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
431 protected final function setResultInstance (SearchableResult $resultInstance) {
432 $this->resultInstance = $resultInstance;
436 * Getter for database result instance
438 * @return $resultInstance An instance of a database result class
440 public final function getResultInstance () {
441 return $this->resultInstance;
445 * Setter for template engine instances
447 * @param $templateInstance An instance of a template engine class
450 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
451 $this->templateInstance = $templateInstance;
455 * Getter for template engine instances
457 * @return $templateInstance An instance of a template engine class
459 protected final function getTemplateInstance () {
460 return $this->templateInstance;
464 * Setter for search instance
466 * @param $searchInstance Searchable criteria instance
469 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
470 $this->searchInstance = $searchInstance;
474 * Getter for search instance
476 * @return $searchInstance Searchable criteria instance
478 public final function getSearchInstance () {
479 return $this->searchInstance;
483 * Setter for update instance
485 * @param $updateInstance Searchable criteria instance
488 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
489 $this->updateInstance = $updateInstance;
493 * Getter for update instance
495 * @return $updateInstance Updateable criteria instance
497 public final function getUpdateInstance () {
498 return $this->updateInstance;
502 * Setter for resolver instance
504 * @param $resolverInstance Instance of a command resolver class
507 public final function setResolverInstance (Resolver $resolverInstance) {
508 $this->resolverInstance = $resolverInstance;
512 * Getter for resolver instance
514 * @return $resolverInstance Instance of a command resolver class
516 public final function getResolverInstance () {
517 return $this->resolverInstance;
521 * Setter for language instance
523 * @param $configInstance The configuration instance which shall
524 * be FrameworkConfiguration
527 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
528 Registry::getRegistry()->addInstance('config', $configInstance);
532 * Getter for configuration instance
534 * @return $configInstance Configuration instance
536 public final function getConfigInstance () {
537 $configInstance = Registry::getRegistry()->getInstance('config');
538 return $configInstance;
542 * Setter for debug instance
544 * @param $debugInstance The instance for debug output class
547 public final function setDebugInstance (DebugMiddleware $debugInstance) {
548 Registry::getRegistry()->addInstance('debug', $debugInstance);
552 * Getter for debug instance
554 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
556 public final function getDebugInstance () {
557 // Get debug instance
558 $debugInstance = Registry::getRegistry()->getInstance('debug');
561 return $debugInstance;
565 * Setter for web output instance
567 * @param $webInstance The instance for web output class
570 public final function setWebOutputInstance (OutputStreamer $webInstance) {
571 Registry::getRegistry()->addInstance('web_output', $webInstance);
575 * Getter for web output instance
577 * @return $webOutputInstance - Instance to class WebOutput
579 public final function getWebOutputInstance () {
580 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
581 return $webOutputInstance;
585 * Setter for database instance
587 * @param $dbInstance The instance for the database connection (forced DatabaseConnection)
590 public final function setDatabaseInstance (DatabaseConnection $dbInstance) {
591 Registry::getRegistry()->addInstance('db_instance', $dbInstance);
595 * Getter for database layer
597 * @return $dbInstance The database layer instance
599 public final function getDatabaseInstance () {
601 $dbInstance = Registry::getRegistry()->getInstance('db_instance');
608 * Setter for compressor channel
610 * @param $compressorInstance An instance of CompressorChannel
613 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
614 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
618 * Getter for compressor channel
620 * @return $compressorInstance The compressor channel
622 public final function getCompressorChannel () {
623 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
624 return $compressorInstance;
628 * Protected getter for a manageable application helper class
630 * @return $applicationInstance An instance of a manageable application helper class
632 protected final function getApplicationInstance () {
633 $applicationInstance = Registry::getRegistry()->getInstance('application');
634 return $applicationInstance;
638 * Setter for a manageable application helper class
640 * @param $applicationInstance An instance of a manageable application helper class
643 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
644 Registry::getRegistry()->addInstance('application', $applicationInstance);
648 * Setter for request instance
650 * @param $requestInstance An instance of a Requestable class
653 public final function setRequestInstance (Requestable $requestInstance) {
654 $this->requestInstance = $requestInstance;
658 * Getter for request instance
660 * @return $requestInstance An instance of a Requestable class
662 public final function getRequestInstance () {
663 return $this->requestInstance;
667 * Setter for response instance
669 * @param $responseInstance An instance of a Responseable class
672 public final function setResponseInstance (Responseable $responseInstance) {
673 $this->responseInstance = $responseInstance;
677 * Getter for response instance
679 * @return $responseInstance An instance of a Responseable class
681 public final function getResponseInstance () {
682 return $this->responseInstance;
686 * Setter for the real class name
688 * @param $realClass Class name (string)
691 public final function setRealClass ($realClass) {
693 $realClass = (string) $realClass;
696 $this->realClass = $realClass;
700 * Checks wether an object equals this object. You should overwrite this
701 * method to implement own equality checks
703 * @param $objectInstance An instance of a FrameworkInterface object
704 * @return $equals Wether both objects equals
706 public function equals (FrameworkInterface $objectInstance) {
709 $this->__toString() == $objectInstance->__toString()
711 $this->hashCode() == $objectInstance->hashCode()
719 * Generates a generic hash code of this class. You should really overwrite
720 * this method with your own hash code generator code. But keep KISS in mind.
722 * @return $hashCode A generic hash code respresenting this whole class
724 public function hashCode () {
726 return crc32($this->__toString());
730 * Formats computer generated price values into human-understandable formats
731 * with thousand and decimal seperators.
733 * @param $value The in computer format value for a price
734 * @param $currency The currency symbol (use HTML-valid characters!)
735 * @param $decNum Number of decimals after commata
736 * @return $price The for the current language formated price string
737 * @throws MissingDecimalsThousandsSeperatorException If decimals or
738 * thousands seperator
741 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
742 // Are all required attriutes set?
743 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
744 // Throw an exception
745 throw new MissingDecimalsThousandsSeperatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
749 $value = (float) $value;
751 // Reformat the US number
752 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
754 // Return as string...
759 * Private getter for language instance
761 * @return $langInstance An instance to the language sub-system
763 protected final function getLanguageInstance () {
764 $langInstance = Registry::getRegistry()->getInstance('language');
765 return $langInstance;
769 * Setter for language instance
771 * @param $langInstance An instance to the language sub-system
773 * @see LanguageSystem
775 public final function setLanguageInstance (ManageableLanguage $langInstance) {
776 Registry::getRegistry()->addInstance('language', $langInstance);
780 * Appends a trailing slash to a string
782 * @param $str A string (maybe) without trailing slash
783 * @return $str A string with an auto-appended trailing slash
785 public final function addMissingTrailingSlash ($str) {
786 // Is there a trailing slash?
787 if (substr($str, -1, 1) != '/') {
791 // Return string with trailing slash
796 * Private getter for file IO instance
798 * @return $fileIoInstance An instance to the file I/O sub-system
800 protected final function getFileIoInstance () {
801 return $this->fileIoInstance;
805 * Setter for file I/O instance
807 * @param $fileIoInstance An instance to the file I/O sub-system
810 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
811 $this->fileIoInstance = $fileIoInstance;
815 * Prepare the template engine (WebTemplateEngine by default) for a given
816 * application helper instance (ApplicationHelper by default).
818 * @param $applicationInstance An application helper instance or
819 * null if we shall use the default
820 * @return $templateInstance The template engine instance
821 * @throws NullPointerException If the discovered application
822 * instance is still null
824 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = null) {
825 // Is the application instance set?
826 if (is_null($applicationInstance)) {
827 // Get the current instance
828 $applicationInstance = $this->getApplicationInstance();
831 if (is_null($applicationInstance)) {
832 // Thrown an exception
833 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
837 // Initialize the template engine
838 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
840 // Return the prepared instance
841 return $templateInstance;
845 * Debugs this instance by putting out it's full content
847 * @param $message Optional message to show in debug output
850 public final function debugInstance ($message = '') {
851 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
852 restore_error_handler();
858 if (!empty($message)) {
860 $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
863 // Generate the output
864 $content .= sprintf("<pre>%s</pre>",
873 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>",
876 ClassLoader::getInstance()->getPrintableIncludeList()
881 * Replaces control characters with printable output
883 * @param $str String with control characters
884 * @return $str Replaced string
886 protected function replaceControlCharacters ($str) {
889 "\r", '[r]', str_replace(
890 "\n", '[n]', str_replace(
900 * Output a partial stub message for the caller method
902 * @param $message An optional message to display
905 protected function partialStub ($message = '') {
907 $backtrace = debug_backtrace();
909 // Generate the class::method string
910 $methodName = 'UnknownClass->unknownMethod';
911 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
912 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
915 // Construct the full message
916 $stubMessage = sprintf("[%s:] Partial stub!",
920 // Is the extra message given?
921 if (!empty($message)) {
922 // Then add it as well
923 $stubMessage .= sprintf(" Message: <span id=\"stub_message\">%s</span>", $message);
926 // Debug instance is there?
927 if (!is_null($this->getDebugInstance())) {
928 // Output stub message
929 $this->debugOutput($stubMessage);
932 trigger_error($stubMessage . "<br />\n");
937 * Outputs a debug backtrace and stops further script execution
939 * @param $message An optional message to output
942 public function debugBackTrace ($message = '') {
943 // Sorry, there is no other way getting this nice backtrace
944 if (!empty($message)) {
946 printf("Message: %s<br />\n", $message);
950 debug_print_backtrace();
956 * Outputs a debug message wether to debug instance (should be set!) or dies with or pints the message
958 * @param $message Message we shall send out...
959 * @param $doPrint Wether we shall print or die here which first is the default
962 public function debugOutput ($message, $doPrint = true) {
963 // Get debug instance
964 $debugInstance = $this->getDebugInstance();
966 // Is the debug instance there?
967 if (is_object($debugInstance)) {
968 // Use debug output handler
969 $debugInstance->output($message);
971 if ($doPrint === false) {
972 // Die here if not printed
977 if ($doPrint === true) {
980 // DO NOT REWRITE THIS TO app_die() !!!
987 * Converts e.g. a command from URL to a valid class by keeping out bad characters
989 * @param $str The string, what ever it is needs to be converted
990 * @return $className Generated class name
992 public function convertToClassName ($str) {
996 // Convert all dashes in underscores
997 $str = $this->convertDashesToUnderscores($str);
999 // Now use that underscores to get classname parts for hungarian style
1000 foreach (explode('_', $str) as $strPart) {
1001 // Make the class name part lower case and first upper case
1002 $className .= ucfirst(strtolower($strPart));
1005 // Return class name
1010 * Converts dashes to underscores, e.g. useable for configuration entries
1012 * @param $str The string with maybe dashes inside
1013 * @return $str The converted string with no dashed, but underscores
1015 public final function convertDashesToUnderscores ($str) {
1017 $str = str_replace('-', '_', $str);
1019 // Return converted string
1024 * Marks up the code by adding e.g. line numbers
1026 * @param $phpCode Unmarked PHP code
1027 * @return $markedCode Marked PHP code
1029 public function markupCode ($phpCode) {
1034 $errorArray = error_get_last();
1036 // Init the code with error message
1037 if (is_array($errorArray)) {
1039 $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>",
1040 basename($errorArray['file']),
1041 $errorArray['line'],
1042 $errorArray['message'],
1047 // Add line number to the code
1048 foreach (explode("\n", $phpCode) as $lineNo => $code) {
1050 $markedCode .= sprintf("<span id=\"code_line\">%s</span>: %s\n",
1052 htmlentities($code, ENT_QUOTES)
1061 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1062 * beatiful for web-based front-ends. If null is given a message id
1063 * null_timestamp will be resolved and returned.
1065 * @param $timestamp Timestamp to prepare (filter) for display
1066 * @return $readable A readable timestamp
1068 public function doFilterFormatTimestamp ($timestamp) {
1069 // Default value to return
1072 // Is the timestamp null?
1073 if (is_null($timestamp)) {
1074 // Get a message string
1075 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1077 switch ($this->getLanguageInstance()->getLanguageCode()) {
1078 case 'de': // German format is a bit different to default
1079 // Split the GMT stamp up
1080 $dateTime = explode(' ', $timestamp );
1081 $dateArray = explode('-', $dateTime[0]);
1082 $timeArray = explode(':', $dateTime[1]);
1084 // Construct the timestamp
1085 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1095 default: // Default is pass-through
1096 $readable = $timestamp;
1106 * Filter a given number into a localized number
1108 * @param $value The raw value from e.g. database
1109 * @return $localized Localized value
1111 public function doFilterFormatNumber ($value) {
1112 // Generate it from config and localize dependencies
1113 switch ($this->getLanguageInstance()->getLanguageCode()) {
1114 case 'de': // German format is a bit different to default
1115 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1118 default: // US, etc.
1119 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1128 * "Getter" for databse entry
1130 * @return $entry An array with database entries
1131 * @throws NullPointerException If the database result is not found
1132 * @throws InvalidDatabaseResultException If the database result is invalid
1134 protected final function getDatabaseEntry () {
1135 // Is there an instance?
1136 if (is_null($this->getResultInstance())) {
1137 // Throw an exception here
1138 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1142 $this->getResultInstance()->rewind();
1144 // Do we have an entry?
1145 if ($this->getResultInstance()->valid() === false) {
1146 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1150 $this->getResultInstance()->next();
1153 $entry = $this->getResultInstance()->current();
1160 * Getter for field name
1162 * @param $fieldName Field name which we shall get
1163 * @return $fieldValue Field value from the user
1164 * @throws NullPointerException If the result instance is null
1166 public final function getField ($fieldName) {
1167 // Default field value
1170 // Get result instance
1171 $resultInstance = $this->getResultInstance();
1173 // Is this instance null?
1174 if (is_null($resultInstance)) {
1175 // Then the user instance is no longer valid (expired cookies?)
1176 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1179 // Get current array
1180 $fieldArray = $resultInstance->current();
1181 //* DEBUG: */ $this->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1183 // Does the field exist?
1184 if (isset($fieldArray[$fieldName])) {
1186 $fieldValue = $fieldArray[$fieldName];
1194 * Protected setter for user instance
1196 * @param $userInstance An instance of a user class
1199 protected final function setUserInstance (ManageableAccount $userInstance) {
1200 $this->userInstance = $userInstance;
1204 * Getter for user instance
1206 * @return $userInstance An instance of a user class
1208 public final function getUserInstance () {
1209 return $this->userInstance;
1213 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1215 * @param $controllerInstance An instance of the controller
1218 public final function setControllerInstance (Controller $controllerInstance) {
1219 $this->controllerInstance = $controllerInstance;
1223 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1225 * @return $controllerInstance An instance of the controller
1227 public final function getControllerInstance () {
1228 return $this->controllerInstance;
1232 * Flushs all pending updates to the database layer
1236 public function flushPendingUpdates () {
1237 // Get result instance
1238 $resultInstance = $this->getResultInstance();
1240 // Do we have data to update?
1241 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1242 // Get wrapper class name config entry
1243 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1245 // Create object instance
1246 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1248 // Yes, then send the whole result to the database layer
1249 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1254 * Outputs a deprecation warning to the developer.
1256 * @param $message The message we shall output to the developer
1258 * @todo Write a logging mechanism for productive mode
1260 public function deprecationWarning ($message) {
1261 // Is developer mode active?
1262 if (defined('DEVELOPER')) {
1263 // Debug instance is there?
1264 if (!is_null($this->getDebugInstance())) {
1265 // Output stub message
1266 $this->debugOutput($message);
1269 trigger_error($message . "<br />\n");
1272 // @TODO Finish this part!
1273 $this->partialStub('Developer mode inactive. Message:' . $message);
1278 * Checks wether the given PHP extension is loaded
1280 * @param $phpExtension The PHP extension we shall check
1281 * @return $isLoaded Wether the PHP extension is loaded
1283 public final function isPhpExtensionLoaded ($phpExtension) {
1285 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1292 * Setter for RNG instance
1294 * @param $rngInstance An instance of a random number generator (RNG)
1297 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1298 $this->rngInstance = $rngInstance;
1302 * Getter for RNG instance
1304 * @return $rngInstance An instance of a random number generator (RNG)
1306 public final function getRngInstance () {
1307 return $this->rngInstance;
1311 * Setter for Cryptable instance
1313 * @param $cryptoInstance An instance of a Cryptable class
1316 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1317 $this->cryptoInstance = $cryptoInstance;
1321 * Getter for Cryptable instance
1323 * @return $cryptoInstance An instance of a Cryptable class
1325 public final function getCryptoInstance () {
1326 return $this->cryptoInstance;
1330 * Setter for Iterator instance
1332 * @param $iteratorInstance An instance of an Iterator
1335 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1336 $this->iteratorInstance = $iteratorInstance;
1340 * Getter for Iterator instance
1342 * @return $iteratorInstance An instance of an Iterator
1344 public final function getIteratorInstance () {
1345 return $this->iteratorInstance;
1349 * "Getter" as a time() replacement but with milliseconds. You should use this
1350 * method instead of the encapsulated getimeofday() function.
1352 * @return $milliTime Timestamp with milliseconds
1354 public function getMilliTime () {
1355 // Get the time of day as float
1356 $milliTime = gettimeofday(true);
1363 * Idles (sleeps) for given milliseconds
1365 * @return $hasSlept Wether it goes fine
1367 public function idle ($milliSeconds) {
1368 // Sleep is fine by default
1371 // Idle so long with found function
1372 if (function_exists('time_sleep_until')) {
1373 // Get current time and add idle time
1374 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1376 // New PHP 5.1.0 function found, ignore errors
1377 $hasSlept = @time_sleep_until($sleepUntil);
1379 // My Sun Station doesn't have that function even with latest PHP
1381 usleep($milliSeconds * 1000);
1389 * Setter for the list instance
1391 * @param $listInstance A list of Listable
1394 protected final function setListInstance (Listable $listInstance) {
1395 $this->listInstance = $listInstance;
1399 * Getter for the list instance
1401 * @return $listInstance A list of Listable
1403 protected final function getListInstance () {
1404 return $this->listInstance;
1408 * Setter for the menu instance
1410 * @param $menuInstance A RenderableMenu instance
1413 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1414 $this->menuInstance = $menuInstance;
1418 * Getter for the menu instance
1420 * @return $menuInstance A RenderableMenu instance
1422 protected final function getMenuInstance () {
1423 return $this->menuInstance;
1427 * Setter for image instance
1429 * @param $imageInstance An instance of an image
1432 public final function setImageInstance (BaseImage $imageInstance) {
1433 $this->imageInstance = $imageInstance;
1437 * Getter for image instance
1439 * @return $imageInstance An instance of an image
1441 public final function getImageInstance () {
1442 return $this->imageInstance;
1446 * Setter for stacker instance
1448 * @param $stackerInstance An instance of an stacker
1451 public final function setStackerInstance (Stackable $stackerInstance) {
1452 $this->stackerInstance = $stackerInstance;
1456 * Getter for stacker instance
1458 * @return $stackerInstance An instance of an stacker
1460 public final function getStackerInstance () {
1461 return $this->stackerInstance;
1465 * Setter for compressor instance
1467 * @param $compressorInstance An instance of an compressor
1470 public final function setCompressorInstance (Compressor $compressorInstance) {
1471 $this->compressorInstance = $compressorInstance;
1475 * Getter for compressor instance
1477 * @return $compressorInstance An instance of an compressor
1479 public final function getCompressorInstance () {
1480 return $this->compressorInstance;
1484 * Setter for Parseable instance
1486 * @param $parserInstance An instance of an Parseable
1489 public final function setParserInstance (Parseable $parserInstance) {
1490 $this->parserInstance = $parserInstance;
1494 * Getter for Parseable instance
1496 * @return $parserInstance An instance of an Parseable
1498 public final function getParserInstance () {
1499 return $this->parserInstance;
1503 * Setter for ProtocolHandler instance
1505 * @param $protocolInstance An instance of an ProtocolHandler
1508 public final function setProtocolInstance (ProtocolHandler $protocolInstance) {
1509 $this->protocolInstance = $protocolInstance;
1513 * Getter for ProtocolHandler instance
1515 * @return $protocolInstance An instance of an ProtocolHandler
1517 public final function getProtocolInstance () {
1518 return $this->protocolInstance;
1522 * Setter for BaseDatabaseWrapper instance
1524 * @param $wrapperInstance An instance of an BaseDatabaseWrapper
1527 public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
1528 $this->wrapperInstance = $wrapperInstance;
1532 * Getter for BaseDatabaseWrapper instance
1534 * @return $wrapperInstance An instance of an BaseDatabaseWrapper
1536 public final function getWrapperInstance () {
1537 return $this->wrapperInstance;
1541 * Setter for socket resource
1543 * @param $socketResource A valid socket resource
1546 public final function setSocketResource ($socketResource) {
1547 $this->socketResource = $socketResource;
1551 * Getter for socket resource
1553 * @return $socketResource A valid socket resource
1555 public function getSocketResource () {
1556 return $this->socketResource;
1560 * Setter for helper instance
1562 * @param $helperInstance An instance of a helper class
1565 protected final function setHelperInstance (Helper $helperInstance) {
1566 $this->helperInstance = $helperInstance;
1570 * Getter for helper instance
1572 * @return $helperInstance An instance of a helper class
1574 public final function getHelperInstance () {
1575 return $this->helperInstance;
1579 * Setter for a Sourceable instance
1581 * @param $sourceInstance The Sourceable instance
1584 protected final function setSourceInstance (Sourceable $sourceInstance) {
1585 $this->sourceInstance = $sourceInstance;
1589 * Getter for a InputStreamable instance
1591 * @param $inputStreamInstance The InputStreamable instance
1593 protected final function getInputStreamInstance () {
1594 return $this->inputStreamInstance;
1598 * Setter for a InputStreamable instance
1600 * @param $inputStreamInstance The InputStreamable instance
1603 protected final function setInputStreamInstance (InputStreamable $inputStreamInstance) {
1604 $this->inputStreamInstance = $inputStreamInstance;
1608 * Getter for a OutputStreamable instance
1610 * @param $outputStreamInstance The OutputStreamable instance
1612 protected final function getOutputStreamInstance () {
1613 return $this->outputStreamInstance;
1617 * Setter for a OutputStreamable instance
1619 * @param $outputStreamInstance The OutputStreamable instance
1622 protected final function setOutputStreamInstance (OutputStreamable $outputStreamInstance) {
1623 $this->outputStreamInstance = $outputStreamInstance;
1627 * Setter for handler instance
1629 * @param $handlerInstance A Networkable instance
1632 protected final function setHandlerInstance (Networkable $handlerInstance) {
1633 $this->handlerInstance = $handlerInstance;
1637 * Getter for handler instance
1639 * @return $handlerInstance A Networkable instance
1641 protected final function getHandlerInstance () {
1642 return $this->handlerInstance;
1646 * Setter for raw package Data
1648 * @param $packageData Raw package Data
1651 public final function setPackageData (array $packageData) {
1652 $this->packageData = $packageData;
1656 * Getter for raw package Data
1658 * @return $packageData Raw package Data
1660 public function getPackageData () {
1661 return $this->packageData;
1665 * Converts a hexadecimal string, even with negative sign as first string to
1666 * a decimal number using BC functions.
1668 * This work is based on comment #86673 on php.net documentation page at:
1669 * <http://de.php.net/manual/en/function.dechex.php#86673>
1671 * @param $hex Hexadecimal string
1672 * @return $dec Decimal number
1674 protected function hex2dec ($hex) {
1675 // Convert to all lower-case
1676 $hex = strtolower($hex);
1678 // Detect sign (negative/positive numbers)
1680 if (substr($hex, 0, 1) == '-') {
1682 $hex = substr($hex, 1);
1685 // Decode the hexadecimal string into a decimal number
1687 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1688 $factor = self::$hexdec[substr($hex, $i, 1)];
1689 $dec = bcadd($dec, bcmul($factor, $e));
1692 // Return the decimal number
1693 return $sign . $dec;
1697 * Converts even very large decimal numbers, also with negative sign, to a
1698 * hexadecimal string.
1700 * This work is based on comment #97756 on php.net documentation page at:
1701 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1703 * @param $dec Decimal number, even with negative sign
1704 * @param $maxLength Optional maximum length of the string
1705 * @return $hex Hexadecimal string
1707 protected function dec2hex ($dec, $maxLength = 0) {
1708 // maxLength can be zero or devideable by 2
1709 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1711 // Detect sign (negative/positive numbers)
1718 // Encode the decimal number into a hexadecimal string
1721 $hex = self::$dechex[($dec % 16)] . $hex;
1723 } while ($dec >= 1);
1726 * We need hexadecimal strings with leading zeros if the length cannot
1729 if ($maxLength > 0) {
1730 // Prepend more zeros
1731 $hex = $this->prependStringToString($hex, '0', $maxLength);
1732 } elseif ((strlen($hex) % 2) != 0) {
1736 // Return the hexadecimal string
1737 return $sign . $hex;
1741 * Converts a ASCII string (0 to 255) into a decimal number.
1743 * @param $asc The ASCII string to be converted
1744 * @return $dec Decimal number
1746 protected function asc2dec ($asc) {
1747 // Convert it into a hexadecimal number
1748 $hex = bin2hex($asc);
1750 // And back into a decimal number
1751 $dec = $this->hex2dec($hex);
1758 * Converts a decimal number into an ASCII string.
1760 * @param $dec Decimal number
1761 * @return $asc An ASCII string
1763 protected function dec2asc ($dec) {
1764 // First convert the number into a hexadecimal string
1765 $hex = $this->dec2hex($dec);
1767 // Then convert it into the ASCII string
1768 $asc = $this->hex2asc($hex);
1775 * Converts a hexadecimal number into an ASCII string. Negative numbers
1778 * @param $hex Hexadecimal string
1779 * @return $asc An ASCII string
1781 protected function hex2asc ($hex) {
1782 // Check for length, it must be devideable by 2
1783 //* DEBUG: */ $this->debugOutput('hex='.$hex);
1784 assert((strlen($hex) % 2) == 0);
1788 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
1789 // Get the decimal number of the chunk
1790 $part = hexdec(substr($hex, $idx, 2));
1792 // Add it to the final string
1796 // Return the final string
1801 * Prepends a given string $prepend to $str with a given total length
1803 * @param $str Given original string which should be prepended
1804 * @param $prepend The string to prepend
1805 * @param $length Total length of the final string
1806 * @return $strFinal Final prepended string
1808 protected function prependStringToString ($str, $prepend, $length) {
1809 // Set final string to original string by default
1813 if (strlen($str) < $length) {
1814 // Difference between total length and length of original string
1815 $diff = $length - strlen($str);
1817 // Prepend the string
1818 $prepend = str_repeat($prepend, ($diff / strlen($prepend) + 1));
1820 // Make sure it will definedly fit
1821 assert(strlen($prepend) >= $diff);
1823 // Cut it a little down
1824 $prepend = substr($prepend, 0, $diff);
1825 //* DEBUG: */ $this->debugOutput('prepend('.strlen($prepend).')='.$prepend.',diff='.$diff.',length='.$length);
1827 // Construct the final prepended string
1828 $strFinal = $prepend . $str;
1836 * Checks wether the given encoded data was encoded with Base64
1838 * @param $encodedData Encoded data we shall check
1839 * @return $isBase64 Wether the encoded data is Base64
1841 protected function isBase64Encoded ($encodedData) {
1843 $isBase64 = (@base64_decode($encodedData, true) !== false);