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 - 2012 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 {
29 private $realClass = 'BaseFrameworkSystem';
32 * Instance of a request class
34 private $requestInstance = NULL;
37 * Instance of a response class
39 private $responseInstance = NULL;
42 * Search criteria instance
44 private $searchInstance = NULL;
47 * Update criteria instance
49 private $updateInstance = NULL;
52 * The file I/O instance for the template loader
54 private $fileIoInstance = NULL;
59 private $resolverInstance = NULL;
62 * Template engine instance
64 private $templateInstance = NULL;
67 * Database result instance
69 private $resultInstance = NULL;
72 * Instance for user class
74 private $userInstance = NULL;
77 * A controller instance
79 private $controllerInstance = NULL;
84 private $rngInstance = NULL;
87 * Instance of a crypto helper
89 private $cryptoInstance = NULL;
92 * Instance of an Iterator class
94 private $iteratorInstance = NULL;
97 * Instance of the list
99 private $listInstance = NULL;
104 private $menuInstance = NULL;
107 * Instance of the image
109 private $imageInstance = NULL;
112 * Instance of the stacker
114 private $stackerInstance = NULL;
117 * A Compressor instance
119 private $compressorInstance = NULL;
122 * A Parseable instance
124 private $parserInstance = NULL;
127 * A ProtocolHandler instance
129 private $protocolInstance = NULL;
132 * A database wrapper instance
134 private $databaseInstance = NULL;
137 * A helper instance for the form
139 private $helperInstance = NULL;
142 * An instance of a Sourceable class
144 private $sourceInstance = NULL;
147 * An instance of a InputStreamable class
149 private $inputStreamInstance = NULL;
152 * An instance of a OutputStreamable class
154 private $outputStreamInstance = NULL;
157 * Networkable handler instance
159 private $handlerInstance = NULL;
162 * Visitor handler instance
164 private $visitorInstance = NULL;
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 the real class name
463 * @param $realClass Class name (string)
466 public final function setRealClass ($realClass) {
468 $this->realClass = (string) $realClass;
472 * Setter for database result instance
474 * @param $resultInstance An instance of a database result class
476 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
478 protected final function setResultInstance (SearchableResult $resultInstance) {
479 $this->resultInstance = $resultInstance;
483 * Getter for database result instance
485 * @return $resultInstance An instance of a database result class
487 public final function getResultInstance () {
488 return $this->resultInstance;
492 * Setter for template engine instances
494 * @param $templateInstance An instance of a template engine class
497 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
498 $this->templateInstance = $templateInstance;
502 * Getter for template engine instances
504 * @return $templateInstance An instance of a template engine class
506 protected final function getTemplateInstance () {
507 return $this->templateInstance;
511 * Setter for search instance
513 * @param $searchInstance Searchable criteria instance
516 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
517 $this->searchInstance = $searchInstance;
521 * Getter for search instance
523 * @return $searchInstance Searchable criteria instance
525 public final function getSearchInstance () {
526 return $this->searchInstance;
530 * Setter for update instance
532 * @param $updateInstance Searchable criteria instance
535 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
536 $this->updateInstance = $updateInstance;
540 * Getter for update instance
542 * @return $updateInstance Updateable criteria instance
544 public final function getUpdateInstance () {
545 return $this->updateInstance;
549 * Setter for resolver instance
551 * @param $resolverInstance Instance of a command resolver class
554 public final function setResolverInstance (Resolver $resolverInstance) {
555 $this->resolverInstance = $resolverInstance;
559 * Getter for resolver instance
561 * @return $resolverInstance Instance of a command resolver class
563 public final function getResolverInstance () {
564 return $this->resolverInstance;
568 * Setter for language instance
570 * @param $configInstance The configuration instance which shall
571 * be FrameworkConfiguration
574 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
575 Registry::getRegistry()->addInstance('config', $configInstance);
579 * Getter for configuration instance
581 * @return $configInstance Configuration instance
583 public final function getConfigInstance () {
584 $configInstance = Registry::getRegistry()->getInstance('config');
585 return $configInstance;
589 * Setter for debug instance
591 * @param $debugInstance The instance for debug output class
594 public final function setDebugInstance (DebugMiddleware $debugInstance) {
595 Registry::getRegistry()->addInstance('debug', $debugInstance);
599 * Getter for debug instance
601 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
603 public final function getDebugInstance () {
604 // Get debug instance
605 $debugInstance = Registry::getRegistry()->getInstance('debug');
608 return $debugInstance;
612 * Setter for web output instance
614 * @param $webInstance The instance for web output class
617 public final function setWebOutputInstance (OutputStreamer $webInstance) {
618 Registry::getRegistry()->addInstance('web_output', $webInstance);
622 * Getter for web output instance
624 * @return $webOutputInstance - Instance to class WebOutput
626 public final function getWebOutputInstance () {
627 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
628 return $webOutputInstance;
632 * Setter for database instance
634 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
637 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
638 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
642 * Getter for database layer
644 * @return $databaseInstance The database layer instance
646 public final function getDatabaseInstance () {
648 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
651 return $databaseInstance;
655 * Setter for compressor channel
657 * @param $compressorInstance An instance of CompressorChannel
660 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
661 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
665 * Getter for compressor channel
667 * @return $compressorInstance The compressor channel
669 public final function getCompressorChannel () {
670 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
671 return $compressorInstance;
675 * Protected getter for a manageable application helper class
677 * @return $applicationInstance An instance of a manageable application helper class
679 protected final function getApplicationInstance () {
680 $applicationInstance = Registry::getRegistry()->getInstance('application');
681 return $applicationInstance;
685 * Setter for a manageable application helper class
687 * @param $applicationInstance An instance of a manageable application helper class
690 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
691 Registry::getRegistry()->addInstance('application', $applicationInstance);
695 * Setter for request instance
697 * @param $requestInstance An instance of a Requestable class
700 public final function setRequestInstance (Requestable $requestInstance) {
701 $this->requestInstance = $requestInstance;
705 * Getter for request instance
707 * @return $requestInstance An instance of a Requestable class
709 public final function getRequestInstance () {
710 return $this->requestInstance;
714 * Setter for response instance
716 * @param $responseInstance An instance of a Responseable class
719 public final function setResponseInstance (Responseable $responseInstance) {
720 $this->responseInstance = $responseInstance;
724 * Getter for response instance
726 * @return $responseInstance An instance of a Responseable class
728 public final function getResponseInstance () {
729 return $this->responseInstance;
733 * Private getter for language instance
735 * @return $langInstance An instance to the language sub-system
737 protected final function getLanguageInstance () {
738 $langInstance = Registry::getRegistry()->getInstance('language');
739 return $langInstance;
743 * Setter for language instance
745 * @param $langInstance An instance to the language sub-system
747 * @see LanguageSystem
749 public final function setLanguageInstance (ManageableLanguage $langInstance) {
750 Registry::getRegistry()->addInstance('language', $langInstance);
754 * Private getter for file IO instance
756 * @return $fileIoInstance An instance to the file I/O sub-system
758 protected final function getFileIoInstance () {
759 return $this->fileIoInstance;
763 * Setter for file I/O instance
765 * @param $fileIoInstance An instance to the file I/O sub-system
768 public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
769 $this->fileIoInstance = $fileIoInstance;
773 * Protected setter for user instance
775 * @param $userInstance An instance of a user class
778 protected final function setUserInstance (ManageableAccount $userInstance) {
779 $this->userInstance = $userInstance;
783 * Getter for user instance
785 * @return $userInstance An instance of a user class
787 public final function getUserInstance () {
788 return $this->userInstance;
792 * Setter for controller instance (this surely breaks a bit the MVC patterm)
794 * @param $controllerInstance An instance of the controller
797 public final function setControllerInstance (Controller $controllerInstance) {
798 $this->controllerInstance = $controllerInstance;
802 * Getter for controller instance (this surely breaks a bit the MVC patterm)
804 * @return $controllerInstance An instance of the controller
806 public final function getControllerInstance () {
807 return $this->controllerInstance;
811 * Setter for RNG instance
813 * @param $rngInstance An instance of a random number generator (RNG)
816 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
817 $this->rngInstance = $rngInstance;
821 * Getter for RNG instance
823 * @return $rngInstance An instance of a random number generator (RNG)
825 public final function getRngInstance () {
826 return $this->rngInstance;
830 * Setter for Cryptable instance
832 * @param $cryptoInstance An instance of a Cryptable class
835 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
836 $this->cryptoInstance = $cryptoInstance;
840 * Getter for Cryptable instance
842 * @return $cryptoInstance An instance of a Cryptable class
844 public final function getCryptoInstance () {
845 return $this->cryptoInstance;
849 * Setter for the list instance
851 * @param $listInstance A list of Listable
854 protected final function setListInstance (Listable $listInstance) {
855 $this->listInstance = $listInstance;
859 * Getter for the list instance
861 * @return $listInstance A list of Listable
863 protected final function getListInstance () {
864 return $this->listInstance;
868 * Setter for the menu instance
870 * @param $menuInstance A RenderableMenu instance
873 protected final function setMenuInstance (RenderableMenu $menuInstance) {
874 $this->menuInstance = $menuInstance;
878 * Getter for the menu instance
880 * @return $menuInstance A RenderableMenu instance
882 protected final function getMenuInstance () {
883 return $this->menuInstance;
887 * Setter for image instance
889 * @param $imageInstance An instance of an image
892 public final function setImageInstance (BaseImage $imageInstance) {
893 $this->imageInstance = $imageInstance;
897 * Getter for image instance
899 * @return $imageInstance An instance of an image
901 public final function getImageInstance () {
902 return $this->imageInstance;
906 * Setter for stacker instance
908 * @param $stackerInstance An instance of an stacker
911 public final function setStackerInstance (Stackable $stackerInstance) {
912 $this->stackerInstance = $stackerInstance;
916 * Getter for stacker instance
918 * @return $stackerInstance An instance of an stacker
920 public final function getStackerInstance () {
921 return $this->stackerInstance;
925 * Setter for compressor instance
927 * @param $compressorInstance An instance of an compressor
930 public final function setCompressorInstance (Compressor $compressorInstance) {
931 $this->compressorInstance = $compressorInstance;
935 * Getter for compressor instance
937 * @return $compressorInstance An instance of an compressor
939 public final function getCompressorInstance () {
940 return $this->compressorInstance;
944 * Setter for Parseable instance
946 * @param $parserInstance An instance of an Parseable
949 public final function setParserInstance (Parseable $parserInstance) {
950 $this->parserInstance = $parserInstance;
954 * Getter for Parseable instance
956 * @return $parserInstance An instance of an Parseable
958 public final function getParserInstance () {
959 return $this->parserInstance;
963 * Setter for ProtocolHandler instance
965 * @param $protocolInstance An instance of an ProtocolHandler
968 public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
969 $this->protocolInstance = $protocolInstance;
973 * Getter for ProtocolHandler instance
975 * @return $protocolInstance An instance of an ProtocolHandler
977 public final function getProtocolInstance () {
978 return $this->protocolInstance;
982 * Setter for BaseDatabaseWrapper instance
984 * @param $wrapperInstance An instance of an BaseDatabaseWrapper
987 public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
988 $this->wrapperInstance = $wrapperInstance;
992 * Getter for BaseDatabaseWrapper instance
994 * @return $wrapperInstance An instance of an BaseDatabaseWrapper
996 public final function getWrapperInstance () {
997 return $this->wrapperInstance;
1001 * Setter for socket resource
1003 * @param $socketResource A valid socket resource
1006 public final function setSocketResource ($socketResource) {
1007 //* NOISY-DEBUG: */ $this->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1008 $this->socketResource = $socketResource;
1012 * Getter for socket resource
1014 * @return $socketResource A valid socket resource
1016 public final function getSocketResource () {
1017 //* NOISY-DEBUG: */ $this->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1018 return $this->socketResource;
1022 * Setter for helper instance
1024 * @param $helperInstance An instance of a helper class
1027 protected final function setHelperInstance (Helper $helperInstance) {
1028 $this->helperInstance = $helperInstance;
1032 * Getter for helper instance
1034 * @return $helperInstance An instance of a helper class
1036 public final function getHelperInstance () {
1037 return $this->helperInstance;
1041 * Setter for a Sourceable instance
1043 * @param $sourceInstance The Sourceable instance
1046 protected final function setSourceInstance (Sourceable $sourceInstance) {
1047 $this->sourceInstance = $sourceInstance;
1051 * Getter for a Sourceable instance
1053 * @return $sourceInstance The Sourceable instance
1055 protected final function getSourceInstance () {
1056 return $this->sourceInstance;
1060 * Getter for a InputStreamable instance
1062 * @param $inputStreamInstance The InputStreamable instance
1064 protected final function getInputStreamInstance () {
1065 return $this->inputStreamInstance;
1069 * Setter for a InputStreamable instance
1071 * @param $inputStreamInstance The InputStreamable instance
1074 protected final function setInputStreamInstance (InputStreamable $inputStreamInstance) {
1075 $this->inputStreamInstance = $inputStreamInstance;
1079 * Getter for a OutputStreamable instance
1081 * @param $outputStreamInstance The OutputStreamable instance
1083 protected final function getOutputStreamInstance () {
1084 return $this->outputStreamInstance;
1088 * Setter for a OutputStreamable instance
1090 * @param $outputStreamInstance The OutputStreamable instance
1093 protected final function setOutputStreamInstance (OutputStreamable $outputStreamInstance) {
1094 $this->outputStreamInstance = $outputStreamInstance;
1098 * Setter for handler instance
1100 * @param $handlerInstance An instance of a Handleable class
1103 protected final function setHandlerInstance (Handleable $handlerInstance) {
1104 $this->handlerInstance = $handlerInstance;
1108 * Getter for handler instance
1110 * @return $handlerInstance A Networkable instance
1112 protected final function getHandlerInstance () {
1113 return $this->handlerInstance;
1117 * Setter for visitor instance
1119 * @param $visitorInstance A Visitor instance
1122 protected final function setVisitorInstance (Visitor $visitorInstance) {
1123 $this->visitorInstance = $visitorInstance;
1127 * Getter for visitor instance
1129 * @return $visitorInstance A Visitor instance
1131 protected final function getVisitorInstance () {
1132 return $this->visitorInstance;
1136 * Setter for raw package Data
1138 * @param $packageData Raw package Data
1141 public final function setPackageData (array $packageData) {
1142 $this->packageData = $packageData;
1146 * Getter for raw package Data
1148 * @return $packageData Raw package Data
1150 public function getPackageData () {
1151 return $this->packageData;
1156 * Setter for Iterator instance
1158 * @param $iteratorInstance An instance of an Iterator
1161 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1162 $this->iteratorInstance = $iteratorInstance;
1166 * Getter for Iterator instance
1168 * @return $iteratorInstance An instance of an Iterator
1170 public final function getIteratorInstance () {
1171 return $this->iteratorInstance;
1175 * Checks whether an object equals this object. You should overwrite this
1176 * method to implement own equality checks
1178 * @param $objectInstance An instance of a FrameworkInterface object
1179 * @return $equals Whether both objects equals
1181 public function equals (FrameworkInterface $objectInstance) {
1184 $this->__toString() == $objectInstance->__toString()
1186 $this->hashCode() == $objectInstance->hashCode()
1189 // Return the result
1194 * Generates a generic hash code of this class. You should really overwrite
1195 * this method with your own hash code generator code. But keep KISS in mind.
1197 * @return $hashCode A generic hash code respresenting this whole class
1199 public function hashCode () {
1201 return crc32($this->__toString());
1205 * Formats computer generated price values into human-understandable formats
1206 * with thousand and decimal separators.
1208 * @param $value The in computer format value for a price
1209 * @param $currency The currency symbol (use HTML-valid characters!)
1210 * @param $decNum Number of decimals after commata
1211 * @return $price The for the current language formated price string
1212 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1213 * thousands separator
1216 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1217 // Are all required attriutes set?
1218 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1219 // Throw an exception
1220 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1224 $value = (float) $value;
1226 // Reformat the US number
1227 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1229 // Return as string...
1234 * Appends a trailing slash to a string
1236 * @param $str A string (maybe) without trailing slash
1237 * @return $str A string with an auto-appended trailing slash
1239 public final function addMissingTrailingSlash ($str) {
1240 // Is there a trailing slash?
1241 if (substr($str, -1, 1) != '/') {
1245 // Return string with trailing slash
1250 * Prepare the template engine (WebTemplateEngine by default) for a given
1251 * application helper instance (ApplicationHelper by default).
1253 * @param $applicationInstance An application helper instance or
1254 * null if we shall use the default
1255 * @return $templateInstance The template engine instance
1256 * @throws NullPointerException If the discovered application
1257 * instance is still null
1259 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1260 // Is the application instance set?
1261 if (is_null($applicationInstance)) {
1262 // Get the current instance
1263 $applicationInstance = $this->getApplicationInstance();
1266 if (is_null($applicationInstance)) {
1267 // Thrown an exception
1268 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1272 // Initialize the template engine
1273 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1275 // Return the prepared instance
1276 return $templateInstance;
1280 * Debugs this instance by putting out it's full content
1282 * @param $message Optional message to show in debug output
1285 public final function debugInstance ($message = '') {
1286 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1287 restore_error_handler();
1292 // Is a message set?
1293 if (!empty($message)) {
1294 // Construct message
1295 $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
1298 // Generate the output
1299 $content .= sprintf("<pre>%s</pre>",
1302 print_r($this, true)
1308 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>",
1309 $this->__toString(),
1311 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1316 * Replaces control characters with printable output
1318 * @param $str String with control characters
1319 * @return $str Replaced string
1321 protected function replaceControlCharacters ($str) {
1324 chr(13), '[r]', str_replace(
1325 chr(10), '[n]', str_replace(
1335 * Output a partial stub message for the caller method
1337 * @param $message An optional message to display
1340 protected function partialStub ($message = '') {
1341 // Get the backtrace
1342 $backtrace = debug_backtrace();
1344 // Generate the class::method string
1345 $methodName = 'UnknownClass->unknownMethod';
1346 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1347 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1350 // Construct the full message
1351 $stubMessage = sprintf('[%s:] Partial stub!',
1355 // Is the extra message given?
1356 if (!empty($message)) {
1357 // Then add it as well
1358 $stubMessage .= sprintf(' Message: <span id="stub_message">%s</span>', $message);
1361 // Debug instance is there?
1362 if (!is_null($this->getDebugInstance())) {
1363 // Output stub message
1364 $this->debugOutput($stubMessage);
1367 trigger_error($stubMessage . '<br />' . chr(10));
1372 * Outputs a debug backtrace and stops further script execution
1374 * @param $message An optional message to output
1375 * @param $doExit Whether exit the program (true is default)
1378 public function debugBackTrace ($message = '', $doExit = true) {
1379 // Sorry, there is no other way getting this nice backtrace
1380 if (!empty($message)) {
1382 printf('Message: %s<br />' . chr(10), $message);
1386 debug_print_backtrace();
1390 if ($doExit === true) {
1396 * Outputs a debug message whether to debug instance (should be set!) or dies with or pints the message
1398 * @param $message Message we shall send out...
1399 * @param $doPrint Whether we shall print or die here which first is the default
1402 public function debugOutput ($message, $doPrint = true) {
1403 // Set debug instance to NULL
1404 $debugInstance = NULL;
1408 // Get debug instance
1409 $debugInstance = $this->getDebugInstance();
1410 } catch (NullPointerException $e) {
1411 // The debug instance is not set (yet)
1414 // Is the debug instance there?
1415 if (is_object($debugInstance)) {
1416 // Use debug output handler
1417 $debugInstance->output($message);
1419 if ($doPrint === false) {
1420 // Die here if not printed
1425 if ($doPrint === true) {
1426 // Are debug times enabled?
1427 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1429 print($this->getPrintableExecutionTime());
1433 print($message . chr(10));
1436 * BIG FAT NOTE: Do NEVER rewrite this to app_die(), this will
1437 * cause an endless loop.
1445 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1447 * @param $str The string, what ever it is needs to be converted
1448 * @return $className Generated class name
1450 public function convertToClassName ($str) {
1454 // Convert all dashes in underscores
1455 $str = $this->convertDashesToUnderscores($str);
1457 // Now use that underscores to get classname parts for hungarian style
1458 foreach (explode('_', $str) as $strPart) {
1459 // Make the class name part lower case and first upper case
1460 $className .= ucfirst(strtolower($strPart));
1463 // Return class name
1468 * Converts dashes to underscores, e.g. useable for configuration entries
1470 * @param $str The string with maybe dashes inside
1471 * @return $str The converted string with no dashed, but underscores
1473 public final function convertDashesToUnderscores ($str) {
1475 $str = str_replace('-', '_', $str);
1477 // Return converted string
1482 * Marks up the code by adding e.g. line numbers
1484 * @param $phpCode Unmarked PHP code
1485 * @return $markedCode Marked PHP code
1487 public function markupCode ($phpCode) {
1492 $errorArray = error_get_last();
1494 // Init the code with error message
1495 if (is_array($errorArray)) {
1497 $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>',
1498 basename($errorArray['file']),
1499 $errorArray['line'],
1500 $errorArray['message'],
1505 // Add line number to the code
1506 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1508 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1510 htmlentities($code, ENT_QUOTES)
1519 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1520 * beatiful for web-based front-ends. If null is given a message id
1521 * null_timestamp will be resolved and returned.
1523 * @param $timestamp Timestamp to prepare (filter) for display
1524 * @return $readable A readable timestamp
1526 public function doFilterFormatTimestamp ($timestamp) {
1527 // Default value to return
1530 // Is the timestamp null?
1531 if (is_null($timestamp)) {
1532 // Get a message string
1533 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1535 switch ($this->getLanguageInstance()->getLanguageCode()) {
1536 case 'de': // German format is a bit different to default
1537 // Split the GMT stamp up
1538 $dateTime = explode(' ', $timestamp );
1539 $dateArray = explode('-', $dateTime[0]);
1540 $timeArray = explode(':', $dateTime[1]);
1542 // Construct the timestamp
1543 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1553 default: // Default is pass-through
1554 $readable = $timestamp;
1564 * Filter a given number into a localized number
1566 * @param $value The raw value from e.g. database
1567 * @return $localized Localized value
1569 public function doFilterFormatNumber ($value) {
1570 // Generate it from config and localize dependencies
1571 switch ($this->getLanguageInstance()->getLanguageCode()) {
1572 case 'de': // German format is a bit different to default
1573 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1576 default: // US, etc.
1577 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1586 * "Getter" for databse entry
1588 * @return $entry An array with database entries
1589 * @throws NullPointerException If the database result is not found
1590 * @throws InvalidDatabaseResultException If the database result is invalid
1592 protected final function getDatabaseEntry () {
1593 // Is there an instance?
1594 if (is_null($this->getResultInstance())) {
1595 // Throw an exception here
1596 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1600 $this->getResultInstance()->rewind();
1602 // Do we have an entry?
1603 if ($this->getResultInstance()->valid() === false) {
1604 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1608 $this->getResultInstance()->next();
1611 $entry = $this->getResultInstance()->current();
1618 * Getter for field name
1620 * @param $fieldName Field name which we shall get
1621 * @return $fieldValue Field value from the user
1622 * @throws NullPointerException If the result instance is null
1624 public final function getField ($fieldName) {
1625 // Default field value
1628 // Get result instance
1629 $resultInstance = $this->getResultInstance();
1631 // Is this instance null?
1632 if (is_null($resultInstance)) {
1633 // Then the user instance is no longer valid (expired cookies?)
1634 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1637 // Get current array
1638 $fieldArray = $resultInstance->current();
1639 //* DEBUG: */ $this->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1641 // Convert dashes to underscore
1642 $fieldName = $this->convertDashesToUnderscores($fieldName);
1644 // Does the field exist?
1645 if (isset($fieldArray[$fieldName])) {
1647 $fieldValue = $fieldArray[$fieldName];
1649 // Missing field entry, may require debugging
1650 $this->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1658 * Flushs all pending updates to the database layer
1662 public function flushPendingUpdates () {
1663 // Get result instance
1664 $resultInstance = $this->getResultInstance();
1666 // Do we have data to update?
1667 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1668 // Get wrapper class name config entry
1669 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1671 // Create object instance
1672 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1674 // Yes, then send the whole result to the database layer
1675 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1680 * Outputs a deprecation warning to the developer.
1682 * @param $message The message we shall output to the developer
1684 * @todo Write a logging mechanism for productive mode
1686 public function deprecationWarning ($message) {
1687 // Is developer mode active?
1688 if (defined('DEVELOPER')) {
1689 // Debug instance is there?
1690 if (!is_null($this->getDebugInstance())) {
1691 // Output stub message
1692 $this->debugOutput($message);
1695 trigger_error($message . "<br />\n");
1698 // @TODO Finish this part!
1699 $this->partialStub('Developer mode inactive. Message:' . $message);
1704 * Checks whether the given PHP extension is loaded
1706 * @param $phpExtension The PHP extension we shall check
1707 * @return $isLoaded Whether the PHP extension is loaded
1709 public final function isPhpExtensionLoaded ($phpExtension) {
1711 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1718 * "Getter" as a time() replacement but with milliseconds. You should use this
1719 * method instead of the encapsulated getimeofday() function.
1721 * @return $milliTime Timestamp with milliseconds
1723 public function getMilliTime () {
1724 // Get the time of day as float
1725 $milliTime = gettimeofday(true);
1732 * Idles (sleeps) for given milliseconds
1734 * @return $hasSlept Whether it goes fine
1736 public function idle ($milliSeconds) {
1737 // Sleep is fine by default
1740 // Idle so long with found function
1741 if (function_exists('time_sleep_until')) {
1742 // Get current time and add idle time
1743 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1745 // New PHP 5.1.0 function found, ignore errors
1746 $hasSlept = @time_sleep_until($sleepUntil);
1749 * My Sun station doesn't have that function even with latest PHP
1752 usleep($milliSeconds * 1000);
1759 * Converts a hexadecimal string, even with negative sign as first string to
1760 * a decimal number using BC functions.
1762 * This work is based on comment #86673 on php.net documentation page at:
1763 * <http://de.php.net/manual/en/function.dechex.php#86673>
1765 * @param $hex Hexadecimal string
1766 * @return $dec Decimal number
1768 protected function hex2dec ($hex) {
1769 // Convert to all lower-case
1770 $hex = strtolower($hex);
1772 // Detect sign (negative/positive numbers)
1774 if (substr($hex, 0, 1) == '-') {
1776 $hex = substr($hex, 1);
1779 // Decode the hexadecimal string into a decimal number
1781 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1782 $factor = self::$hexdec[substr($hex, $i, 1)];
1783 $dec = bcadd($dec, bcmul($factor, $e));
1786 // Return the decimal number
1787 return $sign . $dec;
1791 * Converts even very large decimal numbers, also with negative sign, to a
1792 * hexadecimal string.
1794 * This work is based on comment #97756 on php.net documentation page at:
1795 * <http://de.php.net/manual/en/function.hexdec.php#97756>
1797 * @param $dec Decimal number, even with negative sign
1798 * @param $maxLength Optional maximum length of the string
1799 * @return $hex Hexadecimal string
1801 protected function dec2hex ($dec, $maxLength = 0) {
1802 // maxLength can be zero or devideable by 2
1803 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1805 // Detect sign (negative/positive numbers)
1812 // Encode the decimal number into a hexadecimal string
1815 $hex = self::$dechex[($dec % 16)] . $hex;
1817 } while ($dec >= 1);
1820 * We need hexadecimal strings with leading zeros if the length cannot
1823 if ($maxLength > 0) {
1824 // Prepend more zeros
1825 $hex = $this->prependStringToString($hex, '0', $maxLength);
1826 } elseif ((strlen($hex) % 2) != 0) {
1830 // Return the hexadecimal string
1831 return $sign . $hex;
1835 * Converts a ASCII string (0 to 255) into a decimal number.
1837 * @param $asc The ASCII string to be converted
1838 * @return $dec Decimal number
1840 protected function asc2dec ($asc) {
1841 // Convert it into a hexadecimal number
1842 $hex = bin2hex($asc);
1844 // And back into a decimal number
1845 $dec = $this->hex2dec($hex);
1852 * Converts a decimal number into an ASCII string.
1854 * @param $dec Decimal number
1855 * @return $asc An ASCII string
1857 protected function dec2asc ($dec) {
1858 // First convert the number into a hexadecimal string
1859 $hex = $this->dec2hex($dec);
1861 // Then convert it into the ASCII string
1862 $asc = $this->hex2asc($hex);
1869 * Converts a hexadecimal number into an ASCII string. Negative numbers
1872 * @param $hex Hexadecimal string
1873 * @return $asc An ASCII string
1875 protected function hex2asc ($hex) {
1876 // Check for length, it must be devideable by 2
1877 //* DEBUG: */ $this->debugOutput('hex='.$hex);
1878 assert((strlen($hex) % 2) == 0);
1882 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
1883 // Get the decimal number of the chunk
1884 $part = hexdec(substr($hex, $idx, 2));
1886 // Add it to the final string
1890 // Return the final string
1895 * Prepends a given string $prepend to $str with a given total length
1897 * @param $str Given original string which should be prepended
1898 * @param $prepend The string to prepend
1899 * @param $length Total length of the final string
1900 * @return $strFinal Final prepended string
1902 protected function prependStringToString ($str, $prepend, $length) {
1903 // Set final string to original string by default
1907 if (strlen($str) < $length) {
1908 // Difference between total length and length of original string
1909 $diff = $length - strlen($str);
1911 // Prepend the string
1912 $prepend = str_repeat($prepend, ($diff / strlen($prepend) + 1));
1914 // Make sure it will definedly fit
1915 assert(strlen($prepend) >= $diff);
1917 // Cut it a little down
1918 $prepend = substr($prepend, 0, $diff);
1919 //* DEBUG: */ $this->debugOutput('prepend('.strlen($prepend).')='.$prepend.',diff='.$diff.',length='.$length);
1921 // Construct the final prepended string
1922 $strFinal = $prepend . $str;
1930 * Checks whether the given encoded data was encoded with Base64
1932 * @param $encodedData Encoded data we shall check
1933 * @return $isBase64 Whether the encoded data is Base64
1935 protected function isBase64Encoded ($encodedData) {
1937 $isBase64 = (@base64_decode($encodedData, true) !== false);
1944 * "Getter" to get response/request type from analysis of the system.
1946 * @return $responseType Analyzed response type
1948 protected function getResponseTypeFromSystem () {
1949 // Default is console
1950 $responseType = 'console';
1952 // Is 'HTTP_HOST' set?
1953 if (isset($_SERVER['HTTP_HOST'])) {
1954 // Then it is a HTTP response/request
1955 $responseType = 'http';
1959 return $responseType;
1963 * Gets a cache key from Criteria instance
1965 * @param $criteriaInstance An instance of a Criteria class
1966 * @param $onlyKeys Only use these keys for a cache key
1967 * @return $cacheKey A cache key suitable for lookup/storage purposes
1969 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
1971 $cacheKey = sprintf("%s@%s",
1972 $this->__toString(),
1973 $criteriaInstance->getCacheKey($onlyKeys)
1977 //* NOISY-DEBUG: */ $this->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
1982 * Getter for startup time in miliseconds
1984 * @return $startupTime Startup time in miliseconds
1986 protected function getStartupTime () {
1987 return self::$startupTime;
1991 * "Getter" for a printable currently execution time in nice braces
1993 * @return $executionTime Current execution time in nice braces
1995 protected function getPrintableExecutionTime () {
1996 // Caculate the execution time
1997 $executionTime = microtime(true) - $this->getStartupTime();
1999 // Pack it in nice braces
2000 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2003 return $executionTime;
2007 * Hashes a given string with a simple but stronger hash function (no salts)
2009 * @param $str The string to be hashed
2010 * @return $hash The hash from string $str
2012 public function hashString ($str) {
2013 // Hash given string with (better secure) hasher
2014 $hash = mhash(MHASH_SHA256, $str);
2021 * Checks whether the given number is really a number (only chars 0-9).
2023 * @param $num A string consisting only chars between 0 and 9
2024 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2025 * @param $assertMismatch Whether to assert mismatches
2026 * @return $ret The (hopefully) secured numbered value
2028 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2029 // Filter all numbers out
2030 $ret = preg_replace('/[^0123456789]/', '', $num);
2033 if ($castValue === true) {
2034 // Cast to biggest numeric type
2035 $ret = (double) $ret;
2038 // Assert only if requested
2039 if ($assertMismatch === true) {
2040 // Has the whole value changed?
2041 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2049 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2051 * @param $num A string consisting only chars between 0 and 9
2052 * @param $assertMismatch Whether to assert mismatches
2053 * @return $ret The (hopefully) secured hext-numbered value
2055 public function hexval ($num, $assertMismatch = false) {
2056 // Filter all numbers out
2057 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2059 // Assert only if requested
2060 if ($assertMismatch === true) {
2061 // Has the whole value changed?
2062 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));