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;
224 private $stateInstance = NULL;
227 * Thousands separator
229 private $thousands = '.'; // German
234 private $decimals = ','; // German
239 private $socketResource = FALSE;
242 * Regular expression to use for validation
244 private $regularExpression = '';
249 private $packageData = array();
254 private $genericArray = array();
259 private $commandName = '';
264 private $controllerName = '';
267 * Array with bitmasks and such for pack/unpack methods to support both
268 * 32-bit and 64-bit systems
270 private $packingData = array(
273 'left' => 0xffff0000,
274 'right' => 0x0000ffff,
280 'left' => 0xffffffff00000000,
281 'right' => 0x00000000ffffffff,
288 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
290 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
292 private $archArrayElement = FALSE;
294 /***********************
295 * Exception codes.... *
296 ***********************/
298 // @todo Try to clean these constants up
299 const EXCEPTION_IS_NULL_POINTER = 0x001;
300 const EXCEPTION_IS_NO_OBJECT = 0x002;
301 const EXCEPTION_IS_NO_ARRAY = 0x003;
302 const EXCEPTION_MISSING_METHOD = 0x004;
303 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
304 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
305 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
306 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
307 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
308 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
309 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
310 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
311 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
312 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
313 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
314 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
315 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
316 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
317 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
318 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
319 const EXCEPTION_PATH_NOT_FOUND = 0x015;
320 const EXCEPTION_INVALID_PATH_NAME = 0x016;
321 const EXCEPTION_READ_PROTECED_PATH = 0x017;
322 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
323 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
324 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
325 const EXCEPTION_INVALID_RESOURCE = 0x01b;
326 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
327 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
328 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
329 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
330 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
331 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
332 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
333 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
334 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
335 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
336 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
337 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
338 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
339 const EXCEPTION_INVALID_STRING = 0x029;
340 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
341 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
342 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
343 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
344 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
345 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
346 const EXCEPTION_MISSING_ELEMENT = 0x030;
347 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
348 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
349 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
350 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
351 const EXCEPTION_FATAL_ERROR = 0x035;
352 const EXCEPTION_FILE_NOT_FOUND = 0x036;
353 const EXCEPTION_ASSERTION_FAILED = 0x037;
354 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
355 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
356 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
357 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03b;
358 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03c;
361 * Hexadecimal->Decimal translation array
363 private static $hexdec = array(
383 * Decimal->hexadecimal translation array
385 private static $dechex = array(
405 * Startup time in miliseconds
407 private static $startupTime = 0;
410 * Protected super constructor
412 * @param $className Name of the class
415 protected function __construct ($className) {
417 $this->setRealClass($className);
419 // Set configuration instance if no registry ...
420 if (!$this instanceof Register) {
421 // ... because registries doesn't need to be configured
422 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
425 // Is the startup time set? (0 cannot be TRUE anymore)
426 if (self::$startupTime == 0) {
428 self::$startupTime = microtime(TRUE);
432 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
436 * Destructor for all classes
440 public function __destruct () {
441 // Flush any updated entries to the database
442 $this->flushPendingUpdates();
444 // Is this object already destroyed?
445 if ($this->__toString() != 'DestructedObject') {
446 // Destroy all informations about this class but keep some text about it alive
447 $this->setRealClass('DestructedObject');
448 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
449 // Already destructed object
450 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
455 // Do not call this twice
456 trigger_error(__METHOD__ . ': Called twice.');
462 * The __call() method where all non-implemented methods end up
464 * @param $methodName Name of the missing method
465 * @args $args Arguments passed to the method
468 public final function __call ($methodName, $args) {
469 return self::__callStatic($methodName, $args);
473 * The __callStatic() method where all non-implemented static methods end up
475 * @param $methodName Name of the missing method
476 * @args $args Arguments passed to the method
479 public static final function __callStatic ($methodName, $args) {
480 // Init argument string
483 // Is it NULL, empty or an array?
484 if (is_null($args)) {
486 $argsString = 'NULL';
487 } elseif (empty($args)) {
489 $argsString = '(empty)';
490 } elseif (is_array($args)) {
491 // Some arguments are there
492 foreach ($args as $arg) {
493 // Add the value itself if not array. This prevents 'array to string conversion' message
494 if (is_array($arg)) {
495 $argsString .= 'Array';
500 // Add data about the argument
501 $argsString .= ' (' . gettype($arg);
503 if (is_string($arg)) {
504 // Add length for strings
505 $argsString .= ', ' . strlen($arg);
506 } elseif (is_array($arg)) {
507 // .. or size if array
508 $argsString .= ', ' . count($arg);
509 } elseif ($arg === TRUE) {
510 // ... is boolean 'TRUE'
511 $argsString .= ', TRUE';
512 } elseif ($arg === FALSE) {
513 // ... is boolean 'FALSE'
514 $argsString .= ', FALSE';
518 $argsString .= '), ';
522 if (substr($argsString, -2, 1) == ',') {
523 $argsString = substr($argsString, 0, -2);
526 // Invalid arguments!
527 $argsString = '!INVALID:' . gettype($args) . '!';
530 // Output stub message
531 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
532 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
542 * Getter for $realClass
544 * @return $realClass The name of the real class (not BaseFrameworkSystem)
546 public function __toString () {
547 return $this->realClass;
551 * Magic method to catch setting of missing but set class fields/attributes
553 * @param $name Name of the field/attribute
554 * @param $value Value to store
557 public final function __set ($name, $value) {
558 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
561 print_r($value, TRUE)
566 * Magic method to catch getting of missing fields/attributes
568 * @param $name Name of the field/attribute
571 public final function __get ($name) {
572 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
578 * Magic method to catch unsetting of missing fields/attributes
580 * @param $name Name of the field/attribute
583 public final function __unset ($name) {
584 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
590 * Magic method to catch object serialization
592 * @return $unsupported Unsupported method
593 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
595 public final function __sleep () {
596 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
600 * Magic method to catch object deserialization
602 * @return $unsupported Unsupported method
603 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
605 public final function __wakeup () {
606 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
610 * Magic method to catch calls when an object instance is called
612 * @return $unsupported Unsupported method
613 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
615 public final function __invoke () {
616 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
620 * Setter for the real class name
622 * @param $realClass Class name (string)
625 public final function setRealClass ($realClass) {
627 $this->realClass = (string) $realClass;
631 * Setter for database result instance
633 * @param $resultInstance An instance of a database result class
635 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
637 protected final function setResultInstance (SearchableResult $resultInstance) {
638 $this->resultInstance = $resultInstance;
642 * Getter for database result instance
644 * @return $resultInstance An instance of a database result class
646 public final function getResultInstance () {
647 return $this->resultInstance;
651 * Setter for template engine instances
653 * @param $templateInstance An instance of a template engine class
656 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
657 $this->templateInstance = $templateInstance;
661 * Getter for template engine instances
663 * @return $templateInstance An instance of a template engine class
665 protected final function getTemplateInstance () {
666 return $this->templateInstance;
670 * Setter for search instance
672 * @param $searchInstance Searchable criteria instance
675 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
676 $this->searchInstance = $searchInstance;
680 * Getter for search instance
682 * @return $searchInstance Searchable criteria instance
684 public final function getSearchInstance () {
685 return $this->searchInstance;
689 * Setter for update instance
691 * @param $updateInstance Searchable criteria instance
694 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
695 $this->updateInstance = $updateInstance;
699 * Getter for update instance
701 * @return $updateInstance Updateable criteria instance
703 public final function getUpdateInstance () {
704 return $this->updateInstance;
708 * Setter for resolver instance
710 * @param $resolverInstance Instance of a command resolver class
713 public final function setResolverInstance (Resolver $resolverInstance) {
714 $this->resolverInstance = $resolverInstance;
718 * Getter for resolver instance
720 * @return $resolverInstance Instance of a command resolver class
722 public final function getResolverInstance () {
723 return $this->resolverInstance;
727 * Setter for language instance
729 * @param $configInstance The configuration instance which shall
730 * be FrameworkConfiguration
733 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
734 Registry::getRegistry()->addInstance('config', $configInstance);
738 * Getter for configuration instance
740 * @return $configInstance Configuration instance
742 public final function getConfigInstance () {
743 $configInstance = Registry::getRegistry()->getInstance('config');
744 return $configInstance;
748 * Setter for debug instance
750 * @param $debugInstance The instance for debug output class
753 public final function setDebugInstance (DebugMiddleware $debugInstance) {
754 Registry::getRegistry()->addInstance('debug', $debugInstance);
758 * Getter for debug instance
760 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
762 public final function getDebugInstance () {
763 // Get debug instance
764 $debugInstance = Registry::getRegistry()->getInstance('debug');
767 return $debugInstance;
771 * Setter for web output instance
773 * @param $webInstance The instance for web output class
776 public final function setWebOutputInstance (OutputStreamer $webInstance) {
777 Registry::getRegistry()->addInstance('web_output', $webInstance);
781 * Getter for web output instance
783 * @return $webOutputInstance - Instance to class WebOutput
785 public final function getWebOutputInstance () {
786 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
787 return $webOutputInstance;
791 * Setter for database instance
793 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
796 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
797 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
801 * Getter for database layer
803 * @return $databaseInstance The database layer instance
805 public final function getDatabaseInstance () {
807 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
810 return $databaseInstance;
814 * Setter for compressor channel
816 * @param $compressorInstance An instance of CompressorChannel
819 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
820 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
824 * Getter for compressor channel
826 * @return $compressorInstance The compressor channel
828 public final function getCompressorChannel () {
829 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
830 return $compressorInstance;
834 * Protected getter for a manageable application helper class
836 * @return $applicationInstance An instance of a manageable application helper class
838 protected final function getApplicationInstance () {
839 $applicationInstance = Registry::getRegistry()->getInstance('application');
840 return $applicationInstance;
844 * Setter for a manageable application helper class
846 * @param $applicationInstance An instance of a manageable application helper class
849 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
850 Registry::getRegistry()->addInstance('application', $applicationInstance);
854 * Setter for request instance
856 * @param $requestInstance An instance of a Requestable class
859 public final function setRequestInstance (Requestable $requestInstance) {
860 $this->requestInstance = $requestInstance;
864 * Getter for request instance
866 * @return $requestInstance An instance of a Requestable class
868 public final function getRequestInstance () {
869 return $this->requestInstance;
873 * Setter for response instance
875 * @param $responseInstance An instance of a Responseable class
878 public final function setResponseInstance (Responseable $responseInstance) {
879 $this->responseInstance = $responseInstance;
883 * Getter for response instance
885 * @return $responseInstance An instance of a Responseable class
887 public final function getResponseInstance () {
888 return $this->responseInstance;
892 * Private getter for language instance
894 * @return $langInstance An instance to the language sub-system
896 protected final function getLanguageInstance () {
897 $langInstance = Registry::getRegistry()->getInstance('language');
898 return $langInstance;
902 * Setter for language instance
904 * @param $langInstance An instance to the language sub-system
906 * @see LanguageSystem
908 public final function setLanguageInstance (ManageableLanguage $langInstance) {
909 Registry::getRegistry()->addInstance('language', $langInstance);
913 * Private getter for file IO instance
915 * @return $fileIoInstance An instance to the file I/O sub-system
917 protected final function getFileIoInstance () {
918 return $this->fileIoInstance;
922 * Setter for file I/O instance
924 * @param $fileIoInstance An instance to the file I/O sub-system
927 public final function setFileIoInstance (IoHandler $fileIoInstance) {
928 $this->fileIoInstance = $fileIoInstance;
932 * Protected setter for user instance
934 * @param $userInstance An instance of a user class
937 protected final function setUserInstance (ManageableAccount $userInstance) {
938 $this->userInstance = $userInstance;
942 * Getter for user instance
944 * @return $userInstance An instance of a user class
946 public final function getUserInstance () {
947 return $this->userInstance;
951 * Setter for controller instance (this surely breaks a bit the MVC patterm)
953 * @param $controllerInstance An instance of the controller
956 public final function setControllerInstance (Controller $controllerInstance) {
957 $this->controllerInstance = $controllerInstance;
961 * Getter for controller instance (this surely breaks a bit the MVC patterm)
963 * @return $controllerInstance An instance of the controller
965 public final function getControllerInstance () {
966 return $this->controllerInstance;
970 * Setter for RNG instance
972 * @param $rngInstance An instance of a random number generator (RNG)
975 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
976 $this->rngInstance = $rngInstance;
980 * Getter for RNG instance
982 * @return $rngInstance An instance of a random number generator (RNG)
984 public final function getRngInstance () {
985 return $this->rngInstance;
989 * Setter for Cryptable instance
991 * @param $cryptoInstance An instance of a Cryptable class
994 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
995 $this->cryptoInstance = $cryptoInstance;
999 * Getter for Cryptable instance
1001 * @return $cryptoInstance An instance of a Cryptable class
1003 public final function getCryptoInstance () {
1004 return $this->cryptoInstance;
1008 * Setter for the list instance
1010 * @param $listInstance A list of Listable
1013 protected final function setListInstance (Listable $listInstance) {
1014 $this->listInstance = $listInstance;
1018 * Getter for the list instance
1020 * @return $listInstance A list of Listable
1022 protected final function getListInstance () {
1023 return $this->listInstance;
1027 * Setter for the menu instance
1029 * @param $menuInstance A RenderableMenu instance
1032 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1033 $this->menuInstance = $menuInstance;
1037 * Getter for the menu instance
1039 * @return $menuInstance A RenderableMenu instance
1041 protected final function getMenuInstance () {
1042 return $this->menuInstance;
1046 * Setter for image instance
1048 * @param $imageInstance An instance of an image
1051 public final function setImageInstance (BaseImage $imageInstance) {
1052 $this->imageInstance = $imageInstance;
1056 * Getter for image instance
1058 * @return $imageInstance An instance of an image
1060 public final function getImageInstance () {
1061 return $this->imageInstance;
1065 * Setter for stacker instance
1067 * @param $stackInstance An instance of an stacker
1070 public final function setStackInstance (Stackable $stackInstance) {
1071 $this->stackInstance = $stackInstance;
1075 * Getter for stacker instance
1077 * @return $stackInstance An instance of an stacker
1079 public final function getStackInstance () {
1080 return $this->stackInstance;
1084 * Setter for compressor instance
1086 * @param $compressorInstance An instance of an compressor
1089 public final function setCompressorInstance (Compressor $compressorInstance) {
1090 $this->compressorInstance = $compressorInstance;
1094 * Getter for compressor instance
1096 * @return $compressorInstance An instance of an compressor
1098 public final function getCompressorInstance () {
1099 return $this->compressorInstance;
1103 * Setter for Parseable instance
1105 * @param $parserInstance An instance of an Parseable
1108 public final function setParserInstance (Parseable $parserInstance) {
1109 $this->parserInstance = $parserInstance;
1113 * Getter for Parseable instance
1115 * @return $parserInstance An instance of an Parseable
1117 public final function getParserInstance () {
1118 return $this->parserInstance;
1122 * Setter for HandleableProtocol instance
1124 * @param $protocolInstance An instance of an HandleableProtocol
1127 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1128 $this->protocolInstance = $protocolInstance;
1132 * Getter for HandleableProtocol instance
1134 * @return $protocolInstance An instance of an HandleableProtocol
1136 public final function getProtocolInstance () {
1137 return $this->protocolInstance;
1141 * Setter for DatabaseWrapper instance
1143 * @param $wrapperInstance An instance of an DatabaseWrapper
1146 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1147 $this->wrapperInstance = $wrapperInstance;
1151 * Getter for DatabaseWrapper instance
1153 * @return $wrapperInstance An instance of an DatabaseWrapper
1155 public final function getWrapperInstance () {
1156 return $this->wrapperInstance;
1160 * Setter for socket resource
1162 * @param $socketResource A valid socket resource
1165 public final function setSocketResource ($socketResource) {
1166 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1167 $this->socketResource = $socketResource;
1171 * Getter for socket resource
1173 * @return $socketResource A valid socket resource
1175 public final function getSocketResource () {
1176 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1177 return $this->socketResource;
1181 * Setter for regular expression
1183 * @param $regularExpression A valid regular expression
1186 public final function setRegularExpression ($regularExpression) {
1187 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1188 $this->regularExpression = $regularExpression;
1192 * Getter for regular expression
1194 * @return $regularExpression A valid regular expression
1196 public final function getRegularExpression () {
1197 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1198 return $this->regularExpression;
1202 * Setter for helper instance
1204 * @param $helperInstance An instance of a helper class
1207 protected final function setHelperInstance (Helper $helperInstance) {
1208 $this->helperInstance = $helperInstance;
1212 * Getter for helper instance
1214 * @return $helperInstance An instance of a helper class
1216 public final function getHelperInstance () {
1217 return $this->helperInstance;
1221 * Setter for a Source instance
1223 * @param $sourceInstance An instance of a Source class
1226 protected final function setSourceInstance (Source $sourceInstance) {
1227 $this->sourceInstance = $sourceInstance;
1231 * Getter for a Source instance
1233 * @return $sourceInstance An instance of a Source class
1235 protected final function getSourceInstance () {
1236 return $this->sourceInstance;
1240 * Setter for a UrlSource instance
1242 * @param $sourceInstance An instance of a UrlSource class
1245 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1246 $this->urlSourceInstance = $urlSourceInstance;
1250 * Getter for a UrlSource instance
1252 * @return $urlSourceInstance An instance of a UrlSource class
1254 protected final function getUrlSourceInstance () {
1255 return $this->urlSourceInstance;
1259 * Getter for a InputStream instance
1261 * @param $inputStreamInstance The InputStream instance
1263 protected final function getInputStreamInstance () {
1264 return $this->inputStreamInstance;
1268 * Setter for a InputStream instance
1270 * @param $inputStreamInstance The InputStream instance
1273 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1274 $this->inputStreamInstance = $inputStreamInstance;
1278 * Getter for a OutputStream instance
1280 * @param $outputStreamInstance The OutputStream instance
1282 protected final function getOutputStreamInstance () {
1283 return $this->outputStreamInstance;
1287 * Setter for a OutputStream instance
1289 * @param $outputStreamInstance The OutputStream instance
1292 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1293 $this->outputStreamInstance = $outputStreamInstance;
1297 * Setter for handler instance
1299 * @param $handlerInstance An instance of a Handleable class
1302 protected final function setHandlerInstance (Handleable $handlerInstance) {
1303 $this->handlerInstance = $handlerInstance;
1307 * Getter for handler instance
1309 * @return $handlerInstance A Networkable instance
1311 protected final function getHandlerInstance () {
1312 return $this->handlerInstance;
1316 * Setter for visitor instance
1318 * @param $visitorInstance A Visitor instance
1321 protected final function setVisitorInstance (Visitor $visitorInstance) {
1322 $this->visitorInstance = $visitorInstance;
1326 * Getter for visitor instance
1328 * @return $visitorInstance A Visitor instance
1330 protected final function getVisitorInstance () {
1331 return $this->visitorInstance;
1335 * Setter for DHT instance
1337 * @param $dhtInstance A Distributable instance
1340 protected final function setDhtInstance (Distributable $dhtInstance) {
1341 $this->dhtInstance = $dhtInstance;
1345 * Getter for DHT instance
1347 * @return $dhtInstance A Distributable instance
1349 protected final function getDhtInstance () {
1350 return $this->dhtInstance;
1354 * Setter for raw package Data
1356 * @param $packageData Raw package Data
1359 public final function setPackageData (array $packageData) {
1360 $this->packageData = $packageData;
1364 * Getter for raw package Data
1366 * @return $packageData Raw package Data
1368 public function getPackageData () {
1369 return $this->packageData;
1374 * Setter for Iterator instance
1376 * @param $iteratorInstance An instance of an Iterator
1379 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1380 $this->iteratorInstance = $iteratorInstance;
1384 * Getter for Iterator instance
1386 * @return $iteratorInstance An instance of an Iterator
1388 public final function getIteratorInstance () {
1389 return $this->iteratorInstance;
1393 * Setter for FilePointer instance
1395 * @param $pointerInstance An instance of an FilePointer class
1398 protected final function setPointerInstance (FilePointer $pointerInstance) {
1399 $this->pointerInstance = $pointerInstance;
1403 * Getter for FilePointer instance
1405 * @return $pointerInstance An instance of an FilePointer class
1407 public final function getPointerInstance () {
1408 return $this->pointerInstance;
1412 * Unsets pointer instance which triggers a call of __destruct() if the
1413 * instance is still there. This is surely not fatal on already "closed"
1414 * file pointer instances.
1416 * I don't want to mess around with above setter by giving it a default
1417 * value NULL as setter should always explicitly only set (existing) object
1418 * instances and NULL is NULL.
1422 protected final function unsetPointerInstance () {
1423 // Simply it to NULL
1424 $this->pointerInstance = NULL;
1428 * Setter for Indexable instance
1430 * @param $indexInstance An instance of an Indexable class
1433 protected final function setIndexInstance (Indexable $indexInstance) {
1434 $this->indexInstance = $indexInstance;
1438 * Getter for Indexable instance
1440 * @return $indexInstance An instance of an Indexable class
1442 public final function getIndexInstance () {
1443 return $this->indexInstance;
1447 * Setter for Block instance
1449 * @param $blockInstance An instance of an Block class
1452 protected final function setBlockInstance (Block $blockInstance) {
1453 $this->blockInstance = $blockInstance;
1457 * Getter for Block instance
1459 * @return $blockInstance An instance of an Block class
1461 public final function getBlockInstance () {
1462 return $this->blockInstance;
1466 * Setter for Minable instance
1468 * @param $minableInstance A Minable instance
1471 protected final function setMinableInstance (Minable $minableInstance) {
1472 $this->minableInstance = $minableInstance;
1476 * Getter for minable instance
1478 * @return $minableInstance A Minable instance
1480 protected final function getMinableInstance () {
1481 return $this->minableInstance;
1485 * Setter for FrameworkDirectory instance
1487 * @param $directoryInstance A FrameworkDirectoryPointer instance
1490 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1491 $this->directoryInstance = $directoryInstance;
1495 * Getter for FrameworkDirectory instance
1497 * @return $directoryInstance A FrameworkDirectory instance
1499 protected final function getDirectoryInstance () {
1500 return $this->directoryInstance;
1504 * Setter for listener instance
1506 * @param $listenerInstance A Listenable instance
1509 protected final function setListenerInstance (Listenable $listenerInstance) {
1510 $this->listenerInstance = $listenerInstance;
1514 * Getter for listener instance
1516 * @return $listenerInstance A Listenable instance
1518 protected final function getListenerInstance () {
1519 return $this->listenerInstance;
1523 * Getter for communicator instance
1525 * @return $communicatorInstance An instance of a Communicator class
1527 public final function getCommunicatorInstance () {
1528 return $this->communicatorInstance;
1532 * Setter for communicator instance
1534 * @param $communicatorInstance An instance of a Communicator class
1537 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1538 $this->communicatorInstance = $communicatorInstance;
1542 * Setter for state instance
1544 * @param $stateInstance A Stateable instance
1547 public final function setStateInstance (Stateable $stateInstance) {
1548 $this->stateInstance = $stateInstance;
1552 * Getter for state instance
1554 * @return $stateInstance A Stateable instance
1556 public final function getStateInstance () {
1557 return $this->stateInstance;
1561 * Setter for command name
1563 * @param $commandName Last validated command name
1566 protected final function setCommandName ($commandName) {
1567 $this->commandName = $commandName;
1571 * Getter for command name
1573 * @return $commandName Last validated command name
1575 protected final function getCommandName () {
1576 return $this->commandName;
1580 * Setter for controller name
1582 * @param $controllerName Last validated controller name
1585 protected final function setControllerName ($controllerName) {
1586 $this->controllerName = $controllerName;
1590 * Getter for controller name
1592 * @return $controllerName Last validated controller name
1594 protected final function getControllerName () {
1595 return $this->controllerName;
1599 * Checks whether an object equals this object. You should overwrite this
1600 * method to implement own equality checks
1602 * @param $objectInstance An instance of a FrameworkInterface object
1603 * @return $equals Whether both objects equals
1605 public function equals (FrameworkInterface $objectInstance) {
1608 $this->__toString() == $objectInstance->__toString()
1610 $this->hashCode() == $objectInstance->hashCode()
1613 // Return the result
1618 * Generates a generic hash code of this class. You should really overwrite
1619 * this method with your own hash code generator code. But keep KISS in mind.
1621 * @return $hashCode A generic hash code respresenting this whole class
1623 public function hashCode () {
1625 return crc32($this->__toString());
1629 * Formats computer generated price values into human-understandable formats
1630 * with thousand and decimal separators.
1632 * @param $value The in computer format value for a price
1633 * @param $currency The currency symbol (use HTML-valid characters!)
1634 * @param $decNum Number of decimals after commata
1635 * @return $price The for the current language formated price string
1636 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1637 * thousands separator
1640 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1641 // Are all required attriutes set?
1642 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1643 // Throw an exception
1644 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1648 $value = (float) $value;
1650 // Reformat the US number
1651 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1653 // Return as string...
1658 * Appends a trailing slash to a string
1660 * @param $str A string (maybe) without trailing slash
1661 * @return $str A string with an auto-appended trailing slash
1663 public final function addMissingTrailingSlash ($str) {
1664 // Is there a trailing slash?
1665 if (substr($str, -1, 1) != '/') {
1669 // Return string with trailing slash
1674 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1675 * application helper instance (ApplicationHelper by default).
1677 * @param $applicationInstance An application helper instance or
1678 * null if we shall use the default
1679 * @return $templateInstance The template engine instance
1680 * @throws NullPointerException If the discovered application
1681 * instance is still null
1683 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1684 // Is the application instance set?
1685 if (is_null($applicationInstance)) {
1686 // Get the current instance
1687 $applicationInstance = $this->getApplicationInstance();
1690 if (is_null($applicationInstance)) {
1691 // Thrown an exception
1692 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1696 // Initialize the template engine
1697 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1699 // Return the prepared instance
1700 return $templateInstance;
1704 * Debugs this instance by putting out it's full content
1706 * @param $message Optional message to show in debug output
1709 public final function debugInstance ($message = '') {
1710 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1711 restore_error_handler();
1716 // Is a message set?
1717 if (!empty($message)) {
1718 // Construct message
1719 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1722 // Generate the output
1723 $content .= sprintf('<pre>%s</pre>',
1726 print_r($this, TRUE)
1732 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>',
1733 $this->__toString(),
1735 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1740 * Replaces control characters with printable output
1742 * @param $str String with control characters
1743 * @return $str Replaced string
1745 protected function replaceControlCharacters ($str) {
1748 chr(13), '[r]', str_replace(
1749 chr(10), '[n]', str_replace(
1759 * Output a partial stub message for the caller method
1761 * @param $message An optional message to display
1764 protected function partialStub ($message = '') {
1765 // Get the backtrace
1766 $backtrace = debug_backtrace();
1768 // Generate the class::method string
1769 $methodName = 'UnknownClass->unknownMethod';
1770 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1771 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1774 // Construct the full message
1775 $stubMessage = sprintf('[%s:] Partial stub!',
1779 // Is the extra message given?
1780 if (!empty($message)) {
1781 // Then add it as well
1782 $stubMessage .= ' Message: ' . $message;
1785 // Debug instance is there?
1786 if (!is_null($this->getDebugInstance())) {
1787 // Output stub message
1788 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1791 trigger_error($stubMessage);
1797 * Outputs a debug backtrace and stops further script execution
1799 * @param $message An optional message to output
1800 * @param $doExit Whether exit the program (TRUE is default)
1803 public function debugBackTrace ($message = '', $doExit = TRUE) {
1804 // Sorry, there is no other way getting this nice backtrace
1805 if (!empty($message)) {
1807 printf('Message: %s<br />' . chr(10), $message);
1811 debug_print_backtrace();
1815 if ($doExit === TRUE) {
1821 * Creates an instance of a debugger instance
1823 * @param $className Name of the class (currently unsupported)
1824 * @return $debugInstance An instance of a debugger class
1826 public final static function createDebugInstance ($className) {
1827 // Is the instance set?
1828 if (!Registry::getRegistry()->instanceExists('debug')) {
1829 // Init debug instance
1830 $debugInstance = NULL;
1834 // Get a debugger instance
1835 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'));
1836 } catch (NullPointerException $e) {
1837 // Didn't work, no instance there
1838 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1841 // Empty string should be ignored and used for testing the middleware
1842 DebugMiddleware::getSelfInstance()->output('');
1844 // Set it in its own class. This will set it in the registry
1845 $debugInstance->setDebugInstance($debugInstance);
1847 // Get instance from registry
1848 $debugInstance = Registry::getRegistry()->getDebugInstance();
1852 return $debugInstance;
1856 * Simple output of a message with line-break
1858 * @param $message Message to output
1861 public function outputLine ($message) {
1863 print($message . PHP_EOL);
1867 * Outputs a debug message whether to debug instance (should be set!) or
1868 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1869 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1871 * @param $message Message we shall send out...
1872 * @param $doPrint Whether print or die here (default: print)
1873 * @paran $stripTags Whether to strip tags (default: FALSE)
1876 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1877 // Set debug instance to NULL
1878 $debugInstance = NULL;
1882 // Get debug instance
1883 $debugInstance = $this->getDebugInstance();
1884 } catch (NullPointerException $e) {
1885 // The debug instance is not set (yet)
1888 // Is the debug instance there?
1889 if (is_object($debugInstance)) {
1890 // Use debug output handler
1891 $debugInstance->output($message, $stripTags);
1893 if ($doPrint === FALSE) {
1894 // Die here if not printed
1898 // Are debug times enabled?
1899 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1901 $message = $this->getPrintableExecutionTime() . $message;
1905 if ($doPrint === TRUE) {
1907 $this->outputLine($message);
1916 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1918 * @param $str The string, what ever it is needs to be converted
1919 * @return $className Generated class name
1921 public static final function convertToClassName ($str) {
1925 // Convert all dashes in underscores
1926 $str = self::convertDashesToUnderscores($str);
1928 // Now use that underscores to get classname parts for hungarian style
1929 foreach (explode('_', $str) as $strPart) {
1930 // Make the class name part lower case and first upper case
1931 $className .= ucfirst(strtolower($strPart));
1934 // Return class name
1939 * Converts dashes to underscores, e.g. useable for configuration entries
1941 * @param $str The string with maybe dashes inside
1942 * @return $str The converted string with no dashed, but underscores
1944 public static final function convertDashesToUnderscores ($str) {
1946 $str = str_replace('-', '_', $str);
1948 // Return converted string
1953 * Marks up the code by adding e.g. line numbers
1955 * @param $phpCode Unmarked PHP code
1956 * @return $markedCode Marked PHP code
1958 public function markupCode ($phpCode) {
1963 $errorArray = error_get_last();
1965 // Init the code with error message
1966 if (is_array($errorArray)) {
1968 $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>',
1969 basename($errorArray['file']),
1970 $errorArray['line'],
1971 $errorArray['message'],
1976 // Add line number to the code
1977 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1979 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1981 htmlentities($code, ENT_QUOTES)
1990 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1991 * beatiful for web-based front-ends. If null is given a message id
1992 * null_timestamp will be resolved and returned.
1994 * @param $timestamp Timestamp to prepare (filter) for display
1995 * @return $readable A readable timestamp
1997 public function doFilterFormatTimestamp ($timestamp) {
1998 // Default value to return
2001 // Is the timestamp null?
2002 if (is_null($timestamp)) {
2003 // Get a message string
2004 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2006 switch ($this->getLanguageInstance()->getLanguageCode()) {
2007 case 'de': // German format is a bit different to default
2008 // Split the GMT stamp up
2009 $dateTime = explode(' ', $timestamp );
2010 $dateArray = explode('-', $dateTime[0]);
2011 $timeArray = explode(':', $dateTime[1]);
2013 // Construct the timestamp
2014 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2024 default: // Default is pass-through
2025 $readable = $timestamp;
2035 * Filter a given number into a localized number
2037 * @param $value The raw value from e.g. database
2038 * @return $localized Localized value
2040 public function doFilterFormatNumber ($value) {
2041 // Generate it from config and localize dependencies
2042 switch ($this->getLanguageInstance()->getLanguageCode()) {
2043 case 'de': // German format is a bit different to default
2044 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2047 default: // US, etc.
2048 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2057 * "Getter" for databse entry
2059 * @return $entry An array with database entries
2060 * @throws NullPointerException If the database result is not found
2061 * @throws InvalidDatabaseResultException If the database result is invalid
2063 protected final function getDatabaseEntry () {
2064 // Is there an instance?
2065 if (!$this->getResultInstance() instanceof SearchableResult) {
2066 // Throw an exception here
2067 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2071 $this->getResultInstance()->rewind();
2073 // Do we have an entry?
2074 if ($this->getResultInstance()->valid() === FALSE) {
2075 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2076 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2080 $this->getResultInstance()->next();
2083 $entry = $this->getResultInstance()->current();
2090 * Getter for field name
2092 * @param $fieldName Field name which we shall get
2093 * @return $fieldValue Field value from the user
2094 * @throws NullPointerException If the result instance is null
2096 public final function getField ($fieldName) {
2097 // Default field value
2100 // Get result instance
2101 $resultInstance = $this->getResultInstance();
2103 // Is this instance null?
2104 if (is_null($resultInstance)) {
2105 // Then the user instance is no longer valid (expired cookies?)
2106 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2109 // Get current array
2110 $fieldArray = $resultInstance->current();
2111 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2113 // Convert dashes to underscore
2114 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2116 // Does the field exist?
2117 if ($this->isFieldSet($fieldName)) {
2119 $fieldValue = $fieldArray[$fieldName2];
2120 } elseif (defined('DEVELOPER')) {
2121 // Missing field entry, may require debugging
2122 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2124 // Missing field entry, may require debugging
2125 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2133 * Checks if given field is set
2135 * @param $fieldName Field name to check
2136 * @return $isSet Whether the given field name is set
2137 * @throws NullPointerException If the result instance is null
2139 public function isFieldSet ($fieldName) {
2140 // Get result instance
2141 $resultInstance = $this->getResultInstance();
2143 // Is this instance null?
2144 if (is_null($resultInstance)) {
2145 // Then the user instance is no longer valid (expired cookies?)
2146 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2149 // Get current array
2150 $fieldArray = $resultInstance->current();
2151 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2153 // Convert dashes to underscore
2154 $fieldName = self::convertDashesToUnderscores($fieldName);
2157 $isSet = isset($fieldArray[$fieldName]);
2164 * Flushs all pending updates to the database layer
2168 public function flushPendingUpdates () {
2169 // Get result instance
2170 $resultInstance = $this->getResultInstance();
2172 // Do we have data to update?
2173 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2174 // Get wrapper class name config entry
2175 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2177 // Create object instance
2178 $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
2180 // Yes, then send the whole result to the database layer
2181 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2186 * Outputs a deprecation warning to the developer.
2188 * @param $message The message we shall output to the developer
2190 * @todo Write a logging mechanism for productive mode
2192 public function deprecationWarning ($message) {
2193 // Is developer mode active?
2194 if (defined('DEVELOPER')) {
2195 // Debug instance is there?
2196 if (!is_null($this->getDebugInstance())) {
2197 // Output stub message
2198 self::createDebugInstance(__CLASS__)->debugOutput($message);
2201 trigger_error($message . "<br />\n");
2205 // @TODO Finish this part!
2206 $this->partialStub('Developer mode inactive. Message:' . $message);
2211 * Checks whether the given PHP extension is loaded
2213 * @param $phpExtension The PHP extension we shall check
2214 * @return $isLoaded Whether the PHP extension is loaded
2216 public final function isPhpExtensionLoaded ($phpExtension) {
2218 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2225 * "Getter" as a time() replacement but with milliseconds. You should use this
2226 * method instead of the encapsulated getimeofday() function.
2228 * @return $milliTime Timestamp with milliseconds
2230 public function getMilliTime () {
2231 // Get the time of day as float
2232 $milliTime = gettimeofday(TRUE);
2239 * Idles (sleeps) for given milliseconds
2241 * @return $hasSlept Whether it goes fine
2243 public function idle ($milliSeconds) {
2244 // Sleep is fine by default
2247 // Idle so long with found function
2248 if (function_exists('time_sleep_until')) {
2249 // Get current time and add idle time
2250 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2252 // New PHP 5.1.0 function found, ignore errors
2253 $hasSlept = @time_sleep_until($sleepUntil);
2256 * My Sun station doesn't have that function even with latest PHP
2259 usleep($milliSeconds * 1000);
2266 * Converts a hexadecimal string, even with negative sign as first string to
2267 * a decimal number using BC functions.
2269 * This work is based on comment #86673 on php.net documentation page at:
2270 * <http://de.php.net/manual/en/function.dechex.php#86673>
2272 * @param $hex Hexadecimal string
2273 * @return $dec Decimal number
2275 protected function hex2dec ($hex) {
2276 // Convert to all lower-case
2277 $hex = strtolower($hex);
2279 // Detect sign (negative/positive numbers)
2281 if (substr($hex, 0, 1) == '-') {
2283 $hex = substr($hex, 1);
2286 // Decode the hexadecimal string into a decimal number
2288 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2289 $factor = self::$hexdec[substr($hex, $i, 1)];
2290 $dec = bcadd($dec, bcmul($factor, $e));
2293 // Return the decimal number
2294 return $sign . $dec;
2298 * Converts even very large decimal numbers, also signed, to a hexadecimal
2301 * This work is based on comment #97756 on php.net documentation page at:
2302 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2304 * @param $dec Decimal number, even with negative sign
2305 * @param $maxLength Optional maximum length of the string
2306 * @return $hex Hexadecimal string
2308 protected function dec2hex ($dec, $maxLength = 0) {
2309 // maxLength can be zero or devideable by 2
2310 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2312 // Detect sign (negative/positive numbers)
2319 // Encode the decimal number into a hexadecimal string
2322 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2324 } while ($dec >= 1);
2327 * Leading zeros are required for hex-decimal "numbers". In some
2328 * situations more leading zeros are wanted, so check for both
2331 if ($maxLength > 0) {
2332 // Prepend more zeros
2333 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2334 } elseif ((strlen($hex) % 2) != 0) {
2335 // Only make string's length dividable by 2
2339 // Return the hexadecimal string
2340 return $sign . $hex;
2344 * Converts a ASCII string (0 to 255) into a decimal number.
2346 * @param $asc The ASCII string to be converted
2347 * @return $dec Decimal number
2349 protected function asc2dec ($asc) {
2350 // Convert it into a hexadecimal number
2351 $hex = bin2hex($asc);
2353 // And back into a decimal number
2354 $dec = $this->hex2dec($hex);
2361 * Converts a decimal number into an ASCII string.
2363 * @param $dec Decimal number
2364 * @return $asc An ASCII string
2366 protected function dec2asc ($dec) {
2367 // First convert the number into a hexadecimal string
2368 $hex = $this->dec2hex($dec);
2370 // Then convert it into the ASCII string
2371 $asc = $this->hex2asc($hex);
2378 * Converts a hexadecimal number into an ASCII string. Negative numbers
2381 * @param $hex Hexadecimal string
2382 * @return $asc An ASCII string
2384 protected function hex2asc ($hex) {
2385 // Check for length, it must be devideable by 2
2386 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2387 assert((strlen($hex) % 2) == 0);
2391 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2392 // Get the decimal number of the chunk
2393 $part = hexdec(substr($hex, $idx, 2));
2395 // Add it to the final string
2399 // Return the final string
2404 * Checks whether the given encoded data was encoded with Base64
2406 * @param $encodedData Encoded data we shall check
2407 * @return $isBase64 Whether the encoded data is Base64
2409 protected function isBase64Encoded ($encodedData) {
2411 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2418 * "Getter" to get response/request type from analysis of the system.
2420 * @return $responseType Analyzed response type
2422 protected static function getResponseTypeFromSystem () {
2423 // Default is console
2424 $responseType = 'console';
2426 // Is 'HTTP_HOST' set?
2427 if (isset($_SERVER['HTTP_HOST'])) {
2429 * Then it is a HTML response/request as RSS and so on may be
2430 * transfered over HTTP as well.
2432 $responseType = 'html';
2436 return $responseType;
2440 * Gets a cache key from Criteria instance
2442 * @param $criteriaInstance An instance of a Criteria class
2443 * @param $onlyKeys Only use these keys for a cache key
2444 * @return $cacheKey A cache key suitable for lookup/storage purposes
2446 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2448 $cacheKey = sprintf('%s@%s',
2449 $this->__toString(),
2450 $criteriaInstance->getCacheKey($onlyKeys)
2454 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2459 * Getter for startup time in miliseconds
2461 * @return $startupTime Startup time in miliseconds
2463 protected function getStartupTime () {
2464 return self::$startupTime;
2468 * "Getter" for a printable currently execution time in nice braces
2470 * @return $executionTime Current execution time in nice braces
2472 protected function getPrintableExecutionTime () {
2473 // Caculate the execution time
2474 $executionTime = microtime(TRUE) - $this->getStartupTime();
2476 // Pack it in nice braces
2477 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2480 return $executionTime;
2484 * Hashes a given string with a simple but stronger hash function (no salt)
2485 * and hex-encode it.
2487 * @param $str The string to be hashed
2488 * @return $hash The hash from string $str
2490 public static final function hash ($str) {
2491 // Hash given string with (better secure) hasher
2492 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2499 * "Getter" for length of hash() output. This will be "cached" to speed up
2502 * @return $length Length of hash() output
2504 public static final function getHashLength () {
2506 if (is_null(self::$hashLength)) {
2507 // No, then hash a string and save its length.
2508 self::$hashLength = strlen(self::hash('abc123'));
2512 return self::$hashLength;
2516 * Checks whether the given number is really a number (only chars 0-9).
2518 * @param $num A string consisting only chars between 0 and 9
2519 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2520 * @param $assertMismatch Whether to assert mismatches
2521 * @return $ret The (hopefully) secured numbered value
2523 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2524 // Filter all numbers out
2525 $ret = preg_replace('/[^0123456789]/', '', $num);
2528 if ($castValue === TRUE) {
2529 // Cast to biggest numeric type
2530 $ret = (double) $ret;
2533 // Assert only if requested
2534 if ($assertMismatch === TRUE) {
2535 // Has the whole value changed?
2536 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2544 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2546 * @param $num A string consisting only chars between 0 and 9
2547 * @param $assertMismatch Whether to assert mismatches
2548 * @return $ret The (hopefully) secured hext-numbered value
2550 public function hexval ($num, $assertMismatch = FALSE) {
2551 // Filter all numbers out
2552 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2554 // Assert only if requested
2555 if ($assertMismatch === TRUE) {
2556 // Has the whole value changed?
2557 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2565 * Checks whether start/end marker are set
2567 * @param $data Data to be checked
2568 * @return $isset Whether start/end marker are set
2570 public final function ifStartEndMarkersSet ($data) {
2572 $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));
2574 // ... and return it
2579 * Determines if an element is set in the generic array
2581 * @param $keyGroup Main group for the key
2582 * @param $subGroup Sub group for the key
2583 * @param $key Key to check
2584 * @param $element Element to check
2585 * @return $isset Whether the given key is set
2587 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2589 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2592 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2598 * Determines if a key is set in the generic array
2600 * @param $keyGroup Main group for the key
2601 * @param $subGroup Sub group for the key
2602 * @param $key Key to check
2603 * @return $isset Whether the given key is set
2605 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2607 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2610 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2618 * Determines if a group is set in the generic array
2620 * @param $keyGroup Main group
2621 * @param $subGroup Sub group
2622 * @return $isset Whether the given group is set
2624 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2626 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2629 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2636 * Getter for sub key group
2638 * @param $keyGroup Main key group
2639 * @param $subGroup Sub key group
2640 * @return $array An array with all array elements
2642 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2644 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2645 // No, then abort here
2646 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2651 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2654 return $this->genericArray[$keyGroup][$subGroup];
2658 * Unsets a given key in generic array
2660 * @param $keyGroup Main group for the key
2661 * @param $subGroup Sub group for the key
2662 * @param $key Key to unset
2665 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2667 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2670 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2674 * Unsets a given element in generic array
2676 * @param $keyGroup Main group for the key
2677 * @param $subGroup Sub group for the key
2678 * @param $key Key to unset
2679 * @param $element Element to unset
2682 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2684 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2687 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2691 * Append a string to a given generic array key
2693 * @param $keyGroup Main group for the key
2694 * @param $subGroup Sub group for the key
2695 * @param $key Key to unset
2696 * @param $value Value to add/append
2699 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2701 //* 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);
2703 // Is it already there?
2704 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2706 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2709 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2714 * Append a string to a given generic array element
2716 * @param $keyGroup Main group for the key
2717 * @param $subGroup Sub group for the key
2718 * @param $key Key to unset
2719 * @param $element Element to check
2720 * @param $value Value to add/append
2723 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2725 //* 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);
2727 // Is it already there?
2728 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2730 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2733 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2738 * Initializes given generic array group
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 initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2748 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2750 // Is it already set?
2751 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2752 // Already initialized
2753 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2758 $this->genericArray[$keyGroup][$subGroup] = array();
2762 * Initializes given generic array key
2764 * @param $keyGroup Main group for the key
2765 * @param $subGroup Sub group for the key
2766 * @param $key Key to use
2767 * @param $forceInit Optionally force initialization
2770 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2772 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2774 // Is it already set?
2775 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2776 // Already initialized
2777 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2782 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2786 * Initializes given generic array element
2788 * @param $keyGroup Main group for the key
2789 * @param $subGroup Sub group for the key
2790 * @param $key Key to use
2791 * @param $element Element to use
2792 * @param $forceInit Optionally force initialization
2795 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2797 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2799 // Is it already set?
2800 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2801 // Already initialized
2802 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2807 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2811 * Pushes an element to a generic key
2813 * @param $keyGroup Main group for the key
2814 * @param $subGroup Sub group for the key
2815 * @param $key Key to use
2816 * @param $value Value to add/append
2817 * @return $count Number of array elements
2819 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2821 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2824 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2826 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2830 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2833 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2834 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2839 * Pushes an element to a generic array element
2841 * @param $keyGroup Main group for the key
2842 * @param $subGroup Sub group for the key
2843 * @param $key Key to use
2844 * @param $element Element to check
2845 * @param $value Value to add/append
2846 * @return $count Number of array elements
2848 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2850 //* 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));
2853 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2855 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2859 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2862 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2863 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2868 * Pops an element from a generic group
2870 * @param $keyGroup Main group for the key
2871 * @param $subGroup Sub group for the key
2872 * @param $key Key to unset
2873 * @return $value Last "popped" value
2875 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2877 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2880 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2882 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2887 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2890 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2891 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2896 * Shifts an element from a generic group
2898 * @param $keyGroup Main group for the key
2899 * @param $subGroup Sub group for the key
2900 * @param $key Key to unset
2901 * @return $value Last "popped" value
2903 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2905 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2908 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2910 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2915 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2918 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2919 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2924 * Count generic array group
2926 * @param $keyGroup Main group for the key
2927 * @return $count Count of given group
2929 protected final function countGenericArray ($keyGroup) {
2931 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2934 if (!isset($this->genericArray[$keyGroup])) {
2936 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2941 $count = count($this->genericArray[$keyGroup]);
2944 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2951 * Count generic array sub group
2953 * @param $keyGroup Main group for the key
2954 * @param $subGroup Sub group for the key
2955 * @return $count Count of given group
2957 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2959 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2962 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2964 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2969 $count = count($this->genericArray[$keyGroup][$subGroup]);
2972 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2979 * Count generic array elements
2981 * @param $keyGroup Main group for the key
2982 * @param $subGroup Sub group for the key
2983 * @para $key Key to count
2984 * @return $count Count of given key
2986 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2988 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2991 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2993 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2995 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2997 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3002 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3005 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3012 * Getter for whole generic group array
3014 * @param $keyGroup Key group to get
3015 * @return $array Whole generic array group
3017 protected final function getGenericArray ($keyGroup) {
3019 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3022 if (!isset($this->genericArray[$keyGroup])) {
3024 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3029 return $this->genericArray[$keyGroup];
3033 * Setter for generic array key
3035 * @param $keyGroup Key group to get
3036 * @param $subGroup Sub group for the key
3037 * @param $key Key to unset
3038 * @param $value Mixed value from generic array element
3041 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3043 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3046 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3050 * Getter for generic array key
3052 * @param $keyGroup Key group to get
3053 * @param $subGroup Sub group for the key
3054 * @param $key Key to unset
3055 * @return $value Mixed value from generic array element
3057 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3059 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3062 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3064 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3069 return $this->genericArray[$keyGroup][$subGroup][$key];
3073 * Sets a value in given generic array key/element
3075 * @param $keyGroup Main group for the key
3076 * @param $subGroup Sub group for the key
3077 * @param $key Key to set
3078 * @param $element Element to set
3079 * @param $value Value to set
3082 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3084 //* 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));
3087 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3091 * Getter for generic array element
3093 * @param $keyGroup Key group to get
3094 * @param $subGroup Sub group for the key
3095 * @param $key Key to look for
3096 * @param $element Element to look for
3097 * @return $value Mixed value from generic array element
3099 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3101 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3104 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3106 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3111 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3115 * Checks if a given sub group is valid (array)
3117 * @param $keyGroup Key group to get
3118 * @param $subGroup Sub group for the key
3119 * @return $isValid Whether given sub group is valid
3121 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3123 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3126 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3133 * Checks if a given key is valid (array)
3135 * @param $keyGroup Key group to get
3136 * @param $subGroup Sub group for the key
3137 * @param $key Key to check
3138 * @return $isValid Whether given sub group is valid
3140 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3142 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3145 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3152 * Initializes the web output instance
3156 protected function initWebOutputInstance () {
3157 // Get application instance
3158 $applicationInstance = Registry::getRegistry()->getInstance('app');
3160 // Is this a response instance?
3161 if ($this instanceof Responseable) {
3162 // Then set it in application instance
3163 $applicationInstance->setResponseInstance($this);
3166 // Init web output instance
3167 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3170 $this->setWebOutputInstance($outputInstance);
3174 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3176 * @param $boolean Boolean value
3177 * @return $translated Translated boolean value
3179 public static final function translateBooleanToYesNo ($boolean) {
3180 // Make sure it is really boolean
3181 assert(is_bool($boolean));
3184 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3186 // ... and return it
3191 * Encodes raw data (almost any type) by "serializing" it and then pack it
3192 * into a "binary format".
3194 * @param $rawData Raw data (almost any type)
3195 * @return $encoded Encoded data
3197 protected function encodeData ($rawData) {
3198 // Make sure no objects or resources pass through
3199 assert(!is_object($rawData));
3200 assert(!is_resource($rawData));
3202 // First "serialize" it (json_encode() is faster than serialize())
3203 $encoded = $this->packString(json_encode($rawData));
3210 * Pack a string into a "binary format". Please execuse me that this is
3211 * widely undocumented. :-(
3213 * @param $str Unpacked string
3214 * @return $packed Packed string
3215 * @todo Improve documentation
3217 protected function packString ($str) {
3219 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3221 // First compress the string (gzcompress is okay)
3222 $str = gzcompress($str);
3227 // And start the "encoding" loop
3228 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3230 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3231 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3233 if (($idx + $i) <= strlen($str)) {
3234 $ord = ord(substr($str, ($idx + $i), 1));
3236 $add = $ord * pow(256, $factor);
3240 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3244 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3245 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3247 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3248 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3254 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3259 * Checks whether the given file/path is in open_basedir(). This does not
3260 * gurantee that the file is actually readable and/or writeable. If you need
3261 * such gurantee then please use isReadableFile() instead.
3263 * @param $filePathName Name of the file/path to be checked
3264 * @return $isReachable Whether it is within open_basedir()
3266 public static function isReachableFilePath ($filePathName) {
3267 // Is not reachable by default
3268 $isReachable = FALSE;
3270 // Get open_basedir parameter
3271 $openBaseDir = ini_get('open_basedir');
3274 if (!empty($openBaseDir)) {
3275 // Check all entries
3276 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3277 // Check on existence
3278 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3280 $isReachable = TRUE;
3284 // If open_basedir is not set, all is allowed
3285 $isReachable = TRUE;
3289 return $isReachable;
3293 * Checks whether the give file is within open_basedir() (done by
3294 * isReachableFilePath()), is actually a file and is readable.
3296 * @param $fileName Name of the file to be checked
3297 * @return $isReadable Whether the file is readable (and therefor exists)
3299 public static function isReadableFile ($fileName) {
3300 // Default is not readable
3301 $isReadable = FALSE;
3303 // Is within parameters, so check if it is a file and readable
3304 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));