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@shipsimu.org>
8 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2015 Core Developer Team
9 * @license GNU GPL 3.0 or any newer version
10 * @link http://www.shipsimu.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 * Length of output from hash()
29 private static $hashLength = NULL;
34 private $realClass = 'BaseFrameworkSystem';
37 * Instance of a request class
39 private $requestInstance = NULL;
42 * Instance of a response class
44 private $responseInstance = NULL;
47 * Search criteria instance
49 private $searchInstance = NULL;
52 * Update criteria instance
54 private $updateInstance = NULL;
57 * The file I/O instance for the template loader
59 private $fileIoInstance = NULL;
64 private $resolverInstance = NULL;
67 * Template engine instance
69 private $templateInstance = NULL;
72 * Database result instance
74 private $resultInstance = NULL;
77 * Instance for user class
79 private $userInstance = NULL;
82 * A controller instance
84 private $controllerInstance = NULL;
89 private $rngInstance = NULL;
92 * Instance of a crypto helper
94 private $cryptoInstance = NULL;
97 * Instance of an Iterator class
99 private $iteratorInstance = NULL;
102 * Instance of the list
104 private $listInstance = NULL;
109 private $menuInstance = NULL;
112 * Instance of the image
114 private $imageInstance = NULL;
117 * Instance of the stacker
119 private $stackInstance = NULL;
122 * A Compressor instance
124 private $compressorInstance = NULL;
127 * A Parseable instance
129 private $parserInstance = NULL;
132 * A HandleableProtocol instance
134 private $protocolInstance = NULL;
137 * A database wrapper instance
139 private $databaseInstance = NULL;
142 * A helper instance for the form
144 private $helperInstance = NULL;
147 * An instance of a Source class
149 private $sourceInstance = NULL;
152 * An instance of a UrlSource class
154 private $urlSourceInstance = NULL;
157 * An instance of a InputStream class
159 private $inputStreamInstance = NULL;
162 * An instance of a OutputStream class
164 private $outputStreamInstance = NULL;
167 * Networkable handler instance
169 private $handlerInstance = NULL;
172 * Visitor handler instance
174 private $visitorInstance = NULL;
179 private $dhtInstance = NULL;
182 * An instance of a database wrapper class
184 private $wrapperInstance = NULL;
187 * An instance of a file I/O pointer class (not handler)
189 private $pointerInstance = NULL;
192 * An instance of an Indexable class
194 private $indexInstance = NULL;
197 * An instance of a Block class
199 private $blockInstance = NULL;
204 private $minableInstance = NULL;
207 * A FrameworkDirectory instance
209 private $directoryInstance = NULL;
214 private $listenerInstance = NULL;
217 * An instance of a communicator
219 private $communicatorInstance = NULL;
222 * Thousands separator
224 private $thousands = '.'; // German
229 private $decimals = ','; // German
234 private $socketResource = FALSE;
237 * Regular expression to use for validation
239 private $regularExpression = '';
244 private $packageData = array();
249 private $genericArray = array();
254 private $commandName = '';
259 private $controllerName = '';
262 * Array with bitmasks and such for pack/unpack methods to support both
263 * 32-bit and 64-bit systems
265 private $packingData = array(
268 'left' => 0xffff0000,
269 'right' => 0x0000ffff,
275 'left' => 0xffffffff00000000,
276 'right' => 0x00000000ffffffff,
283 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
285 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
287 private $archArrayElement = FALSE;
289 /***********************
290 * Exception codes.... *
291 ***********************/
293 // @todo Try to clean these constants up
294 const EXCEPTION_IS_NULL_POINTER = 0x001;
295 const EXCEPTION_IS_NO_OBJECT = 0x002;
296 const EXCEPTION_IS_NO_ARRAY = 0x003;
297 const EXCEPTION_MISSING_METHOD = 0x004;
298 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
299 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
300 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
301 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
302 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
303 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
304 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
305 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
306 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
307 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
308 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
309 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
310 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
311 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
312 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
313 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
314 const EXCEPTION_PATH_NOT_FOUND = 0x015;
315 const EXCEPTION_INVALID_PATH_NAME = 0x016;
316 const EXCEPTION_READ_PROTECED_PATH = 0x017;
317 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
318 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
319 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
320 const EXCEPTION_INVALID_RESOURCE = 0x01b;
321 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
322 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
323 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
324 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
325 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
326 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
327 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
328 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
329 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
330 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
331 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
332 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
333 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
334 const EXCEPTION_INVALID_STRING = 0x029;
335 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
336 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
337 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
338 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
339 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
340 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
341 const EXCEPTION_MISSING_ELEMENT = 0x030;
342 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
343 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
344 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
345 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
346 const EXCEPTION_FATAL_ERROR = 0x035;
347 const EXCEPTION_FILE_NOT_FOUND = 0x036;
348 const EXCEPTION_ASSERTION_FAILED = 0x037;
349 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
350 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
351 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
352 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03b;
353 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03c;
356 * Hexadecimal->Decimal translation array
358 private static $hexdec = array(
378 * Decimal->hexadecimal translation array
380 private static $dechex = array(
400 * Startup time in miliseconds
402 private static $startupTime = 0;
405 * Protected super constructor
407 * @param $className Name of the class
410 protected function __construct ($className) {
412 $this->setRealClass($className);
414 // Set configuration instance if no registry ...
415 if (!$this instanceof Register) {
416 // ... because registries doesn't need to be configured
417 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
420 // Is the startup time set? (0 cannot be TRUE anymore)
421 if (self::$startupTime == 0) {
423 self::$startupTime = microtime(TRUE);
427 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
431 * Destructor for all classes
435 public function __destruct () {
436 // Flush any updated entries to the database
437 $this->flushPendingUpdates();
439 // Is this object already destroyed?
440 if ($this->__toString() != 'DestructedObject') {
441 // Destroy all informations about this class but keep some text about it alive
442 $this->setRealClass('DestructedObject');
443 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
444 // Already destructed object
445 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
450 // Do not call this twice
451 trigger_error(__METHOD__ . ': Called twice.');
457 * The __call() method where all non-implemented methods end up
459 * @param $methodName Name of the missing method
460 * @args $args Arguments passed to the method
463 public final function __call ($methodName, $args) {
464 return self::__callStatic($methodName, $args);
468 * The __callStatic() method where all non-implemented static methods end up
470 * @param $methodName Name of the missing method
471 * @args $args Arguments passed to the method
474 public static final function __callStatic ($methodName, $args) {
475 // Init argument string
478 // Is it NULL, empty or an array?
479 if (is_null($args)) {
481 $argsString = 'NULL';
482 } elseif (empty($args)) {
484 $argsString = '(empty)';
485 } elseif (is_array($args)) {
486 // Some arguments are there
487 foreach ($args as $arg) {
488 // Add the value itself if not array. This prevents 'array to string conversion' message
489 if (is_array($arg)) {
490 $argsString .= 'Array';
495 // Add data about the argument
496 $argsString .= ' (' . gettype($arg);
498 if (is_string($arg)) {
499 // Add length for strings
500 $argsString .= ', ' . strlen($arg);
501 } elseif (is_array($arg)) {
502 // .. or size if array
503 $argsString .= ', ' . count($arg);
504 } elseif ($arg === TRUE) {
505 // ... is boolean 'TRUE'
506 $argsString .= ', TRUE';
507 } elseif ($arg === FALSE) {
508 // ... is boolean 'FALSE'
509 $argsString .= ', FALSE';
513 $argsString .= '), ';
517 if (substr($argsString, -2, 1) == ',') {
518 $argsString = substr($argsString, 0, -2);
521 // Invalid arguments!
522 $argsString = '!INVALID:' . gettype($args) . '!';
525 // Output stub message
526 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
527 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
537 * Getter for $realClass
539 * @return $realClass The name of the real class (not BaseFrameworkSystem)
541 public function __toString () {
542 return $this->realClass;
546 * Magic method to catch setting of missing but set class fields/attributes
548 * @param $name Name of the field/attribute
549 * @param $value Value to store
552 public final function __set ($name, $value) {
553 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
556 print_r($value, TRUE)
561 * Magic method to catch getting of missing fields/attributes
563 * @param $name Name of the field/attribute
566 public final function __get ($name) {
567 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
573 * Magic method to catch unsetting of missing fields/attributes
575 * @param $name Name of the field/attribute
578 public final function __unset ($name) {
579 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
585 * Magic method to catch object serialization
587 * @return $unsupported Unsupported method
588 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
590 public final function __sleep () {
591 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
595 * Magic method to catch object deserialization
597 * @return $unsupported Unsupported method
598 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
600 public final function __wakeup () {
601 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
605 * Magic method to catch calls when an object instance is called
607 * @return $unsupported Unsupported method
608 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
610 public final function __invoke () {
611 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
615 * Setter for the real class name
617 * @param $realClass Class name (string)
620 public final function setRealClass ($realClass) {
622 $this->realClass = (string) $realClass;
626 * Setter for database result instance
628 * @param $resultInstance An instance of a database result class
630 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
632 protected final function setResultInstance (SearchableResult $resultInstance) {
633 $this->resultInstance = $resultInstance;
637 * Getter for database result instance
639 * @return $resultInstance An instance of a database result class
641 public final function getResultInstance () {
642 return $this->resultInstance;
646 * Setter for template engine instances
648 * @param $templateInstance An instance of a template engine class
651 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
652 $this->templateInstance = $templateInstance;
656 * Getter for template engine instances
658 * @return $templateInstance An instance of a template engine class
660 protected final function getTemplateInstance () {
661 return $this->templateInstance;
665 * Setter for search instance
667 * @param $searchInstance Searchable criteria instance
670 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
671 $this->searchInstance = $searchInstance;
675 * Getter for search instance
677 * @return $searchInstance Searchable criteria instance
679 public final function getSearchInstance () {
680 return $this->searchInstance;
684 * Setter for update instance
686 * @param $updateInstance Searchable criteria instance
689 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
690 $this->updateInstance = $updateInstance;
694 * Getter for update instance
696 * @return $updateInstance Updateable criteria instance
698 public final function getUpdateInstance () {
699 return $this->updateInstance;
703 * Setter for resolver instance
705 * @param $resolverInstance Instance of a command resolver class
708 public final function setResolverInstance (Resolver $resolverInstance) {
709 $this->resolverInstance = $resolverInstance;
713 * Getter for resolver instance
715 * @return $resolverInstance Instance of a command resolver class
717 public final function getResolverInstance () {
718 return $this->resolverInstance;
722 * Setter for language instance
724 * @param $configInstance The configuration instance which shall
725 * be FrameworkConfiguration
728 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
729 Registry::getRegistry()->addInstance('config', $configInstance);
733 * Getter for configuration instance
735 * @return $configInstance Configuration instance
737 public final function getConfigInstance () {
738 $configInstance = Registry::getRegistry()->getInstance('config');
739 return $configInstance;
743 * Setter for debug instance
745 * @param $debugInstance The instance for debug output class
748 public final function setDebugInstance (DebugMiddleware $debugInstance) {
749 Registry::getRegistry()->addInstance('debug', $debugInstance);
753 * Getter for debug instance
755 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
757 public final function getDebugInstance () {
758 // Get debug instance
759 $debugInstance = Registry::getRegistry()->getInstance('debug');
762 return $debugInstance;
766 * Setter for web output instance
768 * @param $webInstance The instance for web output class
771 public final function setWebOutputInstance (OutputStreamer $webInstance) {
772 Registry::getRegistry()->addInstance('web_output', $webInstance);
776 * Getter for web output instance
778 * @return $webOutputInstance - Instance to class WebOutput
780 public final function getWebOutputInstance () {
781 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
782 return $webOutputInstance;
786 * Setter for database instance
788 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
791 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
792 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
796 * Getter for database layer
798 * @return $databaseInstance The database layer instance
800 public final function getDatabaseInstance () {
802 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
805 return $databaseInstance;
809 * Setter for compressor channel
811 * @param $compressorInstance An instance of CompressorChannel
814 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
815 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
819 * Getter for compressor channel
821 * @return $compressorInstance The compressor channel
823 public final function getCompressorChannel () {
824 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
825 return $compressorInstance;
829 * Protected getter for a manageable application helper class
831 * @return $applicationInstance An instance of a manageable application helper class
833 protected final function getApplicationInstance () {
834 $applicationInstance = Registry::getRegistry()->getInstance('application');
835 return $applicationInstance;
839 * Setter for a manageable application helper class
841 * @param $applicationInstance An instance of a manageable application helper class
844 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
845 Registry::getRegistry()->addInstance('application', $applicationInstance);
849 * Setter for request instance
851 * @param $requestInstance An instance of a Requestable class
854 public final function setRequestInstance (Requestable $requestInstance) {
855 $this->requestInstance = $requestInstance;
859 * Getter for request instance
861 * @return $requestInstance An instance of a Requestable class
863 public final function getRequestInstance () {
864 return $this->requestInstance;
868 * Setter for response instance
870 * @param $responseInstance An instance of a Responseable class
873 public final function setResponseInstance (Responseable $responseInstance) {
874 $this->responseInstance = $responseInstance;
878 * Getter for response instance
880 * @return $responseInstance An instance of a Responseable class
882 public final function getResponseInstance () {
883 return $this->responseInstance;
887 * Private getter for language instance
889 * @return $langInstance An instance to the language sub-system
891 protected final function getLanguageInstance () {
892 $langInstance = Registry::getRegistry()->getInstance('language');
893 return $langInstance;
897 * Setter for language instance
899 * @param $langInstance An instance to the language sub-system
901 * @see LanguageSystem
903 public final function setLanguageInstance (ManageableLanguage $langInstance) {
904 Registry::getRegistry()->addInstance('language', $langInstance);
908 * Private getter for file IO instance
910 * @return $fileIoInstance An instance to the file I/O sub-system
912 protected final function getFileIoInstance () {
913 return $this->fileIoInstance;
917 * Setter for file I/O instance
919 * @param $fileIoInstance An instance to the file I/O sub-system
922 public final function setFileIoInstance (IoHandler $fileIoInstance) {
923 $this->fileIoInstance = $fileIoInstance;
927 * Protected setter for user instance
929 * @param $userInstance An instance of a user class
932 protected final function setUserInstance (ManageableAccount $userInstance) {
933 $this->userInstance = $userInstance;
937 * Getter for user instance
939 * @return $userInstance An instance of a user class
941 public final function getUserInstance () {
942 return $this->userInstance;
946 * Setter for controller instance (this surely breaks a bit the MVC patterm)
948 * @param $controllerInstance An instance of the controller
951 public final function setControllerInstance (Controller $controllerInstance) {
952 $this->controllerInstance = $controllerInstance;
956 * Getter for controller instance (this surely breaks a bit the MVC patterm)
958 * @return $controllerInstance An instance of the controller
960 public final function getControllerInstance () {
961 return $this->controllerInstance;
965 * Setter for RNG instance
967 * @param $rngInstance An instance of a random number generator (RNG)
970 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
971 $this->rngInstance = $rngInstance;
975 * Getter for RNG instance
977 * @return $rngInstance An instance of a random number generator (RNG)
979 public final function getRngInstance () {
980 return $this->rngInstance;
984 * Setter for Cryptable instance
986 * @param $cryptoInstance An instance of a Cryptable class
989 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
990 $this->cryptoInstance = $cryptoInstance;
994 * Getter for Cryptable instance
996 * @return $cryptoInstance An instance of a Cryptable class
998 public final function getCryptoInstance () {
999 return $this->cryptoInstance;
1003 * Setter for the list instance
1005 * @param $listInstance A list of Listable
1008 protected final function setListInstance (Listable $listInstance) {
1009 $this->listInstance = $listInstance;
1013 * Getter for the list instance
1015 * @return $listInstance A list of Listable
1017 protected final function getListInstance () {
1018 return $this->listInstance;
1022 * Setter for the menu instance
1024 * @param $menuInstance A RenderableMenu instance
1027 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1028 $this->menuInstance = $menuInstance;
1032 * Getter for the menu instance
1034 * @return $menuInstance A RenderableMenu instance
1036 protected final function getMenuInstance () {
1037 return $this->menuInstance;
1041 * Setter for image instance
1043 * @param $imageInstance An instance of an image
1046 public final function setImageInstance (BaseImage $imageInstance) {
1047 $this->imageInstance = $imageInstance;
1051 * Getter for image instance
1053 * @return $imageInstance An instance of an image
1055 public final function getImageInstance () {
1056 return $this->imageInstance;
1060 * Setter for stacker instance
1062 * @param $stackInstance An instance of an stacker
1065 public final function setStackInstance (Stackable $stackInstance) {
1066 $this->stackInstance = $stackInstance;
1070 * Getter for stacker instance
1072 * @return $stackInstance An instance of an stacker
1074 public final function getStackInstance () {
1075 return $this->stackInstance;
1079 * Setter for compressor instance
1081 * @param $compressorInstance An instance of an compressor
1084 public final function setCompressorInstance (Compressor $compressorInstance) {
1085 $this->compressorInstance = $compressorInstance;
1089 * Getter for compressor instance
1091 * @return $compressorInstance An instance of an compressor
1093 public final function getCompressorInstance () {
1094 return $this->compressorInstance;
1098 * Setter for Parseable instance
1100 * @param $parserInstance An instance of an Parseable
1103 public final function setParserInstance (Parseable $parserInstance) {
1104 $this->parserInstance = $parserInstance;
1108 * Getter for Parseable instance
1110 * @return $parserInstance An instance of an Parseable
1112 public final function getParserInstance () {
1113 return $this->parserInstance;
1117 * Setter for HandleableProtocol instance
1119 * @param $protocolInstance An instance of an HandleableProtocol
1122 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1123 $this->protocolInstance = $protocolInstance;
1127 * Getter for HandleableProtocol instance
1129 * @return $protocolInstance An instance of an HandleableProtocol
1131 public final function getProtocolInstance () {
1132 return $this->protocolInstance;
1136 * Setter for DatabaseWrapper instance
1138 * @param $wrapperInstance An instance of an DatabaseWrapper
1141 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1142 $this->wrapperInstance = $wrapperInstance;
1146 * Getter for DatabaseWrapper instance
1148 * @return $wrapperInstance An instance of an DatabaseWrapper
1150 public final function getWrapperInstance () {
1151 return $this->wrapperInstance;
1155 * Setter for socket resource
1157 * @param $socketResource A valid socket resource
1160 public final function setSocketResource ($socketResource) {
1161 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1162 $this->socketResource = $socketResource;
1166 * Getter for socket resource
1168 * @return $socketResource A valid socket resource
1170 public final function getSocketResource () {
1171 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1172 return $this->socketResource;
1176 * Setter for regular expression
1178 * @param $regularExpression A valid regular expression
1181 public final function setRegularExpression ($regularExpression) {
1182 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1183 $this->regularExpression = $regularExpression;
1187 * Getter for regular expression
1189 * @return $regularExpression A valid regular expression
1191 public final function getRegularExpression () {
1192 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1193 return $this->regularExpression;
1197 * Setter for helper instance
1199 * @param $helperInstance An instance of a helper class
1202 protected final function setHelperInstance (Helper $helperInstance) {
1203 $this->helperInstance = $helperInstance;
1207 * Getter for helper instance
1209 * @return $helperInstance An instance of a helper class
1211 public final function getHelperInstance () {
1212 return $this->helperInstance;
1216 * Setter for a Source instance
1218 * @param $sourceInstance An instance of a Source class
1221 protected final function setSourceInstance (Source $sourceInstance) {
1222 $this->sourceInstance = $sourceInstance;
1226 * Getter for a Source instance
1228 * @return $sourceInstance An instance of a Source class
1230 protected final function getSourceInstance () {
1231 return $this->sourceInstance;
1235 * Setter for a UrlSource instance
1237 * @param $sourceInstance An instance of a UrlSource class
1240 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1241 $this->urlSourceInstance = $urlSourceInstance;
1245 * Getter for a UrlSource instance
1247 * @return $urlSourceInstance An instance of a UrlSource class
1249 protected final function getUrlSourceInstance () {
1250 return $this->urlSourceInstance;
1254 * Getter for a InputStream instance
1256 * @param $inputStreamInstance The InputStream instance
1258 protected final function getInputStreamInstance () {
1259 return $this->inputStreamInstance;
1263 * Setter for a InputStream instance
1265 * @param $inputStreamInstance The InputStream instance
1268 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1269 $this->inputStreamInstance = $inputStreamInstance;
1273 * Getter for a OutputStream instance
1275 * @param $outputStreamInstance The OutputStream instance
1277 protected final function getOutputStreamInstance () {
1278 return $this->outputStreamInstance;
1282 * Setter for a OutputStream instance
1284 * @param $outputStreamInstance The OutputStream instance
1287 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1288 $this->outputStreamInstance = $outputStreamInstance;
1292 * Setter for handler instance
1294 * @param $handlerInstance An instance of a Handleable class
1297 protected final function setHandlerInstance (Handleable $handlerInstance) {
1298 $this->handlerInstance = $handlerInstance;
1302 * Getter for handler instance
1304 * @return $handlerInstance A Networkable instance
1306 protected final function getHandlerInstance () {
1307 return $this->handlerInstance;
1311 * Setter for visitor instance
1313 * @param $visitorInstance A Visitor instance
1316 protected final function setVisitorInstance (Visitor $visitorInstance) {
1317 $this->visitorInstance = $visitorInstance;
1321 * Getter for visitor instance
1323 * @return $visitorInstance A Visitor instance
1325 protected final function getVisitorInstance () {
1326 return $this->visitorInstance;
1330 * Setter for DHT instance
1332 * @param $dhtInstance A Distributable instance
1335 protected final function setDhtInstance (Distributable $dhtInstance) {
1336 $this->dhtInstance = $dhtInstance;
1340 * Getter for DHT instance
1342 * @return $dhtInstance A Distributable instance
1344 protected final function getDhtInstance () {
1345 return $this->dhtInstance;
1349 * Setter for raw package Data
1351 * @param $packageData Raw package Data
1354 public final function setPackageData (array $packageData) {
1355 $this->packageData = $packageData;
1359 * Getter for raw package Data
1361 * @return $packageData Raw package Data
1363 public function getPackageData () {
1364 return $this->packageData;
1369 * Setter for Iterator instance
1371 * @param $iteratorInstance An instance of an Iterator
1374 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1375 $this->iteratorInstance = $iteratorInstance;
1379 * Getter for Iterator instance
1381 * @return $iteratorInstance An instance of an Iterator
1383 public final function getIteratorInstance () {
1384 return $this->iteratorInstance;
1388 * Setter for FilePointer instance
1390 * @param $pointerInstance An instance of an FilePointer class
1393 protected final function setPointerInstance (FilePointer $pointerInstance) {
1394 $this->pointerInstance = $pointerInstance;
1398 * Getter for FilePointer instance
1400 * @return $pointerInstance An instance of an FilePointer class
1402 public final function getPointerInstance () {
1403 return $this->pointerInstance;
1407 * Unsets pointer instance which triggers a call of __destruct() if the
1408 * instance is still there. This is surely not fatal on already "closed"
1409 * file pointer instances.
1411 * I don't want to mess around with above setter by giving it a default
1412 * value NULL as setter should always explicitly only set (existing) object
1413 * instances and NULL is NULL.
1417 protected final function unsetPointerInstance () {
1418 // Simply it to NULL
1419 $this->pointerInstance = NULL;
1423 * Setter for Indexable instance
1425 * @param $indexInstance An instance of an Indexable class
1428 protected final function setIndexInstance (Indexable $indexInstance) {
1429 $this->indexInstance = $indexInstance;
1433 * Getter for Indexable instance
1435 * @return $indexInstance An instance of an Indexable class
1437 public final function getIndexInstance () {
1438 return $this->indexInstance;
1442 * Setter for Block instance
1444 * @param $blockInstance An instance of an Block class
1447 protected final function setBlockInstance (Block $blockInstance) {
1448 $this->blockInstance = $blockInstance;
1452 * Getter for Block instance
1454 * @return $blockInstance An instance of an Block class
1456 public final function getBlockInstance () {
1457 return $this->blockInstance;
1461 * Setter for Minable instance
1463 * @param $minableInstance A Minable instance
1466 protected final function setMinableInstance (Minable $minableInstance) {
1467 $this->minableInstance = $minableInstance;
1471 * Getter for minable instance
1473 * @return $minableInstance A Minable instance
1475 protected final function getMinableInstance () {
1476 return $this->minableInstance;
1480 * Setter for FrameworkDirectory instance
1482 * @param $directoryInstance A FrameworkDirectoryPointer instance
1485 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1486 $this->directoryInstance = $directoryInstance;
1490 * Getter for FrameworkDirectory instance
1492 * @return $directoryInstance A FrameworkDirectory instance
1494 protected final function getDirectoryInstance () {
1495 return $this->directoryInstance;
1499 * Setter for listener instance
1501 * @param $listenerInstance A Listenable instance
1504 protected final function setListenerInstance (Listenable $listenerInstance) {
1505 $this->listenerInstance = $listenerInstance;
1509 * Getter for listener instance
1511 * @return $listenerInstance A Listenable instance
1513 protected final function getListenerInstance () {
1514 return $this->listenerInstance;
1518 * Getter for communicator instance
1520 * @return $communicatorInstance An instance of a Communicator class
1522 public final function getCommunicatorInstance () {
1523 return $this->communicatorInstance;
1527 * Setter for communicator instance
1529 * @param $communicatorInstance An instance of a Communicator class
1532 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1533 $this->communicatorInstance = $communicatorInstance;
1537 * Setter for command name
1539 * @param $commandName Last validated command name
1542 protected final function setCommandName ($commandName) {
1543 $this->commandName = $commandName;
1547 * Getter for command name
1549 * @return $commandName Last validated command name
1551 protected final function getCommandName () {
1552 return $this->commandName;
1556 * Setter for controller name
1558 * @param $controllerName Last validated controller name
1561 protected final function setControllerName ($controllerName) {
1562 $this->controllerName = $controllerName;
1566 * Getter for controller name
1568 * @return $controllerName Last validated controller name
1570 protected final function getControllerName () {
1571 return $this->controllerName;
1575 * Checks whether an object equals this object. You should overwrite this
1576 * method to implement own equality checks
1578 * @param $objectInstance An instance of a FrameworkInterface object
1579 * @return $equals Whether both objects equals
1581 public function equals (FrameworkInterface $objectInstance) {
1584 $this->__toString() == $objectInstance->__toString()
1586 $this->hashCode() == $objectInstance->hashCode()
1589 // Return the result
1594 * Generates a generic hash code of this class. You should really overwrite
1595 * this method with your own hash code generator code. But keep KISS in mind.
1597 * @return $hashCode A generic hash code respresenting this whole class
1599 public function hashCode () {
1601 return crc32($this->__toString());
1605 * Formats computer generated price values into human-understandable formats
1606 * with thousand and decimal separators.
1608 * @param $value The in computer format value for a price
1609 * @param $currency The currency symbol (use HTML-valid characters!)
1610 * @param $decNum Number of decimals after commata
1611 * @return $price The for the current language formated price string
1612 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1613 * thousands separator
1616 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1617 // Are all required attriutes set?
1618 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1619 // Throw an exception
1620 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1624 $value = (float) $value;
1626 // Reformat the US number
1627 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1629 // Return as string...
1634 * Appends a trailing slash to a string
1636 * @param $str A string (maybe) without trailing slash
1637 * @return $str A string with an auto-appended trailing slash
1639 public final function addMissingTrailingSlash ($str) {
1640 // Is there a trailing slash?
1641 if (substr($str, -1, 1) != '/') {
1645 // Return string with trailing slash
1650 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1651 * application helper instance (ApplicationHelper by default).
1653 * @param $applicationInstance An application helper instance or
1654 * null if we shall use the default
1655 * @return $templateInstance The template engine instance
1656 * @throws NullPointerException If the discovered application
1657 * instance is still null
1659 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1660 // Is the application instance set?
1661 if (is_null($applicationInstance)) {
1662 // Get the current instance
1663 $applicationInstance = $this->getApplicationInstance();
1666 if (is_null($applicationInstance)) {
1667 // Thrown an exception
1668 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1672 // Initialize the template engine
1673 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1675 // Return the prepared instance
1676 return $templateInstance;
1680 * Debugs this instance by putting out it's full content
1682 * @param $message Optional message to show in debug output
1685 public final function debugInstance ($message = '') {
1686 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1687 restore_error_handler();
1692 // Is a message set?
1693 if (!empty($message)) {
1694 // Construct message
1695 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1698 // Generate the output
1699 $content .= sprintf('<pre>%s</pre>',
1702 print_r($this, TRUE)
1708 ApplicationEntryPoint::app_exit(sprintf('<div class="debug_header">%s debug output:</div><div class="debug_content">%s</div>Loaded includes: <div class="debug_include_list">%s</div>',
1709 $this->__toString(),
1711 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1716 * Replaces control characters with printable output
1718 * @param $str String with control characters
1719 * @return $str Replaced string
1721 protected function replaceControlCharacters ($str) {
1724 chr(13), '[r]', str_replace(
1725 chr(10), '[n]', str_replace(
1735 * Output a partial stub message for the caller method
1737 * @param $message An optional message to display
1740 protected function partialStub ($message = '') {
1741 // Get the backtrace
1742 $backtrace = debug_backtrace();
1744 // Generate the class::method string
1745 $methodName = 'UnknownClass->unknownMethod';
1746 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1747 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1750 // Construct the full message
1751 $stubMessage = sprintf('[%s:] Partial stub!',
1755 // Is the extra message given?
1756 if (!empty($message)) {
1757 // Then add it as well
1758 $stubMessage .= ' Message: ' . $message;
1761 // Debug instance is there?
1762 if (!is_null($this->getDebugInstance())) {
1763 // Output stub message
1764 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1767 trigger_error($stubMessage);
1773 * Outputs a debug backtrace and stops further script execution
1775 * @param $message An optional message to output
1776 * @param $doExit Whether exit the program (TRUE is default)
1779 public function debugBackTrace ($message = '', $doExit = TRUE) {
1780 // Sorry, there is no other way getting this nice backtrace
1781 if (!empty($message)) {
1783 printf('Message: %s<br />' . chr(10), $message);
1787 debug_print_backtrace();
1791 if ($doExit === TRUE) {
1797 * Creates an instance of a debugger instance
1799 * @param $className Name of the class (currently unsupported)
1800 * @return $debugInstance An instance of a debugger class
1802 public final static function createDebugInstance ($className) {
1803 // Is the instance set?
1804 if (!Registry::getRegistry()->instanceExists('debug')) {
1805 // Init debug instance
1806 $debugInstance = NULL;
1810 // Get a debugger instance
1811 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'));
1812 } catch (NullPointerException $e) {
1813 // Didn't work, no instance there
1814 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1817 // Empty string should be ignored and used for testing the middleware
1818 DebugMiddleware::getSelfInstance()->output('');
1820 // Set it in its own class. This will set it in the registry
1821 $debugInstance->setDebugInstance($debugInstance);
1823 // Get instance from registry
1824 $debugInstance = Registry::getRegistry()->getDebugInstance();
1828 return $debugInstance;
1832 * Simple output of a message with line-break
1834 * @param $message Message to output
1837 public function outputLine ($message) {
1839 print($message . PHP_EOL);
1843 * Outputs a debug message whether to debug instance (should be set!) or
1844 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1845 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1847 * @param $message Message we shall send out...
1848 * @param $doPrint Whether print or die here (default: print)
1849 * @paran $stripTags Whether to strip tags (default: FALSE)
1852 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1853 // Set debug instance to NULL
1854 $debugInstance = NULL;
1858 // Get debug instance
1859 $debugInstance = $this->getDebugInstance();
1860 } catch (NullPointerException $e) {
1861 // The debug instance is not set (yet)
1864 // Is the debug instance there?
1865 if (is_object($debugInstance)) {
1866 // Use debug output handler
1867 $debugInstance->output($message, $stripTags);
1869 if ($doPrint === FALSE) {
1870 // Die here if not printed
1874 // Are debug times enabled?
1875 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1877 $message = $this->getPrintableExecutionTime() . $message;
1881 if ($doPrint === TRUE) {
1883 $this->outputLine($message);
1892 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1894 * @param $str The string, what ever it is needs to be converted
1895 * @return $className Generated class name
1897 public static final function convertToClassName ($str) {
1901 // Convert all dashes in underscores
1902 $str = self::convertDashesToUnderscores($str);
1904 // Now use that underscores to get classname parts for hungarian style
1905 foreach (explode('_', $str) as $strPart) {
1906 // Make the class name part lower case and first upper case
1907 $className .= ucfirst(strtolower($strPart));
1910 // Return class name
1915 * Converts dashes to underscores, e.g. useable for configuration entries
1917 * @param $str The string with maybe dashes inside
1918 * @return $str The converted string with no dashed, but underscores
1920 public static final function convertDashesToUnderscores ($str) {
1922 $str = str_replace('-', '_', $str);
1924 // Return converted string
1929 * Marks up the code by adding e.g. line numbers
1931 * @param $phpCode Unmarked PHP code
1932 * @return $markedCode Marked PHP code
1934 public function markupCode ($phpCode) {
1939 $errorArray = error_get_last();
1941 // Init the code with error message
1942 if (is_array($errorArray)) {
1944 $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>',
1945 basename($errorArray['file']),
1946 $errorArray['line'],
1947 $errorArray['message'],
1952 // Add line number to the code
1953 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1955 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1957 htmlentities($code, ENT_QUOTES)
1966 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1967 * beatiful for web-based front-ends. If null is given a message id
1968 * null_timestamp will be resolved and returned.
1970 * @param $timestamp Timestamp to prepare (filter) for display
1971 * @return $readable A readable timestamp
1973 public function doFilterFormatTimestamp ($timestamp) {
1974 // Default value to return
1977 // Is the timestamp null?
1978 if (is_null($timestamp)) {
1979 // Get a message string
1980 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1982 switch ($this->getLanguageInstance()->getLanguageCode()) {
1983 case 'de': // German format is a bit different to default
1984 // Split the GMT stamp up
1985 $dateTime = explode(' ', $timestamp );
1986 $dateArray = explode('-', $dateTime[0]);
1987 $timeArray = explode(':', $dateTime[1]);
1989 // Construct the timestamp
1990 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2000 default: // Default is pass-through
2001 $readable = $timestamp;
2011 * Filter a given number into a localized number
2013 * @param $value The raw value from e.g. database
2014 * @return $localized Localized value
2016 public function doFilterFormatNumber ($value) {
2017 // Generate it from config and localize dependencies
2018 switch ($this->getLanguageInstance()->getLanguageCode()) {
2019 case 'de': // German format is a bit different to default
2020 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2023 default: // US, etc.
2024 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2033 * "Getter" for databse entry
2035 * @return $entry An array with database entries
2036 * @throws NullPointerException If the database result is not found
2037 * @throws InvalidDatabaseResultException If the database result is invalid
2039 protected final function getDatabaseEntry () {
2040 // Is there an instance?
2041 if (!$this->getResultInstance() instanceof SearchableResult) {
2042 // Throw an exception here
2043 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2047 $this->getResultInstance()->rewind();
2049 // Do we have an entry?
2050 if ($this->getResultInstance()->valid() === FALSE) {
2051 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2052 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2056 $this->getResultInstance()->next();
2059 $entry = $this->getResultInstance()->current();
2066 * Getter for field name
2068 * @param $fieldName Field name which we shall get
2069 * @return $fieldValue Field value from the user
2070 * @throws NullPointerException If the result instance is null
2072 public final function getField ($fieldName) {
2073 // Default field value
2076 // Get result instance
2077 $resultInstance = $this->getResultInstance();
2079 // Is this instance null?
2080 if (is_null($resultInstance)) {
2081 // Then the user instance is no longer valid (expired cookies?)
2082 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2085 // Get current array
2086 $fieldArray = $resultInstance->current();
2087 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2089 // Convert dashes to underscore
2090 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2092 // Does the field exist?
2093 if ($this->isFieldSet($fieldName)) {
2095 $fieldValue = $fieldArray[$fieldName2];
2096 } elseif (defined('DEVELOPER')) {
2097 // Missing field entry, may require debugging
2098 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2100 // Missing field entry, may require debugging
2101 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2109 * Checks if given field is set
2111 * @param $fieldName Field name to check
2112 * @return $isSet Whether the given field name is set
2113 * @throws NullPointerException If the result instance is null
2115 public function isFieldSet ($fieldName) {
2116 // Get result instance
2117 $resultInstance = $this->getResultInstance();
2119 // Is this instance null?
2120 if (is_null($resultInstance)) {
2121 // Then the user instance is no longer valid (expired cookies?)
2122 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2125 // Get current array
2126 $fieldArray = $resultInstance->current();
2127 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2129 // Convert dashes to underscore
2130 $fieldName = self::convertDashesToUnderscores($fieldName);
2133 $isSet = isset($fieldArray[$fieldName]);
2140 * Flushs all pending updates to the database layer
2144 public function flushPendingUpdates () {
2145 // Get result instance
2146 $resultInstance = $this->getResultInstance();
2148 // Do we have data to update?
2149 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2150 // Get wrapper class name config entry
2151 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2153 // Create object instance
2154 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
2156 // Yes, then send the whole result to the database layer
2157 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2162 * Outputs a deprecation warning to the developer.
2164 * @param $message The message we shall output to the developer
2166 * @todo Write a logging mechanism for productive mode
2168 public function deprecationWarning ($message) {
2169 // Is developer mode active?
2170 if (defined('DEVELOPER')) {
2171 // Debug instance is there?
2172 if (!is_null($this->getDebugInstance())) {
2173 // Output stub message
2174 self::createDebugInstance(__CLASS__)->debugOutput($message);
2177 trigger_error($message . "<br />\n");
2181 // @TODO Finish this part!
2182 $this->partialStub('Developer mode inactive. Message:' . $message);
2187 * Checks whether the given PHP extension is loaded
2189 * @param $phpExtension The PHP extension we shall check
2190 * @return $isLoaded Whether the PHP extension is loaded
2192 public final function isPhpExtensionLoaded ($phpExtension) {
2194 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2201 * "Getter" as a time() replacement but with milliseconds. You should use this
2202 * method instead of the encapsulated getimeofday() function.
2204 * @return $milliTime Timestamp with milliseconds
2206 public function getMilliTime () {
2207 // Get the time of day as float
2208 $milliTime = gettimeofday(TRUE);
2215 * Idles (sleeps) for given milliseconds
2217 * @return $hasSlept Whether it goes fine
2219 public function idle ($milliSeconds) {
2220 // Sleep is fine by default
2223 // Idle so long with found function
2224 if (function_exists('time_sleep_until')) {
2225 // Get current time and add idle time
2226 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2228 // New PHP 5.1.0 function found, ignore errors
2229 $hasSlept = @time_sleep_until($sleepUntil);
2232 * My Sun station doesn't have that function even with latest PHP
2235 usleep($milliSeconds * 1000);
2242 * Converts a hexadecimal string, even with negative sign as first string to
2243 * a decimal number using BC functions.
2245 * This work is based on comment #86673 on php.net documentation page at:
2246 * <http://de.php.net/manual/en/function.dechex.php#86673>
2248 * @param $hex Hexadecimal string
2249 * @return $dec Decimal number
2251 protected function hex2dec ($hex) {
2252 // Convert to all lower-case
2253 $hex = strtolower($hex);
2255 // Detect sign (negative/positive numbers)
2257 if (substr($hex, 0, 1) == '-') {
2259 $hex = substr($hex, 1);
2262 // Decode the hexadecimal string into a decimal number
2264 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2265 $factor = self::$hexdec[substr($hex, $i, 1)];
2266 $dec = bcadd($dec, bcmul($factor, $e));
2269 // Return the decimal number
2270 return $sign . $dec;
2274 * Converts even very large decimal numbers, also signed, to a hexadecimal
2277 * This work is based on comment #97756 on php.net documentation page at:
2278 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2280 * @param $dec Decimal number, even with negative sign
2281 * @param $maxLength Optional maximum length of the string
2282 * @return $hex Hexadecimal string
2284 protected function dec2hex ($dec, $maxLength = 0) {
2285 // maxLength can be zero or devideable by 2
2286 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2288 // Detect sign (negative/positive numbers)
2295 // Encode the decimal number into a hexadecimal string
2298 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2300 } while ($dec >= 1);
2303 * Leading zeros are required for hex-decimal "numbers". In some
2304 * situations more leading zeros are wanted, so check for both
2307 if ($maxLength > 0) {
2308 // Prepend more zeros
2309 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2310 } elseif ((strlen($hex) % 2) != 0) {
2311 // Only make string's length dividable by 2
2315 // Return the hexadecimal string
2316 return $sign . $hex;
2320 * Converts a ASCII string (0 to 255) into a decimal number.
2322 * @param $asc The ASCII string to be converted
2323 * @return $dec Decimal number
2325 protected function asc2dec ($asc) {
2326 // Convert it into a hexadecimal number
2327 $hex = bin2hex($asc);
2329 // And back into a decimal number
2330 $dec = $this->hex2dec($hex);
2337 * Converts a decimal number into an ASCII string.
2339 * @param $dec Decimal number
2340 * @return $asc An ASCII string
2342 protected function dec2asc ($dec) {
2343 // First convert the number into a hexadecimal string
2344 $hex = $this->dec2hex($dec);
2346 // Then convert it into the ASCII string
2347 $asc = $this->hex2asc($hex);
2354 * Converts a hexadecimal number into an ASCII string. Negative numbers
2357 * @param $hex Hexadecimal string
2358 * @return $asc An ASCII string
2360 protected function hex2asc ($hex) {
2361 // Check for length, it must be devideable by 2
2362 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2363 assert((strlen($hex) % 2) == 0);
2367 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2368 // Get the decimal number of the chunk
2369 $part = hexdec(substr($hex, $idx, 2));
2371 // Add it to the final string
2375 // Return the final string
2380 * Checks whether the given encoded data was encoded with Base64
2382 * @param $encodedData Encoded data we shall check
2383 * @return $isBase64 Whether the encoded data is Base64
2385 protected function isBase64Encoded ($encodedData) {
2387 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2394 * "Getter" to get response/request type from analysis of the system.
2396 * @return $responseType Analyzed response type
2398 protected static function getResponseTypeFromSystem () {
2399 // Default is console
2400 $responseType = 'console';
2402 // Is 'HTTP_HOST' set?
2403 if (isset($_SERVER['HTTP_HOST'])) {
2405 * Then it is a HTML response/request as RSS and so on may be
2406 * transfered over HTTP as well.
2408 $responseType = 'html';
2412 return $responseType;
2416 * Gets a cache key from Criteria instance
2418 * @param $criteriaInstance An instance of a Criteria class
2419 * @param $onlyKeys Only use these keys for a cache key
2420 * @return $cacheKey A cache key suitable for lookup/storage purposes
2422 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2424 $cacheKey = sprintf('%s@%s',
2425 $this->__toString(),
2426 $criteriaInstance->getCacheKey($onlyKeys)
2430 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2435 * Getter for startup time in miliseconds
2437 * @return $startupTime Startup time in miliseconds
2439 protected function getStartupTime () {
2440 return self::$startupTime;
2444 * "Getter" for a printable currently execution time in nice braces
2446 * @return $executionTime Current execution time in nice braces
2448 protected function getPrintableExecutionTime () {
2449 // Caculate the execution time
2450 $executionTime = microtime(TRUE) - $this->getStartupTime();
2452 // Pack it in nice braces
2453 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2456 return $executionTime;
2460 * Hashes a given string with a simple but stronger hash function (no salt)
2461 * and hex-encode it.
2463 * @param $str The string to be hashed
2464 * @return $hash The hash from string $str
2466 public static final function hash ($str) {
2467 // Hash given string with (better secure) hasher
2468 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2475 * "Getter" for length of hash() output. This will be "cached" to speed up
2478 * @return $length Length of hash() output
2480 public static final function getHashLength () {
2482 if (is_null(self::$hashLength)) {
2483 // No, then hash a string and save its length.
2484 self::$hashLength = strlen(self::hash('abc123'));
2488 return self::$hashLength;
2492 * Checks whether the given number is really a number (only chars 0-9).
2494 * @param $num A string consisting only chars between 0 and 9
2495 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2496 * @param $assertMismatch Whether to assert mismatches
2497 * @return $ret The (hopefully) secured numbered value
2499 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2500 // Filter all numbers out
2501 $ret = preg_replace('/[^0123456789]/', '', $num);
2504 if ($castValue === TRUE) {
2505 // Cast to biggest numeric type
2506 $ret = (double) $ret;
2509 // Assert only if requested
2510 if ($assertMismatch === TRUE) {
2511 // Has the whole value changed?
2512 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2520 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2522 * @param $num A string consisting only chars between 0 and 9
2523 * @param $assertMismatch Whether to assert mismatches
2524 * @return $ret The (hopefully) secured hext-numbered value
2526 public function hexval ($num, $assertMismatch = FALSE) {
2527 // Filter all numbers out
2528 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2530 // Assert only if requested
2531 if ($assertMismatch === TRUE) {
2532 // Has the whole value changed?
2533 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2541 * Checks whether start/end marker are set
2543 * @param $data Data to be checked
2544 * @return $isset Whether start/end marker are set
2546 public final function ifStartEndMarkersSet ($data) {
2548 $isset = ((substr($data, 0, strlen(BaseRawDataHandler::STREAM_START_MARKER)) == BaseRawDataHandler::STREAM_START_MARKER) && (substr($data, -1 * strlen(BaseRawDataHandler::STREAM_END_MARKER), strlen(BaseRawDataHandler::STREAM_END_MARKER)) == BaseRawDataHandler::STREAM_END_MARKER));
2550 // ... and return it
2555 * Determines if an element is set in the generic array
2557 * @param $keyGroup Main group for the key
2558 * @param $subGroup Sub group for the key
2559 * @param $key Key to check
2560 * @param $element Element to check
2561 * @return $isset Whether the given key is set
2563 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2565 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2568 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2574 * Determines if a key is set in the generic array
2576 * @param $keyGroup Main group for the key
2577 * @param $subGroup Sub group for the key
2578 * @param $key Key to check
2579 * @return $isset Whether the given key is set
2581 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2583 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2586 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2594 * Determines if a group is set in the generic array
2596 * @param $keyGroup Main group
2597 * @param $subGroup Sub group
2598 * @return $isset Whether the given group is set
2600 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2602 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2605 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2612 * Getter for sub key group
2614 * @param $keyGroup Main key group
2615 * @param $subGroup Sub key group
2616 * @return $array An array with all array elements
2618 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2620 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2621 // No, then abort here
2622 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2627 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2630 return $this->genericArray[$keyGroup][$subGroup];
2634 * Unsets a given key in generic array
2636 * @param $keyGroup Main group for the key
2637 * @param $subGroup Sub group for the key
2638 * @param $key Key to unset
2641 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2643 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2646 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2650 * Unsets a given element in generic array
2652 * @param $keyGroup Main group for the key
2653 * @param $subGroup Sub group for the key
2654 * @param $key Key to unset
2655 * @param $element Element to unset
2658 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2660 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2663 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2667 * Append a string to a given generic array key
2669 * @param $keyGroup Main group for the key
2670 * @param $subGroup Sub group for the key
2671 * @param $key Key to unset
2672 * @param $value Value to add/append
2675 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2677 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE) . ',appendGlue=' . $appendGlue);
2679 // Is it already there?
2680 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2682 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2685 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2690 * Append a string to a given generic array element
2692 * @param $keyGroup Main group for the key
2693 * @param $subGroup Sub group for the key
2694 * @param $key Key to unset
2695 * @param $element Element to check
2696 * @param $value Value to add/append
2699 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2701 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE) . ',appendGlue=' . $appendGlue);
2703 // Is it already there?
2704 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2706 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2709 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2714 * Initializes given generic array group
2716 * @param $keyGroup Main group for the key
2717 * @param $subGroup Sub group for the key
2718 * @param $key Key to use
2719 * @param $forceInit Optionally force initialization
2722 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2724 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2726 // Is it already set?
2727 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2728 // Already initialized
2729 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2734 $this->genericArray[$keyGroup][$subGroup] = array();
2738 * Initializes given generic array key
2740 * @param $keyGroup Main group for the key
2741 * @param $subGroup Sub group for the key
2742 * @param $key Key to use
2743 * @param $forceInit Optionally force initialization
2746 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2748 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2750 // Is it already set?
2751 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2752 // Already initialized
2753 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2758 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2762 * Initializes given generic array element
2764 * @param $keyGroup Main group for the key
2765 * @param $subGroup Sub group for the key
2766 * @param $key Key to use
2767 * @param $element Element to use
2768 * @param $forceInit Optionally force initialization
2771 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2773 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2775 // Is it already set?
2776 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2777 // Already initialized
2778 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2783 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2787 * Pushes an element to a generic key
2789 * @param $keyGroup Main group for the key
2790 * @param $subGroup Sub group for the key
2791 * @param $key Key to use
2792 * @param $value Value to add/append
2793 * @return $count Number of array elements
2795 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2797 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2800 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2802 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2806 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2809 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2810 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2815 * Pushes an element to a generic array element
2817 * @param $keyGroup Main group for the key
2818 * @param $subGroup Sub group for the key
2819 * @param $key Key to use
2820 * @param $element Element to check
2821 * @param $value Value to add/append
2822 * @return $count Number of array elements
2824 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2826 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2829 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2831 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2835 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2838 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2839 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2844 * Pops an element from a generic group
2846 * @param $keyGroup Main group for the key
2847 * @param $subGroup Sub group for the key
2848 * @param $key Key to unset
2849 * @return $value Last "popped" value
2851 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2853 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2856 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2858 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2863 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2866 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2867 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2872 * Shifts an element from a generic group
2874 * @param $keyGroup Main group for the key
2875 * @param $subGroup Sub group for the key
2876 * @param $key Key to unset
2877 * @return $value Last "popped" value
2879 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2881 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2884 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2886 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2891 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2894 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2895 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2900 * Count generic array group
2902 * @param $keyGroup Main group for the key
2903 * @return $count Count of given group
2905 protected final function countGenericArray ($keyGroup) {
2907 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2910 if (!isset($this->genericArray[$keyGroup])) {
2912 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2917 $count = count($this->genericArray[$keyGroup]);
2920 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2927 * Count generic array sub group
2929 * @param $keyGroup Main group for the key
2930 * @param $subGroup Sub group for the key
2931 * @return $count Count of given group
2933 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2935 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2938 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2940 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2945 $count = count($this->genericArray[$keyGroup][$subGroup]);
2948 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2955 * Count generic array elements
2957 * @param $keyGroup Main group for the key
2958 * @param $subGroup Sub group for the key
2959 * @para $key Key to count
2960 * @return $count Count of given key
2962 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2964 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2967 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2969 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2971 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2973 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2978 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2981 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2988 * Getter for whole generic group array
2990 * @param $keyGroup Key group to get
2991 * @return $array Whole generic array group
2993 protected final function getGenericArray ($keyGroup) {
2995 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2998 if (!isset($this->genericArray[$keyGroup])) {
3000 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3005 return $this->genericArray[$keyGroup];
3009 * Setter for generic array key
3011 * @param $keyGroup Key group to get
3012 * @param $subGroup Sub group for the key
3013 * @param $key Key to unset
3014 * @param $value Mixed value from generic array element
3017 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3019 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3022 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3026 * Getter for generic array key
3028 * @param $keyGroup Key group to get
3029 * @param $subGroup Sub group for the key
3030 * @param $key Key to unset
3031 * @return $value Mixed value from generic array element
3033 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3035 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3038 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3040 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3045 return $this->genericArray[$keyGroup][$subGroup][$key];
3049 * Sets a value in given generic array key/element
3051 * @param $keyGroup Main group for the key
3052 * @param $subGroup Sub group for the key
3053 * @param $key Key to set
3054 * @param $element Element to set
3055 * @param $value Value to set
3058 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3060 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3063 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3067 * Getter for generic array element
3069 * @param $keyGroup Key group to get
3070 * @param $subGroup Sub group for the key
3071 * @param $key Key to look for
3072 * @param $element Element to look for
3073 * @return $value Mixed value from generic array element
3075 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3077 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3080 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3082 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3087 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3091 * Checks if a given sub group is valid (array)
3093 * @param $keyGroup Key group to get
3094 * @param $subGroup Sub group for the key
3095 * @return $isValid Whether given sub group is valid
3097 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3099 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3102 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3109 * Checks if a given key is valid (array)
3111 * @param $keyGroup Key group to get
3112 * @param $subGroup Sub group for the key
3113 * @param $key Key to check
3114 * @return $isValid Whether given sub group is valid
3116 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3118 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3121 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3128 * Initializes the web output instance
3132 protected function initWebOutputInstance () {
3133 // Get application instance
3134 $applicationInstance = Registry::getRegistry()->getInstance('app');
3136 // Is this a response instance?
3137 if ($this instanceof Responseable) {
3138 // Then set it in application instance
3139 $applicationInstance->setResponseInstance($this);
3142 // Init web output instance
3143 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3146 $this->setWebOutputInstance($outputInstance);
3150 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3152 * @param $boolean Boolean value
3153 * @return $translated Translated boolean value
3155 public static final function translateBooleanToYesNo ($boolean) {
3156 // Make sure it is really boolean
3157 assert(is_bool($boolean));
3160 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3162 // ... and return it
3167 * Encodes raw data (almost any type) by "serializing" it and then pack it
3168 * into a "binary format".
3170 * @param $rawData Raw data (almost any type)
3171 * @return $encoded Encoded data
3173 protected function encodeData ($rawData) {
3174 // Make sure no objects or resources pass through
3175 assert(!is_object($rawData));
3176 assert(!is_resource($rawData));
3178 // First "serialize" it (json_encode() is faster than serialize())
3179 $encoded = $this->packString(json_encode($rawData));
3186 * Pack a string into a "binary format". Please execuse me that this is
3187 * widely undocumented. :-(
3189 * @param $str Unpacked string
3190 * @return $packed Packed string
3191 * @todo Improve documentation
3193 protected function packString ($str) {
3195 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3197 // First compress the string (gzcompress is okay)
3198 $str = gzcompress($str);
3203 // And start the "encoding" loop
3204 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3206 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3207 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3209 if (($idx + $i) <= strlen($str)) {
3210 $ord = ord(substr($str, ($idx + $i), 1));
3212 $add = $ord * pow(256, $factor);
3216 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3220 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3221 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3223 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3224 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3230 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3235 * Checks whether the given file/path is in open_basedir(). This does not
3236 * gurantee that the file is actually readable and/or writeable. If you need
3237 * such gurantee then please use isReadableFile() instead.
3239 * @param $filePathName Name of the file/path to be checked
3240 * @return $isReachable Whether it is within open_basedir()
3242 public static function isReachableFilePath ($filePathName) {
3243 // Is not reachable by default
3244 $isReachable = FALSE;
3246 // Get open_basedir parameter
3247 $openBaseDir = ini_get('open_basedir');
3250 if (!empty($openBaseDir)) {
3251 // Check all entries
3252 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3253 // Check on existence
3254 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3256 $isReachable = TRUE;
3260 // If open_basedir is not set, all is allowed
3261 $isReachable = TRUE;
3265 return $isReachable;
3269 * Checks whether the give file is within open_basedir() (done by
3270 * isReachableFilePath()), is actually a file and is readable.
3272 * @param $fileName Name of the file to be checked
3273 * @return $isReadable Whether the file is readable (and therefor exists)
3275 public static function isReadableFile ($fileName) {
3276 // Default is not readable
3277 $isReadable = FALSE;
3279 // Is within parameters, so check if it is a file and readable
3280 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));