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 * Visitor handler instance
159 private $visitorInstance = NULL;
162 * The real class name
164 private $realClass = 'BaseFrameworkSystem';
167 * An instance of a database wrapper class
169 private $wrapperInstance = NULL;
172 * Thousands separator
174 private $thousands = '.'; // German
179 private $decimals = ','; // German
184 private $socketResource = false;
189 private $packageData = array();
191 /***********************
192 * Exception codes.... *
193 ***********************/
195 // @todo Try to clean these constants up
196 const EXCEPTION_IS_NULL_POINTER = 0x001;
197 const EXCEPTION_IS_NO_OBJECT = 0x002;
198 const EXCEPTION_IS_NO_ARRAY = 0x003;
199 const EXCEPTION_MISSING_METHOD = 0x004;
200 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
201 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
202 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
203 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
204 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
205 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
206 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
207 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
208 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
209 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
210 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
211 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
212 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
213 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
214 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
215 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
216 const EXCEPTION_PATH_NOT_FOUND = 0x015;
217 const EXCEPTION_INVALID_PATH_NAME = 0x016;
218 const EXCEPTION_READ_PROTECED_PATH = 0x017;
219 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
220 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
221 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
222 const EXCEPTION_INVALID_RESOURCE = 0x01b;
223 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
224 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
225 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
226 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
227 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
228 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
229 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
230 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
231 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
232 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
233 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
234 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
235 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
236 const EXCEPTION_INVALID_STRING = 0x029;
237 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
238 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
239 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
240 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
241 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
242 const EXCEPTION_MISSING_ELEMENT = 0x030;
243 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
244 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
245 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
246 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
247 const EXCEPTION_FATAL_ERROR = 0x035;
248 const EXCEPTION_FILE_NOT_FOUND = 0x036;
249 const EXCEPTION_ASSERTION_FAILED = 0x037;
250 const EXCEPTION_FILE_CANNOT_BE_READ = 0x038;
251 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
252 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x040;
255 * Hexadecimal->Decimal translation array
257 private static $hexdec = array(
277 * Decimal->hexadecimal translation array
279 private static $dechex = array(
299 * Startup time in miliseconds
301 private static $startupTime = 0;
304 * Protected super constructor
306 * @param $className Name of the class
309 protected function __construct ($className) {
311 $this->setRealClass($className);
313 // Set configuration instance if no registry ...
314 if (!$this instanceof Register) {
315 // ... because registries doesn't need to be configured
316 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
319 // Is the startup time set? (0 cannot be true anymore)
320 if (self::$startupTime == 0) {
322 self::$startupTime = microtime(true);
327 * Destructor for all classes
331 public function __destruct() {
332 // Flush any updated entries to the database
333 $this->flushPendingUpdates();
335 // Is this object already destroyed?
336 if ($this->__toString() != 'DestructedObject') {
337 // Destroy all informations about this class but keep some text about it alive
338 $this->setRealClass('DestructedObject');
339 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
340 // Already destructed object
341 $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
349 * The __call() method where all non-implemented methods end up
351 * @param $methodName Name of the missing method
352 * @args $args Arguments passed to the method
355 public final function __call ($methodName, $args) {
356 // Implode all given arguments
360 $argsString = 'NULL';
361 } elseif (is_array($args)) {
362 // Some arguments are there
363 foreach ($args as $arg) {
364 // Add the value itself if not array. This prevents 'array to string conversion' message
365 if (is_array($arg)) {
366 $argsString .= 'Array';
371 // Add data about the argument
372 $argsString .= ' (' . gettype($arg);
374 if (is_string($arg)) {
375 // Add length for strings
376 $argsString .= ', '.strlen($arg);
377 } elseif (is_array($arg)) {
378 // .. or size if array
379 $argsString .= ', '.count($arg);
380 } elseif ($arg === true) {
381 // ... is boolean 'true'
382 $argsString .= ', true';
383 } elseif ($arg === false) {
384 // ... is boolean 'true'
385 $argsString .= ', false';
389 $argsString .= '), ';
393 if (substr($argsString, -2, 1) == ',') {
394 $argsString = substr($argsString, 0, -2);
397 // Invalid arguments!
398 $argsString = '!INVALID:' . gettype($args) . '!';
401 // Output stub message
402 $this->debugOutput(sprintf("[%s->%s] Stub! Args: %s",
413 * Getter for $realClass
415 * @return $realClass The name of the real class (not BaseFrameworkSystem)
417 public function __toString () {
418 return $this->realClass;
422 * Magic function to catch setting of missing but set class fields/attributes
424 * @param $name Name of the field/attribute
425 * @param $value Value to store
428 public final function __set ($name, $value) {
429 $this->debugBackTrace(sprintf("Tried to set a missing field. name=%s, value[%s]=%s",
437 * Magic function to catch getting of missing fields/attributes
439 * @param $name Name of the field/attribute
442 public final function __get ($name) {
443 $this->debugBackTrace(sprintf("Tried to get a missing field. name=%s",
449 * Magic function to catch unsetting of missing fields/attributes
451 * @param $name Name of the field/attribute
454 public final function __unset ($name) {
455 $this->debugBackTrace(sprintf("Tried to unset a missing field. name=%s",
461 * Setter for database result instance
463 * @param $resultInstance An instance of a database result class
465 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
467 protected final function setResultInstance (SearchableResult $resultInstance) {
468 $this->resultInstance = $resultInstance;
472 * Getter for database result instance
474 * @return $resultInstance An instance of a database result class
476 public final function getResultInstance () {
477 return $this->resultInstance;
481 * Setter for template engine instances
483 * @param $templateInstance An instance of a template engine class
486 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
487 $this->templateInstance = $templateInstance;
491 * Getter for template engine instances
493 * @return $templateInstance An instance of a template engine class
495 protected final function getTemplateInstance () {
496 return $this->templateInstance;
500 * Setter for search instance
502 * @param $searchInstance Searchable criteria instance
505 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
506 $this->searchInstance = $searchInstance;
510 * Getter for search instance
512 * @return $searchInstance Searchable criteria instance
514 public final function getSearchInstance () {
515 return $this->searchInstance;
519 * Setter for update instance
521 * @param $updateInstance Searchable criteria instance
524 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
525 $this->updateInstance = $updateInstance;
529 * Getter for update instance
531 * @return $updateInstance Updateable criteria instance
533 public final function getUpdateInstance () {
534 return $this->updateInstance;
538 * Setter for resolver instance
540 * @param $resolverInstance Instance of a command resolver class
543 public final function setResolverInstance (Resolver $resolverInstance) {
544 $this->resolverInstance = $resolverInstance;
548 * Getter for resolver instance
550 * @return $resolverInstance Instance of a command resolver class
552 public final function getResolverInstance () {
553 return $this->resolverInstance;
557 * Setter for language instance
559 * @param $configInstance The configuration instance which shall
560 * be FrameworkConfiguration
563 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
564 Registry::getRegistry()->addInstance('config', $configInstance);
568 * Getter for configuration instance
570 * @return $configInstance Configuration instance
572 public final function getConfigInstance () {
573 $configInstance = Registry::getRegistry()->getInstance('config');
574 return $configInstance;
578 * Setter for debug instance
580 * @param $debugInstance The instance for debug output class
583 public final function setDebugInstance (DebugMiddleware $debugInstance) {
584 Registry::getRegistry()->addInstance('debug', $debugInstance);
588 * Getter for debug instance
590 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
592 public final function getDebugInstance () {
593 // Get debug instance
594 $debugInstance = Registry::getRegistry()->getInstance('debug');
597 return $debugInstance;
601 * Setter for web output instance
603 * @param $webInstance The instance for web output class
606 public final function setWebOutputInstance (OutputStreamer $webInstance) {
607 Registry::getRegistry()->addInstance('web_output', $webInstance);
611 * Getter for web output instance
613 * @return $webOutputInstance - Instance to class WebOutput
615 public final function getWebOutputInstance () {
616 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
617 return $webOutputInstance;
621 * Setter for database instance
623 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
626 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
627 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
631 * Getter for database layer
633 * @return $databaseInstance The database layer instance
635 public final function getDatabaseInstance () {
637 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
640 return $databaseInstance;
644 * Setter for compressor channel
646 * @param $compressorInstance An instance of CompressorChannel
649 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
650 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
654 * Getter for compressor channel
656 * @return $compressorInstance The compressor channel
658 public final function getCompressorChannel () {
659 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
660 return $compressorInstance;
664 * Protected getter for a manageable application helper class
666 * @return $applicationInstance An instance of a manageable application helper class
668 protected final function getApplicationInstance () {
669 $applicationInstance = Registry::getRegistry()->getInstance('application');
670 return $applicationInstance;
674 * Setter for a manageable application helper class
676 * @param $applicationInstance An instance of a manageable application helper class
679 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
680 Registry::getRegistry()->addInstance('application', $applicationInstance);
684 * Setter for request instance
686 * @param $requestInstance An instance of a Requestable class
689 public final function setRequestInstance (Requestable $requestInstance) {
690 $this->requestInstance = $requestInstance;
694 * Getter for request instance
696 * @return $requestInstance An instance of a Requestable class
698 public final function getRequestInstance () {
699 return $this->requestInstance;
703 * Setter for response instance
705 * @param $responseInstance An instance of a Responseable class
708 public final function setResponseInstance (Responseable $responseInstance) {
709 $this->responseInstance = $responseInstance;
713 * Getter for response instance
715 * @return $responseInstance An instance of a Responseable class
717 public final function getResponseInstance () {
718 return $this->responseInstance;
722 * Setter for the real class name
724 * @param $realClass Class name (string)
727 public final function setRealClass ($realClass) {
729 $realClass = (string) $realClass;
732 $this->realClass = $realClass;
736 * Checks whether an object equals this object. You should overwrite this
737 * method to implement own equality checks
739 * @param $objectInstance An instance of a FrameworkInterface object
740 * @return $equals Whether both objects equals
742 public function equals (FrameworkInterface $objectInstance) {
745 $this->__toString() == $objectInstance->__toString()
747 $this->hashCode() == $objectInstance->hashCode()
755 * Generates a generic hash code of this class. You should really overwrite
756 * this method with your own hash code generator code. But keep KISS in mind.
758 * @return $hashCode A generic hash code respresenting this whole class
760 public function hashCode () {
762 return crc32($this->__toString());
766 * Formats computer generated price values into human-understandable formats
767 * with thousand and decimal separators.
769 * @param $value The in computer format value for a price
770 * @param $currency The currency symbol (use HTML-valid characters!)
771 * @param $decNum Number of decimals after commata
772 * @return $price The for the current language formated price string
773 * @throws MissingDecimalsThousandsSeparatorException If decimals or
774 * thousands separator
777 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
778 // Are all required attriutes set?
779 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
780 // Throw an exception
781 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
785 $value = (float) $value;
787 // Reformat the US number
788 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
790 // Return as string...
795 * Private getter for language instance
797 * @return $langInstance An instance to the language sub-system
799 protected final function getLanguageInstance () {
800 $langInstance = Registry::getRegistry()->getInstance('language');
801 return $langInstance;
805 * Setter for language instance
807 * @param $langInstance An instance to the language sub-system
809 * @see LanguageSystem
811 public final function setLanguageInstance (ManageableLanguage $langInstance) {
812 Registry::getRegistry()->addInstance('language', $langInstance);
816 * Appends a trailing slash to a string
818 * @param $str A string (maybe) without trailing slash
819 * @return $str A string with an auto-appended trailing slash
821 public final function addMissingTrailingSlash ($str) {
822 // Is there a trailing slash?
823 if (substr($str, -1, 1) != '/') {
827 // Return string with trailing slash
832 * Private getter for file IO instance
834 * @return $fileIoInstance An instance to the file I/O sub-system
836 protected final function getFileIoInstance () {
837 return $this->fileIoInstance;
841 * Setter for file I/O instance
843 * @param $fileIoInstance An instance to the file I/O sub-system
846 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
847 $this->fileIoInstance = $fileIoInstance;
851 * Prepare the template engine (WebTemplateEngine by default) for a given
852 * application helper instance (ApplicationHelper by default).
854 * @param $applicationInstance An application helper instance or
855 * null if we shall use the default
856 * @return $templateInstance The template engine instance
857 * @throws NullPointerException If the discovered application
858 * instance is still null
860 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
861 // Is the application instance set?
862 if (is_null($applicationInstance)) {
863 // Get the current instance
864 $applicationInstance = $this->getApplicationInstance();
867 if (is_null($applicationInstance)) {
868 // Thrown an exception
869 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
873 // Initialize the template engine
874 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
876 // Return the prepared instance
877 return $templateInstance;
881 * Debugs this instance by putting out it's full content
883 * @param $message Optional message to show in debug output
886 public final function debugInstance ($message = '') {
887 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
888 restore_error_handler();
894 if (!empty($message)) {
896 $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
899 // Generate the output
900 $content .= sprintf("<pre>%s</pre>",
909 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>",
912 ClassLoader::getSelfInstance()->getPrintableIncludeList()
917 * Replaces control characters with printable output
919 * @param $str String with control characters
920 * @return $str Replaced string
922 protected function replaceControlCharacters ($str) {
925 chr(13), '[r]', str_replace(
926 chr(10), '[n]', str_replace(
936 * Output a partial stub message for the caller method
938 * @param $message An optional message to display
941 protected function partialStub ($message = '') {
943 $backtrace = debug_backtrace();
945 // Generate the class::method string
946 $methodName = 'UnknownClass->unknownMethod';
947 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
948 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
951 // Construct the full message
952 $stubMessage = sprintf("[%s:] Partial stub!",
956 // Is the extra message given?
957 if (!empty($message)) {
958 // Then add it as well
959 $stubMessage .= sprintf(' Message: <span id="stub_message">%s</span>', $message);
962 // Debug instance is there?
963 if (!is_null($this->getDebugInstance())) {
964 // Output stub message
965 $this->debugOutput($stubMessage);
968 trigger_error($stubMessage . '<br />' + chr(10));
973 * Outputs a debug backtrace and stops further script execution
975 * @param $message An optional message to output
978 public function debugBackTrace ($message = '') {
979 // Sorry, there is no other way getting this nice backtrace
980 if (!empty($message)) {
982 printf("Message: %s<br />\n", $message);
986 debug_print_backtrace();
992 * Outputs a debug message whether to debug instance (should be set!) or dies with or pints the message
994 * @param $message Message we shall send out...
995 * @param $doPrint Whether we shall print or die here which first is the default
998 public function debugOutput ($message, $doPrint = true) {
999 // Get debug instance
1000 $debugInstance = $this->getDebugInstance();
1002 // Is the debug instance there?
1003 if (is_object($debugInstance)) {
1004 // Use debug output handler
1005 $debugInstance->output($message);
1007 if ($doPrint === false) {
1008 // Die here if not printed
1013 if ($doPrint === true) {
1014 // Are debug times enabled?
1015 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1017 print($this->getPrintableExecutionTime());
1021 print($message . chr(10));
1023 // DO NOT REWRITE THIS TO app_die() !!!
1030 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1032 * @param $str The string, what ever it is needs to be converted
1033 * @return $className Generated class name
1035 public function convertToClassName ($str) {
1039 // Convert all dashes in underscores
1040 $str = $this->convertDashesToUnderscores($str);
1042 // Now use that underscores to get classname parts for hungarian style
1043 foreach (explode('_', $str) as $strPart) {
1044 // Make the class name part lower case and first upper case
1045 $className .= ucfirst(strtolower($strPart));
1048 // Return class name
1053 * Converts dashes to underscores, e.g. useable for configuration entries
1055 * @param $str The string with maybe dashes inside
1056 * @return $str The converted string with no dashed, but underscores
1058 public final function convertDashesToUnderscores ($str) {
1060 $str = str_replace('-', '_', $str);
1062 // Return converted string
1067 * Marks up the code by adding e.g. line numbers
1069 * @param $phpCode Unmarked PHP code
1070 * @return $markedCode Marked PHP code
1072 public function markupCode ($phpCode) {
1077 $errorArray = error_get_last();
1079 // Init the code with error message
1080 if (is_array($errorArray)) {
1082 $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>',
1083 basename($errorArray['file']),
1084 $errorArray['line'],
1085 $errorArray['message'],
1090 // Add line number to the code
1091 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1093 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' + chr(10),
1095 htmlentities($code, ENT_QUOTES)
1104 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1105 * beatiful for web-based front-ends. If null is given a message id
1106 * null_timestamp will be resolved and returned.
1108 * @param $timestamp Timestamp to prepare (filter) for display
1109 * @return $readable A readable timestamp
1111 public function doFilterFormatTimestamp ($timestamp) {
1112 // Default value to return
1115 // Is the timestamp null?
1116 if (is_null($timestamp)) {
1117 // Get a message string
1118 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1120 switch ($this->getLanguageInstance()->getLanguageCode()) {
1121 case 'de': // German format is a bit different to default
1122 // Split the GMT stamp up
1123 $dateTime = explode(' ', $timestamp );
1124 $dateArray = explode('-', $dateTime[0]);
1125 $timeArray = explode(':', $dateTime[1]);
1127 // Construct the timestamp
1128 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1138 default: // Default is pass-through
1139 $readable = $timestamp;
1149 * Filter a given number into a localized number
1151 * @param $value The raw value from e.g. database
1152 * @return $localized Localized value
1154 public function doFilterFormatNumber ($value) {
1155 // Generate it from config and localize dependencies
1156 switch ($this->getLanguageInstance()->getLanguageCode()) {
1157 case 'de': // German format is a bit different to default
1158 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1161 default: // US, etc.
1162 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1171 * "Getter" for databse entry
1173 * @return $entry An array with database entries
1174 * @throws NullPointerException If the database result is not found
1175 * @throws InvalidDatabaseResultException If the database result is invalid
1177 protected final function getDatabaseEntry () {
1178 // Is there an instance?
1179 if (is_null($this->getResultInstance())) {
1180 // Throw an exception here
1181 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1185 $this->getResultInstance()->rewind();
1187 // Do we have an entry?
1188 if ($this->getResultInstance()->valid() === false) {
1189 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1193 $this->getResultInstance()->next();
1196 $entry = $this->getResultInstance()->current();
1203 * Getter for field name
1205 * @param $fieldName Field name which we shall get
1206 * @return $fieldValue Field value from the user
1207 * @throws NullPointerException If the result instance is null
1209 public final function getField ($fieldName) {
1210 // Default field value
1213 // Get result instance
1214 $resultInstance = $this->getResultInstance();
1216 // Is this instance null?
1217 if (is_null($resultInstance)) {
1218 // Then the user instance is no longer valid (expired cookies?)
1219 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1222 // Get current array
1223 $fieldArray = $resultInstance->current();
1224 //* DEBUG: */ $this->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1226 // Does the field exist?
1227 if (isset($fieldArray[$fieldName])) {
1229 $fieldValue = $fieldArray[$fieldName];
1237 * Protected setter for user instance
1239 * @param $userInstance An instance of a user class
1242 protected final function setUserInstance (ManageableAccount $userInstance) {
1243 $this->userInstance = $userInstance;
1247 * Getter for user instance
1249 * @return $userInstance An instance of a user class
1251 public final function getUserInstance () {
1252 return $this->userInstance;
1256 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1258 * @param $controllerInstance An instance of the controller
1261 public final function setControllerInstance (Controller $controllerInstance) {
1262 $this->controllerInstance = $controllerInstance;
1266 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1268 * @return $controllerInstance An instance of the controller
1270 public final function getControllerInstance () {
1271 return $this->controllerInstance;
1275 * Flushs all pending updates to the database layer
1279 public function flushPendingUpdates () {
1280 // Get result instance
1281 $resultInstance = $this->getResultInstance();
1283 // Do we have data to update?
1284 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1285 // Get wrapper class name config entry
1286 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1288 // Create object instance
1289 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1291 // Yes, then send the whole result to the database layer
1292 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1297 * Outputs a deprecation warning to the developer.
1299 * @param $message The message we shall output to the developer
1301 * @todo Write a logging mechanism for productive mode
1303 public function deprecationWarning ($message) {
1304 // Is developer mode active?
1305 if (defined('DEVELOPER')) {
1306 // Debug instance is there?
1307 if (!is_null($this->getDebugInstance())) {
1308 // Output stub message
1309 $this->debugOutput($message);
1312 trigger_error($message . "<br />\n");
1315 // @TODO Finish this part!
1316 $this->partialStub('Developer mode inactive. Message:' . $message);
1321 * Checks whether the given PHP extension is loaded
1323 * @param $phpExtension The PHP extension we shall check
1324 * @return $isLoaded Whether the PHP extension is loaded
1326 public final function isPhpExtensionLoaded ($phpExtension) {
1328 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1335 * Setter for RNG instance
1337 * @param $rngInstance An instance of a random number generator (RNG)
1340 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1341 $this->rngInstance = $rngInstance;
1345 * Getter for RNG instance
1347 * @return $rngInstance An instance of a random number generator (RNG)
1349 public final function getRngInstance () {
1350 return $this->rngInstance;
1354 * Setter for Cryptable instance
1356 * @param $cryptoInstance An instance of a Cryptable class
1359 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1360 $this->cryptoInstance = $cryptoInstance;
1364 * Getter for Cryptable instance
1366 * @return $cryptoInstance An instance of a Cryptable class
1368 public final function getCryptoInstance () {
1369 return $this->cryptoInstance;
1373 * Setter for Iterator instance
1375 * @param $iteratorInstance An instance of an Iterator
1378 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1379 $this->iteratorInstance = $iteratorInstance;
1383 * Getter for Iterator instance
1385 * @return $iteratorInstance An instance of an Iterator
1387 public final function getIteratorInstance () {
1388 return $this->iteratorInstance;
1392 * "Getter" as a time() replacement but with milliseconds. You should use this
1393 * method instead of the encapsulated getimeofday() function.
1395 * @return $milliTime Timestamp with milliseconds
1397 public function getMilliTime () {
1398 // Get the time of day as float
1399 $milliTime = gettimeofday(true);
1406 * Idles (sleeps) for given milliseconds
1408 * @return $hasSlept Whether it goes fine
1410 public function idle ($milliSeconds) {
1411 // Sleep is fine by default
1414 // Idle so long with found function
1415 if (function_exists('time_sleep_until')) {
1416 // Get current time and add idle time
1417 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1419 // New PHP 5.1.0 function found, ignore errors
1420 $hasSlept = @time_sleep_until($sleepUntil);
1423 * My Sun station doesn't have that function even with latest PHP
1426 usleep($milliSeconds * 1000);
1434 * Setter for the list instance
1436 * @param $listInstance A list of Listable
1439 protected final function setListInstance (Listable $listInstance) {
1440 $this->listInstance = $listInstance;
1444 * Getter for the list instance
1446 * @return $listInstance A list of Listable
1448 protected final function getListInstance () {
1449 return $this->listInstance;
1453 * Setter for the menu instance
1455 * @param $menuInstance A RenderableMenu instance
1458 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1459 $this->menuInstance = $menuInstance;
1463 * Getter for the menu instance
1465 * @return $menuInstance A RenderableMenu instance
1467 protected final function getMenuInstance () {
1468 return $this->menuInstance;
1472 * Setter for image instance
1474 * @param $imageInstance An instance of an image
1477 public final function setImageInstance (BaseImage $imageInstance) {
1478 $this->imageInstance = $imageInstance;
1482 * Getter for image instance
1484 * @return $imageInstance An instance of an image
1486 public final function getImageInstance () {
1487 return $this->imageInstance;
1491 * Setter for stacker instance
1493 * @param $stackerInstance An instance of an stacker
1496 public final function setStackerInstance (Stackable $stackerInstance) {
1497 $this->stackerInstance = $stackerInstance;
1501 * Getter for stacker instance
1503 * @return $stackerInstance An instance of an stacker
1505 public final function getStackerInstance () {
1506 return $this->stackerInstance;
1510 * Setter for compressor instance
1512 * @param $compressorInstance An instance of an compressor
1515 public final function setCompressorInstance (Compressor $compressorInstance) {
1516 $this->compressorInstance = $compressorInstance;
1520 * Getter for compressor instance
1522 * @return $compressorInstance An instance of an compressor
1524 public final function getCompressorInstance () {
1525 return $this->compressorInstance;
1529 * Setter for Parseable instance
1531 * @param $parserInstance An instance of an Parseable
1534 public final function setParserInstance (Parseable $parserInstance) {
1535 $this->parserInstance = $parserInstance;
1539 * Getter for Parseable instance
1541 * @return $parserInstance An instance of an Parseable
1543 public final function getParserInstance () {
1544 return $this->parserInstance;
1548 * Setter for ProtocolHandler instance
1550 * @param $protocolInstance An instance of an ProtocolHandler
1553 public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
1554 $this->protocolInstance = $protocolInstance;
1558 * Getter for ProtocolHandler instance
1560 * @return $protocolInstance An instance of an ProtocolHandler
1562 public final function getProtocolInstance () {
1563 return $this->protocolInstance;
1567 * Setter for BaseDatabaseWrapper instance
1569 * @param $wrapperInstance An instance of an BaseDatabaseWrapper
1572 public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
1573 $this->wrapperInstance = $wrapperInstance;
1577 * Getter for BaseDatabaseWrapper instance
1579 * @return $wrapperInstance An instance of an BaseDatabaseWrapper
1581 public final function getWrapperInstance () {
1582 return $this->wrapperInstance;
1586 * Setter for socket resource
1588 * @param $socketResource A valid socket resource
1591 public final function setSocketResource ($socketResource) {
1592 $this->socketResource = $socketResource;
1596 * Getter for socket resource
1598 * @return $socketResource A valid socket resource
1600 public function getSocketResource () {
1601 return $this->socketResource;
1605 * Setter for helper instance
1607 * @param $helperInstance An instance of a helper class
1610 protected final function setHelperInstance (Helper $helperInstance) {
1611 $this->helperInstance = $helperInstance;
1615 * Getter for helper instance
1617 * @return $helperInstance An instance of a helper class
1619 public final function getHelperInstance () {
1620 return $this->helperInstance;
1624 * Setter for a Sourceable instance
1626 * @param $sourceInstance The Sourceable instance
1629 protected final function setSourceInstance (Sourceable $sourceInstance) {
1630 $this->sourceInstance = $sourceInstance;
1634 * Getter for a Sourceable instance
1636 * @return $sourceInstance The Sourceable instance
1638 protected final function getSourceInstance () {
1639 return $this->sourceInstance;
1643 * Getter for a InputStreamable instance
1645 * @param $inputStreamInstance The InputStreamable instance
1647 protected final function getInputStreamInstance () {
1648 return $this->inputStreamInstance;
1652 * Setter for a InputStreamable instance
1654 * @param $inputStreamInstance The InputStreamable instance
1657 protected final function setInputStreamInstance (InputStreamable $inputStreamInstance) {
1658 $this->inputStreamInstance = $inputStreamInstance;
1662 * Getter for a OutputStreamable instance
1664 * @param $outputStreamInstance The OutputStreamable instance
1666 protected final function getOutputStreamInstance () {
1667 return $this->outputStreamInstance;
1671 * Setter for a OutputStreamable instance
1673 * @param $outputStreamInstance The OutputStreamable instance
1676 protected final function setOutputStreamInstance (OutputStreamable $outputStreamInstance) {
1677 $this->outputStreamInstance = $outputStreamInstance;
1681 * Setter for handler instance
1683 * @param $handlerInstance An instance of a Handleable class
1686 protected final function setHandlerInstance (Handleable $handlerInstance) {
1687 $this->handlerInstance = $handlerInstance;
1691 * Getter for handler instance
1693 * @return $handlerInstance A Networkable instance
1695 protected final function getHandlerInstance () {
1696 return $this->handlerInstance;
1700 * Setter for visitor instance
1702 * @param $visitorInstance A Visitor instance
1705 protected final function setVisitorInstance (Visitor $visitorInstance) {
1706 $this->visitorInstance = $visitorInstance;
1710 * Getter for visitor instance
1712 * @return $visitorInstance A Visitor instance
1714 protected final function getVisitorInstance () {
1715 return $this->visitorInstance;
1719 * Setter for raw package Data
1721 * @param $packageData Raw package Data
1724 public final function setPackageData (array $packageData) {
1725 $this->packageData = $packageData;
1729 * Getter for raw package Data
1731 * @return $packageData Raw package Data
1733 public function getPackageData () {
1734 return $this->packageData;
1738 * Converts a hexadecimal string, even with negative sign as first string to
1739 * a decimal number using BC functions.
1741 * This work is based on comment #86673 on php.net documentation page at:
1742 * <http://de.php.net/manual/en/function.dechex.php#86673>
1744 * @param $hex Hexadecimal string
1745 * @return $dec Decimal number
1747 protected function hex2dec ($hex) {
1748 // Convert to all lower-case
1749 $hex = strtolower($hex);
1751 // Detect sign (negative/positive numbers)
1753 if (substr($hex, 0, 1) == '-') {
1755 $hex = substr($hex, 1);
1758 // Decode the hexadecimal string into a decimal number
1760 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1761 $factor = self::$hexdec[substr($hex, $i, 1)];
1762 $dec = bcadd($dec, bcmul($factor, $e));
1765 // Return the decimal number
1766 return $sign . $dec;
1770 * Converts even very large decimal numbers, also with negative sign, to a
1771 * hexadecimal string.
1773 * This work is based on comment #97756 on php.net documentation page at:
1774 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1776 * @param $dec Decimal number, even with negative sign
1777 * @param $maxLength Optional maximum length of the string
1778 * @return $hex Hexadecimal string
1780 protected function dec2hex ($dec, $maxLength = 0) {
1781 // maxLength can be zero or devideable by 2
1782 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1784 // Detect sign (negative/positive numbers)
1791 // Encode the decimal number into a hexadecimal string
1794 $hex = self::$dechex[($dec % 16)] . $hex;
1796 } while ($dec >= 1);
1799 * We need hexadecimal strings with leading zeros if the length cannot
1802 if ($maxLength > 0) {
1803 // Prepend more zeros
1804 $hex = $this->prependStringToString($hex, '0', $maxLength);
1805 } elseif ((strlen($hex) % 2) != 0) {
1809 // Return the hexadecimal string
1810 return $sign . $hex;
1814 * Converts a ASCII string (0 to 255) into a decimal number.
1816 * @param $asc The ASCII string to be converted
1817 * @return $dec Decimal number
1819 protected function asc2dec ($asc) {
1820 // Convert it into a hexadecimal number
1821 $hex = bin2hex($asc);
1823 // And back into a decimal number
1824 $dec = $this->hex2dec($hex);
1831 * Converts a decimal number into an ASCII string.
1833 * @param $dec Decimal number
1834 * @return $asc An ASCII string
1836 protected function dec2asc ($dec) {
1837 // First convert the number into a hexadecimal string
1838 $hex = $this->dec2hex($dec);
1840 // Then convert it into the ASCII string
1841 $asc = $this->hex2asc($hex);
1848 * Converts a hexadecimal number into an ASCII string. Negative numbers
1851 * @param $hex Hexadecimal string
1852 * @return $asc An ASCII string
1854 protected function hex2asc ($hex) {
1855 // Check for length, it must be devideable by 2
1856 //* DEBUG: */ $this->debugOutput('hex='.$hex);
1857 assert((strlen($hex) % 2) == 0);
1861 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
1862 // Get the decimal number of the chunk
1863 $part = hexdec(substr($hex, $idx, 2));
1865 // Add it to the final string
1869 // Return the final string
1874 * Prepends a given string $prepend to $str with a given total length
1876 * @param $str Given original string which should be prepended
1877 * @param $prepend The string to prepend
1878 * @param $length Total length of the final string
1879 * @return $strFinal Final prepended string
1881 protected function prependStringToString ($str, $prepend, $length) {
1882 // Set final string to original string by default
1886 if (strlen($str) < $length) {
1887 // Difference between total length and length of original string
1888 $diff = $length - strlen($str);
1890 // Prepend the string
1891 $prepend = str_repeat($prepend, ($diff / strlen($prepend) + 1));
1893 // Make sure it will definedly fit
1894 assert(strlen($prepend) >= $diff);
1896 // Cut it a little down
1897 $prepend = substr($prepend, 0, $diff);
1898 //* DEBUG: */ $this->debugOutput('prepend('.strlen($prepend).')='.$prepend.',diff='.$diff.',length='.$length);
1900 // Construct the final prepended string
1901 $strFinal = $prepend . $str;
1909 * Checks whether the given encoded data was encoded with Base64
1911 * @param $encodedData Encoded data we shall check
1912 * @return $isBase64 Whether the encoded data is Base64
1914 protected function isBase64Encoded ($encodedData) {
1916 $isBase64 = (@base64_decode($encodedData, true) !== false);
1923 * "Getter" to get response/request type from analysis of the system.
1925 * @return $responseType Analyzed response type
1927 protected function getResponseTypeFromSystem () {
1928 // Default is console
1929 $responseType = 'console';
1931 // Is 'HTTP_HOST' set?
1932 if (isset($_SERVER['HTTP_HOST'])) {
1933 // Then it is a HTTP response/request
1934 $responseType = 'http';
1938 return $responseType;
1942 * Gets a cache key from Criteria instance
1944 * @param $criteriaInstance An instance of a Criteria class
1945 * @param $onlyKeys Only use these keys for a cache key
1946 * @return $cacheKey A cache key suitable for lookup/storage purposes
1948 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, $onlyKeys = array()) {
1950 $cacheKey = sprintf("%s@%s",
1951 $this->__toString(),
1952 $criteriaInstance->getCacheKey($onlyKeys)
1956 //* NOISY-DEBUG: */ $this->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
1961 * Getter for startup time in miliseconds
1963 * @return $startupTime Startup time in miliseconds
1965 protected function getStartupTime () {
1966 return self::$startupTime;
1970 * "Getter" for a printable currently execution time in nice braces
1972 * @return $executionTime Current execution time in nice braces
1974 protected function getPrintableExecutionTime () {
1975 // Caculate the execution time
1976 $executionTime = microtime(true) - $this->getStartupTime();
1978 // Pack it in nice braces
1979 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
1982 return $executionTime;
1986 * Hashes a given string with a simple but stronger hash function (no salts)
1988 * @param $str The string to be hashed
1989 * @return $hash The hash from string $str
1991 public function hashString ($str) {
1992 // Hash given string with (better secure) hasher
1993 $hash = mhash(MHASH_SHA256, $str);
2000 * Checks whether the given number is really a number (only chars 0-9).
2002 * @param $num A string consisting only chars between 0 and 9
2003 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2004 * @param $assertMismatch Whether to assert mismatches
2005 * @return $ret The (hopefully) secured numbered value
2007 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2008 // Filter all numbers out
2009 $ret = preg_replace('/[^0123456789]/', '', $num);
2012 if ($castValue === true) {
2013 // Cast to biggest numeric type
2014 $ret = (double) $ret;
2017 // Assert only if requested
2018 if ($assertMismatch === true) {
2019 // Has the whole value changed?
2020 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));