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 * The concrete output instance
224 private $outputInstance = NULL;
229 private $stateInstance = NULL;
232 * Thousands separator
234 private $thousands = '.'; // German
239 private $decimals = ','; // German
244 private $socketResource = FALSE;
247 * Regular expression to use for validation
249 private $regularExpression = '';
254 private $packageData = array();
259 private $genericArray = array();
264 private $commandName = '';
269 private $controllerName = '';
272 * Name of used protocol
274 private $protocolName = 'invalid';
277 * Array with bitmasks and such for pack/unpack methods to support both
278 * 32-bit and 64-bit systems
280 private $packingData = array(
283 'left' => 0xffff0000,
284 'right' => 0x0000ffff,
290 'left' => 0xffffffff00000000,
291 'right' => 0x00000000ffffffff,
298 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
300 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
302 private $archArrayElement = FALSE;
304 /***********************
305 * Exception codes.... *
306 ***********************/
308 // @todo Try to clean these constants up
309 const EXCEPTION_IS_NULL_POINTER = 0x001;
310 const EXCEPTION_IS_NO_OBJECT = 0x002;
311 const EXCEPTION_IS_NO_ARRAY = 0x003;
312 const EXCEPTION_MISSING_METHOD = 0x004;
313 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
314 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
315 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
316 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
317 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
318 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
319 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
320 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
321 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
322 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
323 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
324 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
325 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
326 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
327 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
328 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
329 const EXCEPTION_PATH_NOT_FOUND = 0x015;
330 const EXCEPTION_INVALID_PATH_NAME = 0x016;
331 const EXCEPTION_READ_PROTECED_PATH = 0x017;
332 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
333 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
334 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
335 const EXCEPTION_INVALID_RESOURCE = 0x01b;
336 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
337 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
338 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
339 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
340 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
341 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
342 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
343 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
344 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
345 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
346 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
347 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
348 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
349 const EXCEPTION_INVALID_STRING = 0x029;
350 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
351 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
352 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
353 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
354 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
355 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
356 const EXCEPTION_MISSING_ELEMENT = 0x030;
357 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
358 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
359 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
360 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
361 const EXCEPTION_FATAL_ERROR = 0x035;
362 const EXCEPTION_FILE_NOT_FOUND = 0x036;
363 const EXCEPTION_ASSERTION_FAILED = 0x037;
364 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
365 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
366 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
367 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
368 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
369 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
372 * Hexadecimal->Decimal translation array
374 private static $hexdec = array(
394 * Decimal->hexadecimal translation array
396 private static $dechex = array(
416 * Startup time in miliseconds
418 private static $startupTime = 0;
421 * Protected super constructor
423 * @param $className Name of the class
426 protected function __construct ($className) {
428 $this->setRealClass($className);
430 // Set configuration instance if no registry ...
431 if (!$this instanceof Register) {
432 // ... because registries doesn't need to be configured
433 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
436 // Is the startup time set? (0 cannot be TRUE anymore)
437 if (self::$startupTime == 0) {
439 self::$startupTime = microtime(TRUE);
443 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
447 * Destructor for all classes. You should not call this method on your own.
451 public function __destruct () {
452 // Flush any updated entries to the database
453 $this->flushPendingUpdates();
455 // Is this object already destroyed?
456 if ($this->__toString() != 'DestructedObject') {
457 // Destroy all informations about this class but keep some text about it alive
458 $this->setRealClass('DestructedObject');
459 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
460 // Already destructed object
461 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
466 // Do not call this twice
467 trigger_error(__METHOD__ . ': Called twice.');
473 * The __call() method where all non-implemented methods end up
475 * @param $methodName Name of the missing method
476 * @args $args Arguments passed to the method
479 public final function __call ($methodName, $args) {
480 return self::__callStatic($methodName, $args);
484 * The __callStatic() method where all non-implemented static methods end up
486 * @param $methodName Name of the missing method
487 * @args $args Arguments passed to the method
490 public static final function __callStatic ($methodName, $args) {
491 // Init argument string
494 // Is it NULL, empty or an array?
495 if (is_null($args)) {
497 $argsString = 'NULL';
498 } elseif (empty($args)) {
500 $argsString = '(empty)';
501 } elseif (is_array($args)) {
502 // Some arguments are there
503 foreach ($args as $arg) {
504 // Add the value itself if not array. This prevents 'array to string conversion' message
505 if (is_array($arg)) {
506 $argsString .= 'Array';
511 // Add data about the argument
512 $argsString .= ' (' . gettype($arg);
514 if (is_string($arg)) {
515 // Add length for strings
516 $argsString .= ', ' . strlen($arg);
517 } elseif (is_array($arg)) {
518 // .. or size if array
519 $argsString .= ', ' . count($arg);
520 } elseif ($arg === TRUE) {
521 // ... is boolean 'TRUE'
522 $argsString .= ', TRUE';
523 } elseif ($arg === FALSE) {
524 // ... is boolean 'FALSE'
525 $argsString .= ', FALSE';
529 $argsString .= '), ';
533 if (substr($argsString, -2, 1) == ',') {
534 $argsString = substr($argsString, 0, -2);
537 // Invalid arguments!
538 $argsString = '!INVALID:' . gettype($args) . '!';
541 // Output stub message
542 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
543 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
553 * Getter for $realClass
555 * @return $realClass The name of the real class (not BaseFrameworkSystem)
557 public function __toString () {
558 return $this->realClass;
562 * Magic method to catch setting of missing but set class fields/attributes
564 * @param $name Name of the field/attribute
565 * @param $value Value to store
568 public final function __set ($name, $value) {
569 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
572 print_r($value, TRUE)
577 * Magic method to catch getting of missing fields/attributes
579 * @param $name Name of the field/attribute
582 public final function __get ($name) {
583 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
589 * Magic method to catch unsetting of missing fields/attributes
591 * @param $name Name of the field/attribute
594 public final function __unset ($name) {
595 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
601 * Magic method to catch object serialization
603 * @return $unsupported Unsupported method
604 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
606 public final function __sleep () {
607 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
611 * Magic method to catch object deserialization
613 * @return $unsupported Unsupported method
614 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
616 public final function __wakeup () {
617 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
621 * Magic method to catch calls when an object instance is called
623 * @return $unsupported Unsupported method
624 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
626 public final function __invoke () {
627 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
631 * Setter for the real class name
633 * @param $realClass Class name (string)
636 public final function setRealClass ($realClass) {
638 $this->realClass = (string) $realClass;
642 * Setter for database result instance
644 * @param $resultInstance An instance of a database result class
646 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
648 protected final function setResultInstance (SearchableResult $resultInstance) {
649 $this->resultInstance = $resultInstance;
653 * Getter for database result instance
655 * @return $resultInstance An instance of a database result class
657 public final function getResultInstance () {
658 return $this->resultInstance;
662 * Setter for template engine instances
664 * @param $templateInstance An instance of a template engine class
667 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
668 $this->templateInstance = $templateInstance;
672 * Getter for template engine instances
674 * @return $templateInstance An instance of a template engine class
676 protected final function getTemplateInstance () {
677 return $this->templateInstance;
681 * Setter for search instance
683 * @param $searchInstance Searchable criteria instance
686 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
687 $this->searchInstance = $searchInstance;
691 * Getter for search instance
693 * @return $searchInstance Searchable criteria instance
695 public final function getSearchInstance () {
696 return $this->searchInstance;
700 * Setter for update instance
702 * @param $updateInstance Searchable criteria instance
705 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
706 $this->updateInstance = $updateInstance;
710 * Getter for update instance
712 * @return $updateInstance Updateable criteria instance
714 public final function getUpdateInstance () {
715 return $this->updateInstance;
719 * Setter for resolver instance
721 * @param $resolverInstance Instance of a command resolver class
724 public final function setResolverInstance (Resolver $resolverInstance) {
725 $this->resolverInstance = $resolverInstance;
729 * Getter for resolver instance
731 * @return $resolverInstance Instance of a command resolver class
733 public final function getResolverInstance () {
734 return $this->resolverInstance;
738 * Setter for language instance
740 * @param $configInstance The configuration instance which shall
741 * be FrameworkConfiguration
744 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
745 Registry::getRegistry()->addInstance('config', $configInstance);
749 * Getter for configuration instance
751 * @return $configInstance Configuration instance
753 public final function getConfigInstance () {
754 $configInstance = Registry::getRegistry()->getInstance('config');
755 return $configInstance;
759 * Setter for debug instance
761 * @param $debugInstance The instance for debug output class
764 public final function setDebugInstance (DebugMiddleware $debugInstance) {
765 Registry::getRegistry()->addInstance('debug', $debugInstance);
769 * Getter for debug instance
771 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
773 public final function getDebugInstance () {
774 // Get debug instance
775 $debugInstance = Registry::getRegistry()->getInstance('debug');
778 return $debugInstance;
782 * Setter for web output instance
784 * @param $webInstance The instance for web output class
787 public final function setWebOutputInstance (OutputStreamer $webInstance) {
788 Registry::getRegistry()->addInstance('web_output', $webInstance);
792 * Getter for web output instance
794 * @return $webOutputInstance - Instance to class WebOutput
796 public final function getWebOutputInstance () {
797 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
798 return $webOutputInstance;
802 * Setter for database instance
804 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
807 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
808 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
812 * Getter for database layer
814 * @return $databaseInstance The database layer instance
816 public final function getDatabaseInstance () {
818 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
821 return $databaseInstance;
825 * Setter for compressor channel
827 * @param $compressorInstance An instance of CompressorChannel
830 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
831 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
835 * Getter for compressor channel
837 * @return $compressorInstance The compressor channel
839 public final function getCompressorChannel () {
840 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
841 return $compressorInstance;
845 * Protected getter for a manageable application helper class
847 * @return $applicationInstance An instance of a manageable application helper class
849 protected final function getApplicationInstance () {
850 $applicationInstance = Registry::getRegistry()->getInstance('application');
851 return $applicationInstance;
855 * Setter for a manageable application helper class
857 * @param $applicationInstance An instance of a manageable application helper class
860 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
861 Registry::getRegistry()->addInstance('application', $applicationInstance);
865 * Setter for request instance
867 * @param $requestInstance An instance of a Requestable class
870 public final function setRequestInstance (Requestable $requestInstance) {
871 $this->requestInstance = $requestInstance;
875 * Getter for request instance
877 * @return $requestInstance An instance of a Requestable class
879 public final function getRequestInstance () {
880 return $this->requestInstance;
884 * Setter for response instance
886 * @param $responseInstance An instance of a Responseable class
889 public final function setResponseInstance (Responseable $responseInstance) {
890 $this->responseInstance = $responseInstance;
894 * Getter for response instance
896 * @return $responseInstance An instance of a Responseable class
898 public final function getResponseInstance () {
899 return $this->responseInstance;
903 * Private getter for language instance
905 * @return $langInstance An instance to the language sub-system
907 protected final function getLanguageInstance () {
908 $langInstance = Registry::getRegistry()->getInstance('language');
909 return $langInstance;
913 * Setter for language instance
915 * @param $langInstance An instance to the language sub-system
917 * @see LanguageSystem
919 public final function setLanguageInstance (ManageableLanguage $langInstance) {
920 Registry::getRegistry()->addInstance('language', $langInstance);
924 * Private getter for file IO instance
926 * @return $fileIoInstance An instance to the file I/O sub-system
928 protected final function getFileIoInstance () {
929 return $this->fileIoInstance;
933 * Setter for file I/O instance
935 * @param $fileIoInstance An instance to the file I/O sub-system
938 public final function setFileIoInstance (IoHandler $fileIoInstance) {
939 $this->fileIoInstance = $fileIoInstance;
943 * Protected setter for user instance
945 * @param $userInstance An instance of a user class
948 protected final function setUserInstance (ManageableAccount $userInstance) {
949 $this->userInstance = $userInstance;
953 * Getter for user instance
955 * @return $userInstance An instance of a user class
957 public final function getUserInstance () {
958 return $this->userInstance;
962 * Setter for controller instance (this surely breaks a bit the MVC patterm)
964 * @param $controllerInstance An instance of the controller
967 public final function setControllerInstance (Controller $controllerInstance) {
968 $this->controllerInstance = $controllerInstance;
972 * Getter for controller instance (this surely breaks a bit the MVC patterm)
974 * @return $controllerInstance An instance of the controller
976 public final function getControllerInstance () {
977 return $this->controllerInstance;
981 * Setter for RNG instance
983 * @param $rngInstance An instance of a random number generator (RNG)
986 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
987 $this->rngInstance = $rngInstance;
991 * Getter for RNG instance
993 * @return $rngInstance An instance of a random number generator (RNG)
995 public final function getRngInstance () {
996 return $this->rngInstance;
1000 * Setter for Cryptable instance
1002 * @param $cryptoInstance An instance of a Cryptable class
1005 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1006 $this->cryptoInstance = $cryptoInstance;
1010 * Getter for Cryptable instance
1012 * @return $cryptoInstance An instance of a Cryptable class
1014 public final function getCryptoInstance () {
1015 return $this->cryptoInstance;
1019 * Setter for the list instance
1021 * @param $listInstance A list of Listable
1024 protected final function setListInstance (Listable $listInstance) {
1025 $this->listInstance = $listInstance;
1029 * Getter for the list instance
1031 * @return $listInstance A list of Listable
1033 protected final function getListInstance () {
1034 return $this->listInstance;
1038 * Setter for the menu instance
1040 * @param $menuInstance A RenderableMenu instance
1043 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1044 $this->menuInstance = $menuInstance;
1048 * Getter for the menu instance
1050 * @return $menuInstance A RenderableMenu instance
1052 protected final function getMenuInstance () {
1053 return $this->menuInstance;
1057 * Setter for image instance
1059 * @param $imageInstance An instance of an image
1062 public final function setImageInstance (BaseImage $imageInstance) {
1063 $this->imageInstance = $imageInstance;
1067 * Getter for image instance
1069 * @return $imageInstance An instance of an image
1071 public final function getImageInstance () {
1072 return $this->imageInstance;
1076 * Setter for stacker instance
1078 * @param $stackInstance An instance of an stacker
1081 public final function setStackInstance (Stackable $stackInstance) {
1082 $this->stackInstance = $stackInstance;
1086 * Getter for stacker instance
1088 * @return $stackInstance An instance of an stacker
1090 public final function getStackInstance () {
1091 return $this->stackInstance;
1095 * Setter for compressor instance
1097 * @param $compressorInstance An instance of an compressor
1100 public final function setCompressorInstance (Compressor $compressorInstance) {
1101 $this->compressorInstance = $compressorInstance;
1105 * Getter for compressor instance
1107 * @return $compressorInstance An instance of an compressor
1109 public final function getCompressorInstance () {
1110 return $this->compressorInstance;
1114 * Setter for Parseable instance
1116 * @param $parserInstance An instance of an Parseable
1119 public final function setParserInstance (Parseable $parserInstance) {
1120 $this->parserInstance = $parserInstance;
1124 * Getter for Parseable instance
1126 * @return $parserInstance An instance of an Parseable
1128 public final function getParserInstance () {
1129 return $this->parserInstance;
1133 * Setter for HandleableProtocol instance
1135 * @param $protocolInstance An instance of an HandleableProtocol
1138 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1139 $this->protocolInstance = $protocolInstance;
1143 * Getter for HandleableProtocol instance
1145 * @return $protocolInstance An instance of an HandleableProtocol
1147 public final function getProtocolInstance () {
1148 return $this->protocolInstance;
1152 * Setter for DatabaseWrapper instance
1154 * @param $wrapperInstance An instance of an DatabaseWrapper
1157 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1158 $this->wrapperInstance = $wrapperInstance;
1162 * Getter for DatabaseWrapper instance
1164 * @return $wrapperInstance An instance of an DatabaseWrapper
1166 public final function getWrapperInstance () {
1167 return $this->wrapperInstance;
1171 * Setter for socket resource
1173 * @param $socketResource A valid socket resource
1176 public final function setSocketResource ($socketResource) {
1177 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1178 $this->socketResource = $socketResource;
1182 * Getter for socket resource
1184 * @return $socketResource A valid socket resource
1186 public final function getSocketResource () {
1187 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1188 return $this->socketResource;
1192 * Setter for regular expression
1194 * @param $regularExpression A valid regular expression
1197 public final function setRegularExpression ($regularExpression) {
1198 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1199 $this->regularExpression = $regularExpression;
1203 * Getter for regular expression
1205 * @return $regularExpression A valid regular expression
1207 public final function getRegularExpression () {
1208 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1209 return $this->regularExpression;
1213 * Setter for helper instance
1215 * @param $helperInstance An instance of a helper class
1218 protected final function setHelperInstance (Helper $helperInstance) {
1219 $this->helperInstance = $helperInstance;
1223 * Getter for helper instance
1225 * @return $helperInstance An instance of a helper class
1227 public final function getHelperInstance () {
1228 return $this->helperInstance;
1232 * Setter for a Source instance
1234 * @param $sourceInstance An instance of a Source class
1237 protected final function setSourceInstance (Source $sourceInstance) {
1238 $this->sourceInstance = $sourceInstance;
1242 * Getter for a Source instance
1244 * @return $sourceInstance An instance of a Source class
1246 protected final function getSourceInstance () {
1247 return $this->sourceInstance;
1251 * Setter for a UrlSource instance
1253 * @param $sourceInstance An instance of a UrlSource class
1256 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1257 $this->urlSourceInstance = $urlSourceInstance;
1261 * Getter for a UrlSource instance
1263 * @return $urlSourceInstance An instance of a UrlSource class
1265 protected final function getUrlSourceInstance () {
1266 return $this->urlSourceInstance;
1270 * Getter for a InputStream instance
1272 * @param $inputStreamInstance The InputStream instance
1274 protected final function getInputStreamInstance () {
1275 return $this->inputStreamInstance;
1279 * Setter for a InputStream instance
1281 * @param $inputStreamInstance The InputStream instance
1284 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1285 $this->inputStreamInstance = $inputStreamInstance;
1289 * Getter for a OutputStream instance
1291 * @param $outputStreamInstance The OutputStream instance
1293 protected final function getOutputStreamInstance () {
1294 return $this->outputStreamInstance;
1298 * Setter for a OutputStream instance
1300 * @param $outputStreamInstance The OutputStream instance
1303 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1304 $this->outputStreamInstance = $outputStreamInstance;
1308 * Setter for handler instance
1310 * @param $handlerInstance An instance of a Handleable class
1313 protected final function setHandlerInstance (Handleable $handlerInstance) {
1314 $this->handlerInstance = $handlerInstance;
1318 * Getter for handler instance
1320 * @return $handlerInstance A Networkable instance
1322 protected final function getHandlerInstance () {
1323 return $this->handlerInstance;
1327 * Setter for visitor instance
1329 * @param $visitorInstance A Visitor instance
1332 protected final function setVisitorInstance (Visitor $visitorInstance) {
1333 $this->visitorInstance = $visitorInstance;
1337 * Getter for visitor instance
1339 * @return $visitorInstance A Visitor instance
1341 protected final function getVisitorInstance () {
1342 return $this->visitorInstance;
1346 * Setter for DHT instance
1348 * @param $dhtInstance A Distributable instance
1351 protected final function setDhtInstance (Distributable $dhtInstance) {
1352 $this->dhtInstance = $dhtInstance;
1356 * Getter for DHT instance
1358 * @return $dhtInstance A Distributable instance
1360 protected final function getDhtInstance () {
1361 return $this->dhtInstance;
1365 * Setter for raw package Data
1367 * @param $packageData Raw package Data
1370 public final function setPackageData (array $packageData) {
1371 $this->packageData = $packageData;
1375 * Getter for raw package Data
1377 * @return $packageData Raw package Data
1379 public function getPackageData () {
1380 return $this->packageData;
1385 * Setter for Iterator instance
1387 * @param $iteratorInstance An instance of an Iterator
1390 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1391 $this->iteratorInstance = $iteratorInstance;
1395 * Getter for Iterator instance
1397 * @return $iteratorInstance An instance of an Iterator
1399 public final function getIteratorInstance () {
1400 return $this->iteratorInstance;
1404 * Setter for FilePointer instance
1406 * @param $pointerInstance An instance of an FilePointer class
1409 protected final function setPointerInstance (FilePointer $pointerInstance) {
1410 $this->pointerInstance = $pointerInstance;
1414 * Getter for FilePointer instance
1416 * @return $pointerInstance An instance of an FilePointer class
1418 public final function getPointerInstance () {
1419 return $this->pointerInstance;
1423 * Unsets pointer instance which triggers a call of __destruct() if the
1424 * instance is still there. This is surely not fatal on already "closed"
1425 * file pointer instances.
1427 * I don't want to mess around with above setter by giving it a default
1428 * value NULL as setter should always explicitly only set (existing) object
1429 * instances and NULL is NULL.
1433 protected final function unsetPointerInstance () {
1434 // Simply it to NULL
1435 $this->pointerInstance = NULL;
1439 * Setter for Indexable instance
1441 * @param $indexInstance An instance of an Indexable class
1444 protected final function setIndexInstance (Indexable $indexInstance) {
1445 $this->indexInstance = $indexInstance;
1449 * Getter for Indexable instance
1451 * @return $indexInstance An instance of an Indexable class
1453 public final function getIndexInstance () {
1454 return $this->indexInstance;
1458 * Setter for Block instance
1460 * @param $blockInstance An instance of an Block class
1463 protected final function setBlockInstance (Block $blockInstance) {
1464 $this->blockInstance = $blockInstance;
1468 * Getter for Block instance
1470 * @return $blockInstance An instance of an Block class
1472 public final function getBlockInstance () {
1473 return $this->blockInstance;
1477 * Setter for Minable instance
1479 * @param $minableInstance A Minable instance
1482 protected final function setMinableInstance (Minable $minableInstance) {
1483 $this->minableInstance = $minableInstance;
1487 * Getter for minable instance
1489 * @return $minableInstance A Minable instance
1491 protected final function getMinableInstance () {
1492 return $this->minableInstance;
1496 * Setter for FrameworkDirectory instance
1498 * @param $directoryInstance A FrameworkDirectoryPointer instance
1501 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1502 $this->directoryInstance = $directoryInstance;
1506 * Getter for FrameworkDirectory instance
1508 * @return $directoryInstance A FrameworkDirectory instance
1510 protected final function getDirectoryInstance () {
1511 return $this->directoryInstance;
1515 * Setter for listener instance
1517 * @param $listenerInstance A Listenable instance
1520 protected final function setListenerInstance (Listenable $listenerInstance) {
1521 $this->listenerInstance = $listenerInstance;
1525 * Getter for listener instance
1527 * @return $listenerInstance A Listenable instance
1529 protected final function getListenerInstance () {
1530 return $this->listenerInstance;
1534 * Getter for communicator instance
1536 * @return $communicatorInstance An instance of a Communicator class
1538 public final function getCommunicatorInstance () {
1539 return $this->communicatorInstance;
1543 * Setter for communicator instance
1545 * @param $communicatorInstance An instance of a Communicator class
1548 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1549 $this->communicatorInstance = $communicatorInstance;
1553 * Setter for state instance
1555 * @param $stateInstance A Stateable instance
1558 public final function setStateInstance (Stateable $stateInstance) {
1559 $this->stateInstance = $stateInstance;
1563 * Getter for state instance
1565 * @return $stateInstance A Stateable instance
1567 public final function getStateInstance () {
1568 return $this->stateInstance;
1572 * Setter for output instance
1574 * @param $outputInstance The debug output instance
1577 public final function setOutputInstance (OutputStreamer $outputInstance) {
1578 $this->outputInstance = $outputInstance;
1582 * Getter for output instance
1584 * @return $outputInstance The debug output instance
1586 public final function getOutputInstance () {
1587 return $this->outputInstance;
1591 * Setter for command name
1593 * @param $commandName Last validated command name
1596 protected final function setCommandName ($commandName) {
1597 $this->commandName = $commandName;
1601 * Getter for command name
1603 * @return $commandName Last validated command name
1605 protected final function getCommandName () {
1606 return $this->commandName;
1610 * Setter for controller name
1612 * @param $controllerName Last validated controller name
1615 protected final function setControllerName ($controllerName) {
1616 $this->controllerName = $controllerName;
1620 * Getter for controller name
1622 * @return $controllerName Last validated controller name
1624 protected final function getControllerName () {
1625 return $this->controllerName;
1629 * Getter for protocol name
1631 * @return $protocolName Name of used protocol
1633 public final function getProtocolName () {
1634 return $this->protocolName;
1638 * Setter for protocol name
1640 * @param $protocolName Name of used protocol
1643 protected final function setProtocolName ($protocolName) {
1644 $this->protocolName = $protocolName;
1648 * Checks whether an object equals this object. You should overwrite this
1649 * method to implement own equality checks
1651 * @param $objectInstance An instance of a FrameworkInterface object
1652 * @return $equals Whether both objects equals
1654 public function equals (FrameworkInterface $objectInstance) {
1657 $this->__toString() == $objectInstance->__toString()
1659 $this->hashCode() == $objectInstance->hashCode()
1662 // Return the result
1667 * Generates a generic hash code of this class. You should really overwrite
1668 * this method with your own hash code generator code. But keep KISS in mind.
1670 * @return $hashCode A generic hash code respresenting this whole class
1672 public function hashCode () {
1674 return crc32($this->__toString());
1678 * Formats computer generated price values into human-understandable formats
1679 * with thousand and decimal separators.
1681 * @param $value The in computer format value for a price
1682 * @param $currency The currency symbol (use HTML-valid characters!)
1683 * @param $decNum Number of decimals after commata
1684 * @return $price The for the current language formated price string
1685 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1686 * thousands separator
1689 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1690 // Are all required attriutes set?
1691 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1692 // Throw an exception
1693 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1697 $value = (float) $value;
1699 // Reformat the US number
1700 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1702 // Return as string...
1707 * Appends a trailing slash to a string
1709 * @param $str A string (maybe) without trailing slash
1710 * @return $str A string with an auto-appended trailing slash
1712 public final function addMissingTrailingSlash ($str) {
1713 // Is there a trailing slash?
1714 if (substr($str, -1, 1) != '/') {
1718 // Return string with trailing slash
1723 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1724 * application helper instance (ApplicationHelper by default).
1726 * @param $applicationInstance An application helper instance or
1727 * null if we shall use the default
1728 * @return $templateInstance The template engine instance
1729 * @throws NullPointerException If the discovered application
1730 * instance is still null
1732 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1733 // Is the application instance set?
1734 if (is_null($applicationInstance)) {
1735 // Get the current instance
1736 $applicationInstance = $this->getApplicationInstance();
1739 if (is_null($applicationInstance)) {
1740 // Thrown an exception
1741 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1745 // Initialize the template engine
1746 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1748 // Return the prepared instance
1749 return $templateInstance;
1753 * Debugs this instance by putting out it's full content
1755 * @param $message Optional message to show in debug output
1758 public final function debugInstance ($message = '') {
1759 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1760 restore_error_handler();
1765 // Is a message set?
1766 if (!empty($message)) {
1767 // Construct message
1768 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1771 // Generate the output
1772 $content .= sprintf('<pre>%s</pre>',
1775 print_r($this, TRUE)
1781 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>',
1782 $this->__toString(),
1784 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1789 * Replaces control characters with printable output
1791 * @param $str String with control characters
1792 * @return $str Replaced string
1794 protected function replaceControlCharacters ($str) {
1797 chr(13), '[r]', str_replace(
1798 chr(10), '[n]', str_replace(
1808 * Output a partial stub message for the caller method
1810 * @param $message An optional message to display
1813 protected function partialStub ($message = '') {
1814 // Get the backtrace
1815 $backtrace = debug_backtrace();
1817 // Generate the class::method string
1818 $methodName = 'UnknownClass->unknownMethod';
1819 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1820 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1823 // Construct the full message
1824 $stubMessage = sprintf('[%s:] Partial stub!',
1828 // Is the extra message given?
1829 if (!empty($message)) {
1830 // Then add it as well
1831 $stubMessage .= ' Message: ' . $message;
1834 // Debug instance is there?
1835 if (!is_null($this->getDebugInstance())) {
1836 // Output stub message
1837 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1840 trigger_error($stubMessage);
1846 * Outputs a debug backtrace and stops further script execution
1848 * @param $message An optional message to output
1849 * @param $doExit Whether exit the program (TRUE is default)
1852 public function debugBackTrace ($message = '', $doExit = TRUE) {
1853 // Sorry, there is no other way getting this nice backtrace
1854 if (!empty($message)) {
1856 printf('Message: %s<br />' . chr(10), $message);
1860 debug_print_backtrace();
1864 if ($doExit === TRUE) {
1870 * Creates an instance of a debugger instance
1872 * @param $className Name of the class (currently unsupported)
1873 * @return $debugInstance An instance of a debugger class
1874 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1876 public final static function createDebugInstance ($className) {
1877 // Is the instance set?
1878 if (!Registry::getRegistry()->instanceExists('debug')) {
1879 // Init debug instance
1880 $debugInstance = NULL;
1884 // Get a debugger instance
1885 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1886 } catch (NullPointerException $e) {
1887 // Didn't work, no instance there
1888 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1891 // Empty string should be ignored and used for testing the middleware
1892 DebugMiddleware::getSelfInstance()->output('');
1894 // Set it in its own class. This will set it in the registry
1895 $debugInstance->setDebugInstance($debugInstance);
1897 // Get instance from registry
1898 $debugInstance = Registry::getRegistry()->getDebugInstance();
1902 return $debugInstance;
1906 * Simple output of a message with line-break
1908 * @param $message Message to output
1911 public function outputLine ($message) {
1913 print($message . PHP_EOL);
1917 * Outputs a debug message whether to debug instance (should be set!) or
1918 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1919 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1921 * @param $message Message we shall send out...
1922 * @param $doPrint Whether print or die here (default: print)
1923 * @paran $stripTags Whether to strip tags (default: FALSE)
1926 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1927 // Set debug instance to NULL
1928 $debugInstance = NULL;
1932 // Get debug instance
1933 $debugInstance = $this->getDebugInstance();
1934 } catch (NullPointerException $e) {
1935 // The debug instance is not set (yet)
1938 // Is the debug instance there?
1939 if (is_object($debugInstance)) {
1940 // Use debug output handler
1941 $debugInstance->output($message, $stripTags);
1943 if ($doPrint === FALSE) {
1944 // Die here if not printed
1948 // Are debug times enabled?
1949 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1951 $message = $this->getPrintableExecutionTime() . $message;
1955 if ($doPrint === TRUE) {
1957 $this->outputLine($message);
1966 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1968 * @param $str The string, what ever it is needs to be converted
1969 * @return $className Generated class name
1971 public static final function convertToClassName ($str) {
1975 // Convert all dashes in underscores
1976 $str = self::convertDashesToUnderscores($str);
1978 // Now use that underscores to get classname parts for hungarian style
1979 foreach (explode('_', $str) as $strPart) {
1980 // Make the class name part lower case and first upper case
1981 $className .= ucfirst(strtolower($strPart));
1984 // Return class name
1989 * Converts dashes to underscores, e.g. useable for configuration entries
1991 * @param $str The string with maybe dashes inside
1992 * @return $str The converted string with no dashed, but underscores
1994 public static final function convertDashesToUnderscores ($str) {
1996 $str = str_replace('-', '_', $str);
1998 // Return converted string
2003 * Marks up the code by adding e.g. line numbers
2005 * @param $phpCode Unmarked PHP code
2006 * @return $markedCode Marked PHP code
2008 public function markupCode ($phpCode) {
2013 $errorArray = error_get_last();
2015 // Init the code with error message
2016 if (is_array($errorArray)) {
2018 $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>',
2019 basename($errorArray['file']),
2020 $errorArray['line'],
2021 $errorArray['message'],
2026 // Add line number to the code
2027 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2029 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
2031 htmlentities($code, ENT_QUOTES)
2040 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2041 * beatiful for web-based front-ends. If null is given a message id
2042 * null_timestamp will be resolved and returned.
2044 * @param $timestamp Timestamp to prepare (filter) for display
2045 * @return $readable A readable timestamp
2047 public function doFilterFormatTimestamp ($timestamp) {
2048 // Default value to return
2051 // Is the timestamp null?
2052 if (is_null($timestamp)) {
2053 // Get a message string
2054 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2056 switch ($this->getLanguageInstance()->getLanguageCode()) {
2057 case 'de': // German format is a bit different to default
2058 // Split the GMT stamp up
2059 $dateTime = explode(' ', $timestamp );
2060 $dateArray = explode('-', $dateTime[0]);
2061 $timeArray = explode(':', $dateTime[1]);
2063 // Construct the timestamp
2064 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2074 default: // Default is pass-through
2075 $readable = $timestamp;
2085 * Filter a given number into a localized number
2087 * @param $value The raw value from e.g. database
2088 * @return $localized Localized value
2090 public function doFilterFormatNumber ($value) {
2091 // Generate it from config and localize dependencies
2092 switch ($this->getLanguageInstance()->getLanguageCode()) {
2093 case 'de': // German format is a bit different to default
2094 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2097 default: // US, etc.
2098 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2107 * "Getter" for databse entry
2109 * @return $entry An array with database entries
2110 * @throws NullPointerException If the database result is not found
2111 * @throws InvalidDatabaseResultException If the database result is invalid
2113 protected final function getDatabaseEntry () {
2114 // Is there an instance?
2115 if (!$this->getResultInstance() instanceof SearchableResult) {
2116 // Throw an exception here
2117 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2121 $this->getResultInstance()->rewind();
2123 // Do we have an entry?
2124 if ($this->getResultInstance()->valid() === FALSE) {
2125 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2126 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2130 $this->getResultInstance()->next();
2133 $entry = $this->getResultInstance()->current();
2140 * Getter for field name
2142 * @param $fieldName Field name which we shall get
2143 * @return $fieldValue Field value from the user
2144 * @throws NullPointerException If the result instance is null
2146 public final function getField ($fieldName) {
2147 // Default field value
2150 // Get result instance
2151 $resultInstance = $this->getResultInstance();
2153 // Is this instance null?
2154 if (is_null($resultInstance)) {
2155 // Then the user instance is no longer valid (expired cookies?)
2156 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2159 // Get current array
2160 $fieldArray = $resultInstance->current();
2161 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2163 // Convert dashes to underscore
2164 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2166 // Does the field exist?
2167 if ($this->isFieldSet($fieldName)) {
2169 $fieldValue = $fieldArray[$fieldName2];
2170 } elseif (defined('DEVELOPER')) {
2171 // Missing field entry, may require debugging
2172 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2174 // Missing field entry, may require debugging
2175 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2183 * Checks if given field is set
2185 * @param $fieldName Field name to check
2186 * @return $isSet Whether the given field name is set
2187 * @throws NullPointerException If the result instance is null
2189 public function isFieldSet ($fieldName) {
2190 // Get result instance
2191 $resultInstance = $this->getResultInstance();
2193 // Is this instance null?
2194 if (is_null($resultInstance)) {
2195 // Then the user instance is no longer valid (expired cookies?)
2196 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2199 // Get current array
2200 $fieldArray = $resultInstance->current();
2201 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2203 // Convert dashes to underscore
2204 $fieldName = self::convertDashesToUnderscores($fieldName);
2207 $isSet = isset($fieldArray[$fieldName]);
2214 * Flushs all pending updates to the database layer
2218 public function flushPendingUpdates () {
2219 // Get result instance
2220 $resultInstance = $this->getResultInstance();
2222 // Do we have data to update?
2223 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2224 // Get wrapper class name config entry
2225 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2227 // Create object instance
2228 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2230 // Yes, then send the whole result to the database layer
2231 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2236 * Outputs a deprecation warning to the developer.
2238 * @param $message The message we shall output to the developer
2240 * @todo Write a logging mechanism for productive mode
2242 public function deprecationWarning ($message) {
2243 // Is developer mode active?
2244 if (defined('DEVELOPER')) {
2245 // Debug instance is there?
2246 if (!is_null($this->getDebugInstance())) {
2247 // Output stub message
2248 self::createDebugInstance(__CLASS__)->debugOutput($message);
2251 trigger_error($message . "<br />\n");
2255 // @TODO Finish this part!
2256 $this->partialStub('Developer mode inactive. Message:' . $message);
2261 * Checks whether the given PHP extension is loaded
2263 * @param $phpExtension The PHP extension we shall check
2264 * @return $isLoaded Whether the PHP extension is loaded
2266 public final function isPhpExtensionLoaded ($phpExtension) {
2268 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2275 * "Getter" as a time() replacement but with milliseconds. You should use this
2276 * method instead of the encapsulated getimeofday() function.
2278 * @return $milliTime Timestamp with milliseconds
2280 public function getMilliTime () {
2281 // Get the time of day as float
2282 $milliTime = gettimeofday(TRUE);
2289 * Idles (sleeps) for given milliseconds
2291 * @return $hasSlept Whether it goes fine
2293 public function idle ($milliSeconds) {
2294 // Sleep is fine by default
2297 // Idle so long with found function
2298 if (function_exists('time_sleep_until')) {
2299 // Get current time and add idle time
2300 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2302 // New PHP 5.1.0 function found, ignore errors
2303 $hasSlept = @time_sleep_until($sleepUntil);
2306 * My Sun station doesn't have that function even with latest PHP
2309 usleep($milliSeconds * 1000);
2316 * Converts a hexadecimal string, even with negative sign as first string to
2317 * a decimal number using BC functions.
2319 * This work is based on comment #86673 on php.net documentation page at:
2320 * <http://de.php.net/manual/en/function.dechex.php#86673>
2322 * @param $hex Hexadecimal string
2323 * @return $dec Decimal number
2325 protected function hex2dec ($hex) {
2326 // Convert to all lower-case
2327 $hex = strtolower($hex);
2329 // Detect sign (negative/positive numbers)
2331 if (substr($hex, 0, 1) == '-') {
2333 $hex = substr($hex, 1);
2336 // Decode the hexadecimal string into a decimal number
2338 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2339 $factor = self::$hexdec[substr($hex, $i, 1)];
2340 $dec = bcadd($dec, bcmul($factor, $e));
2343 // Return the decimal number
2344 return $sign . $dec;
2348 * Converts even very large decimal numbers, also signed, to a hexadecimal
2351 * This work is based on comment #97756 on php.net documentation page at:
2352 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2354 * @param $dec Decimal number, even with negative sign
2355 * @param $maxLength Optional maximum length of the string
2356 * @return $hex Hexadecimal string
2358 protected function dec2hex ($dec, $maxLength = 0) {
2359 // maxLength can be zero or devideable by 2
2360 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2362 // Detect sign (negative/positive numbers)
2369 // Encode the decimal number into a hexadecimal string
2372 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2374 } while ($dec >= 1);
2377 * Leading zeros are required for hex-decimal "numbers". In some
2378 * situations more leading zeros are wanted, so check for both
2381 if ($maxLength > 0) {
2382 // Prepend more zeros
2383 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2384 } elseif ((strlen($hex) % 2) != 0) {
2385 // Only make string's length dividable by 2
2389 // Return the hexadecimal string
2390 return $sign . $hex;
2394 * Converts a ASCII string (0 to 255) into a decimal number.
2396 * @param $asc The ASCII string to be converted
2397 * @return $dec Decimal number
2399 protected function asc2dec ($asc) {
2400 // Convert it into a hexadecimal number
2401 $hex = bin2hex($asc);
2403 // And back into a decimal number
2404 $dec = $this->hex2dec($hex);
2411 * Converts a decimal number into an ASCII string.
2413 * @param $dec Decimal number
2414 * @return $asc An ASCII string
2416 protected function dec2asc ($dec) {
2417 // First convert the number into a hexadecimal string
2418 $hex = $this->dec2hex($dec);
2420 // Then convert it into the ASCII string
2421 $asc = $this->hex2asc($hex);
2428 * Converts a hexadecimal number into an ASCII string. Negative numbers
2431 * @param $hex Hexadecimal string
2432 * @return $asc An ASCII string
2434 protected function hex2asc ($hex) {
2435 // Check for length, it must be devideable by 2
2436 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2437 assert((strlen($hex) % 2) == 0);
2441 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2442 // Get the decimal number of the chunk
2443 $part = hexdec(substr($hex, $idx, 2));
2445 // Add it to the final string
2449 // Return the final string
2454 * Checks whether the given encoded data was encoded with Base64
2456 * @param $encodedData Encoded data we shall check
2457 * @return $isBase64 Whether the encoded data is Base64
2459 protected function isBase64Encoded ($encodedData) {
2461 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2468 * "Getter" to get response/request type from analysis of the system.
2470 * @return $responseType Analyzed response type
2472 protected static function getResponseTypeFromSystem () {
2473 // Default is console
2474 $responseType = 'console';
2476 // Is 'HTTP_HOST' set?
2477 if (isset($_SERVER['HTTP_HOST'])) {
2479 * Then it is a HTML response/request as RSS and so on may be
2480 * transfered over HTTP as well.
2482 $responseType = 'html';
2486 return $responseType;
2490 * Gets a cache key from Criteria instance
2492 * @param $criteriaInstance An instance of a Criteria class
2493 * @param $onlyKeys Only use these keys for a cache key
2494 * @return $cacheKey A cache key suitable for lookup/storage purposes
2496 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2498 $cacheKey = sprintf('%s@%s',
2499 $this->__toString(),
2500 $criteriaInstance->getCacheKey($onlyKeys)
2504 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2509 * Getter for startup time in miliseconds
2511 * @return $startupTime Startup time in miliseconds
2513 protected function getStartupTime () {
2514 return self::$startupTime;
2518 * "Getter" for a printable currently execution time in nice braces
2520 * @return $executionTime Current execution time in nice braces
2522 protected function getPrintableExecutionTime () {
2523 // Caculate the execution time
2524 $executionTime = microtime(TRUE) - $this->getStartupTime();
2526 // Pack it in nice braces
2527 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2530 return $executionTime;
2534 * Hashes a given string with a simple but stronger hash function (no salt)
2535 * and hex-encode it.
2537 * @param $str The string to be hashed
2538 * @return $hash The hash from string $str
2540 public static final function hash ($str) {
2541 // Hash given string with (better secure) hasher
2542 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2549 * "Getter" for length of hash() output. This will be "cached" to speed up
2552 * @return $length Length of hash() output
2554 public static final function getHashLength () {
2556 if (is_null(self::$hashLength)) {
2557 // No, then hash a string and save its length.
2558 self::$hashLength = strlen(self::hash('abc123'));
2562 return self::$hashLength;
2566 * Checks whether the given number is really a number (only chars 0-9).
2568 * @param $num A string consisting only chars between 0 and 9
2569 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2570 * @param $assertMismatch Whether to assert mismatches
2571 * @return $ret The (hopefully) secured numbered value
2573 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2574 // Filter all numbers out
2575 $ret = preg_replace('/[^0123456789]/', '', $num);
2578 if ($castValue === TRUE) {
2579 // Cast to biggest numeric type
2580 $ret = (double) $ret;
2583 // Assert only if requested
2584 if ($assertMismatch === TRUE) {
2585 // Has the whole value changed?
2586 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2594 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2596 * @param $num A string consisting only chars between 0 and 9
2597 * @param $assertMismatch Whether to assert mismatches
2598 * @return $ret The (hopefully) secured hext-numbered value
2600 public function hexval ($num, $assertMismatch = FALSE) {
2601 // Filter all numbers out
2602 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2604 // Assert only if requested
2605 if ($assertMismatch === TRUE) {
2606 // Has the whole value changed?
2607 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2615 * Checks whether start/end marker are set
2617 * @param $data Data to be checked
2618 * @return $isset Whether start/end marker are set
2620 public final function ifStartEndMarkersSet ($data) {
2622 $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));
2624 // ... and return it
2629 * Determines if an element is set in the generic array
2631 * @param $keyGroup Main group for the key
2632 * @param $subGroup Sub group for the key
2633 * @param $key Key to check
2634 * @param $element Element to check
2635 * @return $isset Whether the given key is set
2637 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2639 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2642 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2648 * Determines if a key is set in the generic array
2650 * @param $keyGroup Main group for the key
2651 * @param $subGroup Sub group for the key
2652 * @param $key Key to check
2653 * @return $isset Whether the given key is set
2655 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2657 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2660 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2668 * Determines if a group is set in the generic array
2670 * @param $keyGroup Main group
2671 * @param $subGroup Sub group
2672 * @return $isset Whether the given group is set
2674 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2676 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2679 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2686 * Getter for sub key group
2688 * @param $keyGroup Main key group
2689 * @param $subGroup Sub key group
2690 * @return $array An array with all array elements
2692 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2694 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2695 // No, then abort here
2696 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2701 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2704 return $this->genericArray[$keyGroup][$subGroup];
2708 * Unsets a given key in generic array
2710 * @param $keyGroup Main group for the key
2711 * @param $subGroup Sub group for the key
2712 * @param $key Key to unset
2715 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2717 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2720 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2724 * Unsets a given element in generic array
2726 * @param $keyGroup Main group for the key
2727 * @param $subGroup Sub group for the key
2728 * @param $key Key to unset
2729 * @param $element Element to unset
2732 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2734 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2737 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2741 * Append a string to a given generic array key
2743 * @param $keyGroup Main group for the key
2744 * @param $subGroup Sub group for the key
2745 * @param $key Key to unset
2746 * @param $value Value to add/append
2749 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2751 //* 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);
2753 // Is it already there?
2754 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2756 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2759 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2764 * Append a string to a given generic array element
2766 * @param $keyGroup Main group for the key
2767 * @param $subGroup Sub group for the key
2768 * @param $key Key to unset
2769 * @param $element Element to check
2770 * @param $value Value to add/append
2773 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2775 //* 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);
2777 // Is it already there?
2778 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2780 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2783 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2788 * Initializes given generic array group
2790 * @param $keyGroup Main group for the key
2791 * @param $subGroup Sub group for the key
2792 * @param $key Key to use
2793 * @param $forceInit Optionally force initialization
2796 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2798 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2800 // Is it already set?
2801 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2802 // Already initialized
2803 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2808 $this->genericArray[$keyGroup][$subGroup] = array();
2812 * Initializes given generic array key
2814 * @param $keyGroup Main group for the key
2815 * @param $subGroup Sub group for the key
2816 * @param $key Key to use
2817 * @param $forceInit Optionally force initialization
2820 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2822 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2824 // Is it already set?
2825 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2826 // Already initialized
2827 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2832 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2836 * Initializes given generic array element
2838 * @param $keyGroup Main group for the key
2839 * @param $subGroup Sub group for the key
2840 * @param $key Key to use
2841 * @param $element Element to use
2842 * @param $forceInit Optionally force initialization
2845 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2847 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2849 // Is it already set?
2850 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2851 // Already initialized
2852 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2857 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2861 * Pushes an element to a generic key
2863 * @param $keyGroup Main group for the key
2864 * @param $subGroup Sub group for the key
2865 * @param $key Key to use
2866 * @param $value Value to add/append
2867 * @return $count Number of array elements
2869 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2871 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2874 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2876 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2880 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2883 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2884 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2889 * Pushes an element to a generic array element
2891 * @param $keyGroup Main group for the key
2892 * @param $subGroup Sub group for the key
2893 * @param $key Key to use
2894 * @param $element Element to check
2895 * @param $value Value to add/append
2896 * @return $count Number of array elements
2898 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2900 //* 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));
2903 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2905 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2909 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2912 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2913 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2918 * Pops an element from a generic group
2920 * @param $keyGroup Main group for the key
2921 * @param $subGroup Sub group for the key
2922 * @param $key Key to unset
2923 * @return $value Last "popped" value
2925 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2927 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2930 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2932 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2937 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2940 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2941 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2946 * Shifts an element from a generic group
2948 * @param $keyGroup Main group for the key
2949 * @param $subGroup Sub group for the key
2950 * @param $key Key to unset
2951 * @return $value Last "popped" value
2953 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2955 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2958 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2960 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2965 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2968 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2969 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2974 * Count generic array group
2976 * @param $keyGroup Main group for the key
2977 * @return $count Count of given group
2979 protected final function countGenericArray ($keyGroup) {
2981 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2984 if (!isset($this->genericArray[$keyGroup])) {
2986 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2991 $count = count($this->genericArray[$keyGroup]);
2994 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3001 * Count generic array sub group
3003 * @param $keyGroup Main group for the key
3004 * @param $subGroup Sub group for the key
3005 * @return $count Count of given group
3007 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3009 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3012 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3014 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3019 $count = count($this->genericArray[$keyGroup][$subGroup]);
3022 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3029 * Count generic array elements
3031 * @param $keyGroup Main group for the key
3032 * @param $subGroup Sub group for the key
3033 * @para $key Key to count
3034 * @return $count Count of given key
3036 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3038 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3041 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3043 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3045 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3047 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3052 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3055 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3062 * Getter for whole generic group array
3064 * @param $keyGroup Key group to get
3065 * @return $array Whole generic array group
3067 protected final function getGenericArray ($keyGroup) {
3069 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3072 if (!isset($this->genericArray[$keyGroup])) {
3074 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3079 return $this->genericArray[$keyGroup];
3083 * Setter for generic array key
3085 * @param $keyGroup Key group to get
3086 * @param $subGroup Sub group for the key
3087 * @param $key Key to unset
3088 * @param $value Mixed value from generic array element
3091 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3093 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3096 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3100 * Getter for generic array key
3102 * @param $keyGroup Key group to get
3103 * @param $subGroup Sub group for the key
3104 * @param $key Key to unset
3105 * @return $value Mixed value from generic array element
3107 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3109 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3112 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3114 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3119 return $this->genericArray[$keyGroup][$subGroup][$key];
3123 * Sets a value in given generic array key/element
3125 * @param $keyGroup Main group for the key
3126 * @param $subGroup Sub group for the key
3127 * @param $key Key to set
3128 * @param $element Element to set
3129 * @param $value Value to set
3132 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3134 //* 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));
3137 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3141 * Getter for generic array element
3143 * @param $keyGroup Key group to get
3144 * @param $subGroup Sub group for the key
3145 * @param $key Key to look for
3146 * @param $element Element to look for
3147 * @return $value Mixed value from generic array element
3149 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3151 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3154 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3156 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3161 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3165 * Checks if a given sub group is valid (array)
3167 * @param $keyGroup Key group to get
3168 * @param $subGroup Sub group for the key
3169 * @return $isValid Whether given sub group is valid
3171 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3173 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3176 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3183 * Checks if a given key is valid (array)
3185 * @param $keyGroup Key group to get
3186 * @param $subGroup Sub group for the key
3187 * @param $key Key to check
3188 * @return $isValid Whether given sub group is valid
3190 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3192 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3195 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3202 * Initializes the web output instance
3206 protected function initWebOutputInstance () {
3207 // Get application instance
3208 $applicationInstance = Registry::getRegistry()->getInstance('app');
3210 // Is this a response instance?
3211 if ($this instanceof Responseable) {
3212 // Then set it in application instance
3213 $applicationInstance->setResponseInstance($this);
3216 // Init web output instance
3217 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3220 $this->setWebOutputInstance($outputInstance);
3224 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3226 * @param $boolean Boolean value
3227 * @return $translated Translated boolean value
3229 public static final function translateBooleanToYesNo ($boolean) {
3230 // Make sure it is really boolean
3231 assert(is_bool($boolean));
3234 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3236 // ... and return it
3241 * Encodes raw data (almost any type) by "serializing" it and then pack it
3242 * into a "binary format".
3244 * @param $rawData Raw data (almost any type)
3245 * @return $encoded Encoded data
3247 protected function encodeData ($rawData) {
3248 // Make sure no objects or resources pass through
3249 assert(!is_object($rawData));
3250 assert(!is_resource($rawData));
3252 // First "serialize" it (json_encode() is faster than serialize())
3253 $encoded = $this->packString(json_encode($rawData));
3260 * Pack a string into a "binary format". Please execuse me that this is
3261 * widely undocumented. :-(
3263 * @param $str Unpacked string
3264 * @return $packed Packed string
3265 * @todo Improve documentation
3267 protected function packString ($str) {
3269 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3271 // First compress the string (gzcompress is okay)
3272 $str = gzcompress($str);
3277 // And start the "encoding" loop
3278 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3280 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3281 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3283 if (($idx + $i) <= strlen($str)) {
3284 $ord = ord(substr($str, ($idx + $i), 1));
3286 $add = $ord * pow(256, $factor);
3290 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3294 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3295 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3297 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3298 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3304 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3309 * Checks whether the given file/path is in open_basedir(). This does not
3310 * gurantee that the file is actually readable and/or writeable. If you need
3311 * such gurantee then please use isReadableFile() instead.
3313 * @param $filePathName Name of the file/path to be checked
3314 * @return $isReachable Whether it is within open_basedir()
3316 public static function isReachableFilePath ($filePathName) {
3317 // Is not reachable by default
3318 $isReachable = FALSE;
3320 // Get open_basedir parameter
3321 $openBaseDir = ini_get('open_basedir');
3324 if (!empty($openBaseDir)) {
3325 // Check all entries
3326 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3327 // Check on existence
3328 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3330 $isReachable = TRUE;
3334 // If open_basedir is not set, all is allowed
3335 $isReachable = TRUE;
3339 return $isReachable;
3343 * Checks whether the give file is within open_basedir() (done by
3344 * isReachableFilePath()), is actually a file and is readable.
3346 * @param $fileName Name of the file to be checked
3347 * @return $isReadable Whether the file is readable (and therefor exists)
3349 public static function isReadableFile ($fileName) {
3350 // Default is not readable
3351 $isReadable = FALSE;
3353 // Is within parameters, so check if it is a file and readable
3354 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));