3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Generic\FrameworkInterface;
8 use CoreFramework\Loader\ClassLoader;
9 use CoreFramework\Manager\ManageableApplication;
10 use CoreFramework\Registry\Register;
11 use CoreFramework\Template\CompileableTemplate;
17 * The simulator system class is the super class of all other classes. This
18 * class handles saving of games etc.
20 * @author Roland Haeder <webmaster@shipsimu.org>
22 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
23 * @license GNU GPL 3.0 or any newer version
24 * @link http://www.shipsimu.org
26 * This program is free software: you can redistribute it and/or modify
27 * it under the terms of the GNU General Public License as published by
28 * the Free Software Foundation, either version 3 of the License, or
29 * (at your option) any later version.
31 * This program is distributed in the hope that it will be useful,
32 * but WITHOUT ANY WARRANTY; without even the implied warranty of
33 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
34 * GNU General Public License for more details.
36 * You should have received a copy of the GNU General Public License
37 * along with this program. If not, see <http://www.gnu.org/licenses/>.
39 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
41 * Length of output from hash()
43 private static $hashLength = NULL;
48 private $realClass = 'BaseFrameworkSystem';
51 * Instance of a request class
53 private $requestInstance = NULL;
56 * Instance of a response class
58 private $responseInstance = NULL;
61 * Search criteria instance
63 private $searchInstance = NULL;
66 * Update criteria instance
68 private $updateInstance = NULL;
71 * The file I/O instance for the template loader
73 private $fileIoInstance = NULL;
78 private $resolverInstance = NULL;
81 * Template engine instance
83 private $templateInstance = NULL;
86 * Database result instance
88 private $resultInstance = NULL;
91 * Instance for user class
93 private $userInstance = NULL;
96 * A controller instance
98 private $controllerInstance = NULL;
103 private $rngInstance = NULL;
106 * Instance of a crypto helper
108 private $cryptoInstance = NULL;
111 * Instance of an Iterator class
113 private $iteratorInstance = NULL;
116 * Instance of the list
118 private $listInstance = NULL;
123 private $menuInstance = NULL;
126 * Instance of the image
128 private $imageInstance = NULL;
131 * Instance of the stacker
133 private $stackInstance = NULL;
136 * A Compressor instance
138 private $compressorInstance = NULL;
141 * A Parseable instance
143 private $parserInstance = NULL;
146 * A HandleableProtocol instance
148 private $protocolInstance = NULL;
151 * A database wrapper instance
153 private $databaseInstance = NULL;
156 * A helper instance for the form
158 private $helperInstance = NULL;
161 * An instance of a Source class
163 private $sourceInstance = NULL;
166 * An instance of a UrlSource class
168 private $urlSourceInstance = NULL;
171 * An instance of a InputStream class
173 private $inputStreamInstance = NULL;
176 * An instance of a OutputStream class
178 private $outputStreamInstance = NULL;
181 * Networkable handler instance
183 private $handlerInstance = NULL;
186 * Visitor handler instance
188 private $visitorInstance = NULL;
193 private $dhtInstance = NULL;
196 * An instance of a database wrapper class
198 private $wrapperInstance = NULL;
201 * An instance of a file I/O pointer class (not handler)
203 private $pointerInstance = NULL;
206 * An instance of an Indexable class
208 private $indexInstance = NULL;
211 * An instance of a Block class
213 private $blockInstance = NULL;
218 private $minableInstance = NULL;
221 * A FrameworkDirectory instance
223 private $directoryInstance = NULL;
228 private $listenerInstance = NULL;
231 * An instance of a communicator
233 private $communicatorInstance = NULL;
236 * The concrete output instance
238 private $outputInstance = NULL;
243 private $stateInstance = NULL;
246 * Thousands separator
248 private $thousands = '.'; // German
253 private $decimals = ','; // German
258 private $socketResource = FALSE;
261 * Regular expression to use for validation
263 private $regularExpression = '';
268 private $packageData = array();
273 private $genericArray = array();
278 private $commandName = '';
283 private $controllerName = '';
286 * Name of used protocol
288 private $protocolName = 'invalid';
291 * Array with bitmasks and such for pack/unpack methods to support both
292 * 32-bit and 64-bit systems
294 private $packingData = array(
297 'left' => 0xffff0000,
298 'right' => 0x0000ffff,
304 'left' => 0xffffffff00000000,
305 'right' => 0x00000000ffffffff,
312 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
314 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
316 private $archArrayElement = FALSE;
318 /***********************
319 * Exception codes.... *
320 ***********************/
322 // @todo Try to clean these constants up
323 const EXCEPTION_IS_NULL_POINTER = 0x001;
324 const EXCEPTION_IS_NO_OBJECT = 0x002;
325 const EXCEPTION_IS_NO_ARRAY = 0x003;
326 const EXCEPTION_MISSING_METHOD = 0x004;
327 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
328 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
329 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
330 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
331 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
332 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
333 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
334 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
335 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
336 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
337 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
338 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
339 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
340 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
341 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
342 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
343 const EXCEPTION_PATH_NOT_FOUND = 0x015;
344 const EXCEPTION_INVALID_PATH_NAME = 0x016;
345 const EXCEPTION_READ_PROTECED_PATH = 0x017;
346 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
347 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
348 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
349 const EXCEPTION_INVALID_RESOURCE = 0x01b;
350 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
351 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
352 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
353 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
354 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
355 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
356 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
357 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
358 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
359 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
360 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
361 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
362 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
363 const EXCEPTION_INVALID_STRING = 0x029;
364 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
365 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
366 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
367 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
368 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
369 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
370 const EXCEPTION_MISSING_ELEMENT = 0x030;
371 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
372 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
373 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
374 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
375 const EXCEPTION_FATAL_ERROR = 0x035;
376 const EXCEPTION_FILE_NOT_FOUND = 0x036;
377 const EXCEPTION_ASSERTION_FAILED = 0x037;
378 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
379 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
380 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
381 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
382 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
383 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
386 * Hexadecimal->Decimal translation array
388 private static $hexdec = array(
408 * Decimal->hexadecimal translation array
410 private static $dechex = array(
430 * Startup time in miliseconds
432 private static $startupTime = 0;
435 * Protected super constructor
437 * @param $className Name of the class
440 protected function __construct ($className) {
442 $this->setRealClass($className);
444 // Set configuration instance if no registry ...
445 if (!$this instanceof Register) {
446 // ... because registries doesn't need to be configured
447 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
450 // Is the startup time set? (0 cannot be TRUE anymore)
451 if (self::$startupTime == 0) {
453 self::$startupTime = microtime(TRUE);
457 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
461 * Destructor for all classes. You should not call this method on your own.
465 public function __destruct () {
466 // Flush any updated entries to the database
467 $this->flushPendingUpdates();
469 // Is this object already destroyed?
470 if ($this->__toString() != 'DestructedObject') {
471 // Destroy all informations about this class but keep some text about it alive
472 $this->setRealClass('DestructedObject');
473 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
474 // Already destructed object
475 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
480 // Do not call this twice
481 trigger_error(__METHOD__ . ': Called twice.');
487 * The __call() method where all non-implemented methods end up
489 * @param $methodName Name of the missing method
490 * @args $args Arguments passed to the method
493 public final function __call ($methodName, $args) {
494 return self::__callStatic($methodName, $args);
498 * The __callStatic() method where all non-implemented static methods end up
500 * @param $methodName Name of the missing method
501 * @args $args Arguments passed to the method
504 public static final function __callStatic ($methodName, $args) {
505 // Init argument string
508 // Is it NULL, empty or an array?
509 if (is_null($args)) {
511 $argsString = 'NULL';
512 } elseif (is_array($args)) {
516 // Some arguments are there
517 foreach ($args as $arg) {
518 // Add data about the argument
519 $argsString .= gettype($arg) . ':';
522 // Found a NULL argument
523 $argsString .= 'NULL';
524 } elseif (is_string($arg)) {
525 // Add length for strings
526 $argsString .= strlen($arg);
527 } elseif ((is_int($arg)) || (is_float($arg))) {
530 } elseif (is_array($arg)) {
531 // .. or size if array
532 $argsString .= count($arg);
533 } elseif (is_object($arg)) {
535 $reflection = new ReflectionClass($arg);
537 // Is an other object, maybe no __toString() available
538 $argsString .= $reflection->getName();
539 } elseif ($arg === TRUE) {
540 // ... is boolean 'TRUE'
541 $argsString .= 'TRUE';
542 } elseif ($arg === FALSE) {
543 // ... is boolean 'FALSE'
544 $argsString .= 'FALSE';
547 // Comma for next one
552 if (substr($argsString, -2, 1) == ',') {
553 $argsString = substr($argsString, 0, -2);
559 // Invalid arguments!
560 $argsString = '!INVALID:' . gettype($args) . '!';
563 // Output stub message
564 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
565 self::createDebugInstance(__CLASS__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
575 * Getter for $realClass
577 * @return $realClass The name of the real class (not BaseFrameworkSystem)
579 public function __toString () {
580 return $this->realClass;
584 * Magic method to catch setting of missing but set class fields/attributes
586 * @param $name Name of the field/attribute
587 * @param $value Value to store
590 public final function __set ($name, $value) {
591 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
594 print_r($value, TRUE)
599 * Magic method to catch getting of missing fields/attributes
601 * @param $name Name of the field/attribute
604 public final function __get ($name) {
605 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
611 * Magic method to catch unsetting of missing fields/attributes
613 * @param $name Name of the field/attribute
616 public final function __unset ($name) {
617 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
623 * Magic method to catch object serialization
625 * @return $unsupported Unsupported method
626 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
628 public final function __sleep () {
629 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
633 * Magic method to catch object deserialization
635 * @return $unsupported Unsupported method
636 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
638 public final function __wakeup () {
639 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
643 * Magic method to catch calls when an object instance is called
645 * @return $unsupported Unsupported method
646 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
648 public final function __invoke () {
649 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
653 * Setter for the real class name
655 * @param $realClass Class name (string)
658 public final function setRealClass ($realClass) {
660 $this->realClass = (string) $realClass;
664 * Setter for database result instance
666 * @param $resultInstance An instance of a database result class
668 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
670 protected final function setResultInstance (SearchableResult $resultInstance) {
671 $this->resultInstance = $resultInstance;
675 * Getter for database result instance
677 * @return $resultInstance An instance of a database result class
679 public final function getResultInstance () {
680 return $this->resultInstance;
684 * Setter for template engine instances
686 * @param $templateInstance An instance of a template engine class
689 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
690 $this->templateInstance = $templateInstance;
694 * Getter for template engine instances
696 * @return $templateInstance An instance of a template engine class
698 protected final function getTemplateInstance () {
699 return $this->templateInstance;
703 * Setter for search instance
705 * @param $searchInstance Searchable criteria instance
708 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
709 $this->searchInstance = $searchInstance;
713 * Getter for search instance
715 * @return $searchInstance Searchable criteria instance
717 public final function getSearchInstance () {
718 return $this->searchInstance;
722 * Setter for update instance
724 * @param $updateInstance Searchable criteria instance
727 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
728 $this->updateInstance = $updateInstance;
732 * Getter for update instance
734 * @return $updateInstance Updateable criteria instance
736 public final function getUpdateInstance () {
737 return $this->updateInstance;
741 * Setter for resolver instance
743 * @param $resolverInstance Instance of a command resolver class
746 public final function setResolverInstance (Resolver $resolverInstance) {
747 $this->resolverInstance = $resolverInstance;
751 * Getter for resolver instance
753 * @return $resolverInstance Instance of a command resolver class
755 public final function getResolverInstance () {
756 return $this->resolverInstance;
760 * Setter for language instance
762 * @param $configInstance The configuration instance which shall
763 * be FrameworkConfiguration
766 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
767 Registry::getRegistry()->addInstance('config', $configInstance);
771 * Getter for configuration instance
773 * @return $configInstance Configuration instance
775 public final function getConfigInstance () {
776 $configInstance = Registry::getRegistry()->getInstance('config');
777 return $configInstance;
781 * Setter for debug instance
783 * @param $debugInstance The instance for debug output class
786 public final function setDebugInstance (DebugMiddleware $debugInstance) {
787 Registry::getRegistry()->addInstance('debug', $debugInstance);
791 * Getter for debug instance
793 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
795 public final function getDebugInstance () {
796 // Get debug instance
797 $debugInstance = Registry::getRegistry()->getInstance('debug');
800 return $debugInstance;
804 * Setter for web output instance
806 * @param $webInstance The instance for web output class
809 public final function setWebOutputInstance (OutputStreamer $webInstance) {
810 Registry::getRegistry()->addInstance('web_output', $webInstance);
814 * Getter for web output instance
816 * @return $webOutputInstance - Instance to class WebOutput
818 public final function getWebOutputInstance () {
819 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
820 return $webOutputInstance;
824 * Setter for database instance
826 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
829 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
830 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
834 * Getter for database layer
836 * @return $databaseInstance The database layer instance
838 public final function getDatabaseInstance () {
840 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
843 return $databaseInstance;
847 * Setter for compressor channel
849 * @param $compressorInstance An instance of CompressorChannel
852 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
853 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
857 * Getter for compressor channel
859 * @return $compressorInstance The compressor channel
861 public final function getCompressorChannel () {
862 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
863 return $compressorInstance;
867 * Protected getter for a manageable application helper class
869 * @return $applicationInstance An instance of a manageable application helper class
871 protected final function getApplicationInstance () {
872 $applicationInstance = Registry::getRegistry()->getInstance('application');
873 return $applicationInstance;
877 * Setter for a manageable application helper class
879 * @param $applicationInstance An instance of a manageable application helper class
882 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
883 Registry::getRegistry()->addInstance('application', $applicationInstance);
887 * Setter for request instance
889 * @param $requestInstance An instance of a Requestable class
892 public final function setRequestInstance (Requestable $requestInstance) {
893 $this->requestInstance = $requestInstance;
897 * Getter for request instance
899 * @return $requestInstance An instance of a Requestable class
901 public final function getRequestInstance () {
902 return $this->requestInstance;
906 * Setter for response instance
908 * @param $responseInstance An instance of a Responseable class
911 public final function setResponseInstance (Responseable $responseInstance) {
912 $this->responseInstance = $responseInstance;
916 * Getter for response instance
918 * @return $responseInstance An instance of a Responseable class
920 public final function getResponseInstance () {
921 return $this->responseInstance;
925 * Private getter for language instance
927 * @return $langInstance An instance to the language sub-system
929 protected final function getLanguageInstance () {
930 $langInstance = Registry::getRegistry()->getInstance('language');
931 return $langInstance;
935 * Setter for language instance
937 * @param $langInstance An instance to the language sub-system
939 * @see LanguageSystem
941 public final function setLanguageInstance (ManageableLanguage $langInstance) {
942 Registry::getRegistry()->addInstance('language', $langInstance);
946 * Private getter for file IO instance
948 * @return $fileIoInstance An instance to the file I/O sub-system
950 protected final function getFileIoInstance () {
951 return $this->fileIoInstance;
955 * Setter for file I/O instance
957 * @param $fileIoInstance An instance to the file I/O sub-system
960 public final function setFileIoInstance (IoHandler $fileIoInstance) {
961 $this->fileIoInstance = $fileIoInstance;
965 * Protected setter for user instance
967 * @param $userInstance An instance of a user class
970 protected final function setUserInstance (ManageableAccount $userInstance) {
971 $this->userInstance = $userInstance;
975 * Getter for user instance
977 * @return $userInstance An instance of a user class
979 public final function getUserInstance () {
980 return $this->userInstance;
984 * Setter for controller instance (this surely breaks a bit the MVC patterm)
986 * @param $controllerInstance An instance of the controller
989 public final function setControllerInstance (Controller $controllerInstance) {
990 $this->controllerInstance = $controllerInstance;
994 * Getter for controller instance (this surely breaks a bit the MVC patterm)
996 * @return $controllerInstance An instance of the controller
998 public final function getControllerInstance () {
999 return $this->controllerInstance;
1003 * Setter for RNG instance
1005 * @param $rngInstance An instance of a random number generator (RNG)
1008 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1009 $this->rngInstance = $rngInstance;
1013 * Getter for RNG instance
1015 * @return $rngInstance An instance of a random number generator (RNG)
1017 public final function getRngInstance () {
1018 return $this->rngInstance;
1022 * Setter for Cryptable instance
1024 * @param $cryptoInstance An instance of a Cryptable class
1027 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1028 $this->cryptoInstance = $cryptoInstance;
1032 * Getter for Cryptable instance
1034 * @return $cryptoInstance An instance of a Cryptable class
1036 public final function getCryptoInstance () {
1037 return $this->cryptoInstance;
1041 * Setter for the list instance
1043 * @param $listInstance A list of Listable
1046 protected final function setListInstance (Listable $listInstance) {
1047 $this->listInstance = $listInstance;
1051 * Getter for the list instance
1053 * @return $listInstance A list of Listable
1055 protected final function getListInstance () {
1056 return $this->listInstance;
1060 * Setter for the menu instance
1062 * @param $menuInstance A RenderableMenu instance
1065 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1066 $this->menuInstance = $menuInstance;
1070 * Getter for the menu instance
1072 * @return $menuInstance A RenderableMenu instance
1074 protected final function getMenuInstance () {
1075 return $this->menuInstance;
1079 * Setter for image instance
1081 * @param $imageInstance An instance of an image
1084 public final function setImageInstance (BaseImage $imageInstance) {
1085 $this->imageInstance = $imageInstance;
1089 * Getter for image instance
1091 * @return $imageInstance An instance of an image
1093 public final function getImageInstance () {
1094 return $this->imageInstance;
1098 * Setter for stacker instance
1100 * @param $stackInstance An instance of an stacker
1103 public final function setStackInstance (Stackable $stackInstance) {
1104 $this->stackInstance = $stackInstance;
1108 * Getter for stacker instance
1110 * @return $stackInstance An instance of an stacker
1112 public final function getStackInstance () {
1113 return $this->stackInstance;
1117 * Setter for compressor instance
1119 * @param $compressorInstance An instance of an compressor
1122 public final function setCompressorInstance (Compressor $compressorInstance) {
1123 $this->compressorInstance = $compressorInstance;
1127 * Getter for compressor instance
1129 * @return $compressorInstance An instance of an compressor
1131 public final function getCompressorInstance () {
1132 return $this->compressorInstance;
1136 * Setter for Parseable instance
1138 * @param $parserInstance An instance of an Parseable
1141 public final function setParserInstance (Parseable $parserInstance) {
1142 $this->parserInstance = $parserInstance;
1146 * Getter for Parseable instance
1148 * @return $parserInstance An instance of an Parseable
1150 public final function getParserInstance () {
1151 return $this->parserInstance;
1155 * Setter for HandleableProtocol instance
1157 * @param $protocolInstance An instance of an HandleableProtocol
1160 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1161 $this->protocolInstance = $protocolInstance;
1165 * Getter for HandleableProtocol instance
1167 * @return $protocolInstance An instance of an HandleableProtocol
1169 public final function getProtocolInstance () {
1170 return $this->protocolInstance;
1174 * Setter for DatabaseWrapper instance
1176 * @param $wrapperInstance An instance of an DatabaseWrapper
1179 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1180 $this->wrapperInstance = $wrapperInstance;
1184 * Getter for DatabaseWrapper instance
1186 * @return $wrapperInstance An instance of an DatabaseWrapper
1188 public final function getWrapperInstance () {
1189 return $this->wrapperInstance;
1193 * Setter for socket resource
1195 * @param $socketResource A valid socket resource
1198 public final function setSocketResource ($socketResource) {
1199 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1200 $this->socketResource = $socketResource;
1204 * Getter for socket resource
1206 * @return $socketResource A valid socket resource
1208 public final function getSocketResource () {
1209 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1210 return $this->socketResource;
1214 * Setter for regular expression
1216 * @param $regularExpression A valid regular expression
1219 public final function setRegularExpression ($regularExpression) {
1220 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1221 $this->regularExpression = $regularExpression;
1225 * Getter for regular expression
1227 * @return $regularExpression A valid regular expression
1229 public final function getRegularExpression () {
1230 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1231 return $this->regularExpression;
1235 * Setter for helper instance
1237 * @param $helperInstance An instance of a helper class
1240 protected final function setHelperInstance (Helper $helperInstance) {
1241 $this->helperInstance = $helperInstance;
1245 * Getter for helper instance
1247 * @return $helperInstance An instance of a helper class
1249 public final function getHelperInstance () {
1250 return $this->helperInstance;
1254 * Setter for a Source instance
1256 * @param $sourceInstance An instance of a Source class
1259 protected final function setSourceInstance (Source $sourceInstance) {
1260 $this->sourceInstance = $sourceInstance;
1264 * Getter for a Source instance
1266 * @return $sourceInstance An instance of a Source class
1268 protected final function getSourceInstance () {
1269 return $this->sourceInstance;
1273 * Setter for a UrlSource instance
1275 * @param $sourceInstance An instance of a UrlSource class
1278 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1279 $this->urlSourceInstance = $urlSourceInstance;
1283 * Getter for a UrlSource instance
1285 * @return $urlSourceInstance An instance of a UrlSource class
1287 protected final function getUrlSourceInstance () {
1288 return $this->urlSourceInstance;
1292 * Getter for a InputStream instance
1294 * @param $inputStreamInstance The InputStream instance
1296 protected final function getInputStreamInstance () {
1297 return $this->inputStreamInstance;
1301 * Setter for a InputStream instance
1303 * @param $inputStreamInstance The InputStream instance
1306 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1307 $this->inputStreamInstance = $inputStreamInstance;
1311 * Getter for a OutputStream instance
1313 * @param $outputStreamInstance The OutputStream instance
1315 protected final function getOutputStreamInstance () {
1316 return $this->outputStreamInstance;
1320 * Setter for a OutputStream instance
1322 * @param $outputStreamInstance The OutputStream instance
1325 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1326 $this->outputStreamInstance = $outputStreamInstance;
1330 * Setter for handler instance
1332 * @param $handlerInstance An instance of a Handleable class
1335 protected final function setHandlerInstance (Handleable $handlerInstance) {
1336 $this->handlerInstance = $handlerInstance;
1340 * Getter for handler instance
1342 * @return $handlerInstance A Networkable instance
1344 protected final function getHandlerInstance () {
1345 return $this->handlerInstance;
1349 * Setter for visitor instance
1351 * @param $visitorInstance A Visitor instance
1354 protected final function setVisitorInstance (Visitor $visitorInstance) {
1355 $this->visitorInstance = $visitorInstance;
1359 * Getter for visitor instance
1361 * @return $visitorInstance A Visitor instance
1363 protected final function getVisitorInstance () {
1364 return $this->visitorInstance;
1368 * Setter for DHT instance
1370 * @param $dhtInstance A Distributable instance
1373 protected final function setDhtInstance (Distributable $dhtInstance) {
1374 $this->dhtInstance = $dhtInstance;
1378 * Getter for DHT instance
1380 * @return $dhtInstance A Distributable instance
1382 protected final function getDhtInstance () {
1383 return $this->dhtInstance;
1387 * Setter for raw package Data
1389 * @param $packageData Raw package Data
1392 public final function setPackageData (array $packageData) {
1393 $this->packageData = $packageData;
1397 * Getter for raw package Data
1399 * @return $packageData Raw package Data
1401 public function getPackageData () {
1402 return $this->packageData;
1407 * Setter for Iterator instance
1409 * @param $iteratorInstance An instance of an Iterator
1412 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1413 $this->iteratorInstance = $iteratorInstance;
1417 * Getter for Iterator instance
1419 * @return $iteratorInstance An instance of an Iterator
1421 public final function getIteratorInstance () {
1422 return $this->iteratorInstance;
1426 * Setter for FilePointer instance
1428 * @param $pointerInstance An instance of an FilePointer class
1431 protected final function setPointerInstance (FilePointer $pointerInstance) {
1432 $this->pointerInstance = $pointerInstance;
1436 * Getter for FilePointer instance
1438 * @return $pointerInstance An instance of an FilePointer class
1440 public final function getPointerInstance () {
1441 return $this->pointerInstance;
1445 * Unsets pointer instance which triggers a call of __destruct() if the
1446 * instance is still there. This is surely not fatal on already "closed"
1447 * file pointer instances.
1449 * I don't want to mess around with above setter by giving it a default
1450 * value NULL as setter should always explicitly only set (existing) object
1451 * instances and NULL is NULL.
1455 protected final function unsetPointerInstance () {
1456 // Simply it to NULL
1457 $this->pointerInstance = NULL;
1461 * Setter for Indexable instance
1463 * @param $indexInstance An instance of an Indexable class
1466 protected final function setIndexInstance (Indexable $indexInstance) {
1467 $this->indexInstance = $indexInstance;
1471 * Getter for Indexable instance
1473 * @return $indexInstance An instance of an Indexable class
1475 public final function getIndexInstance () {
1476 return $this->indexInstance;
1480 * Setter for Block instance
1482 * @param $blockInstance An instance of an Block class
1485 protected final function setBlockInstance (Block $blockInstance) {
1486 $this->blockInstance = $blockInstance;
1490 * Getter for Block instance
1492 * @return $blockInstance An instance of an Block class
1494 public final function getBlockInstance () {
1495 return $this->blockInstance;
1499 * Setter for Minable instance
1501 * @param $minableInstance A Minable instance
1504 protected final function setMinableInstance (Minable $minableInstance) {
1505 $this->minableInstance = $minableInstance;
1509 * Getter for minable instance
1511 * @return $minableInstance A Minable instance
1513 protected final function getMinableInstance () {
1514 return $this->minableInstance;
1518 * Setter for FrameworkDirectory instance
1520 * @param $directoryInstance A FrameworkDirectoryPointer instance
1523 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1524 $this->directoryInstance = $directoryInstance;
1528 * Getter for FrameworkDirectory instance
1530 * @return $directoryInstance A FrameworkDirectory instance
1532 protected final function getDirectoryInstance () {
1533 return $this->directoryInstance;
1537 * Setter for listener instance
1539 * @param $listenerInstance A Listenable instance
1542 protected final function setListenerInstance (Listenable $listenerInstance) {
1543 $this->listenerInstance = $listenerInstance;
1547 * Getter for listener instance
1549 * @return $listenerInstance A Listenable instance
1551 protected final function getListenerInstance () {
1552 return $this->listenerInstance;
1556 * Getter for communicator instance
1558 * @return $communicatorInstance An instance of a Communicator class
1560 public final function getCommunicatorInstance () {
1561 return $this->communicatorInstance;
1565 * Setter for communicator instance
1567 * @param $communicatorInstance An instance of a Communicator class
1570 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1571 $this->communicatorInstance = $communicatorInstance;
1575 * Setter for state instance
1577 * @param $stateInstance A Stateable instance
1580 public final function setStateInstance (Stateable $stateInstance) {
1581 $this->stateInstance = $stateInstance;
1585 * Getter for state instance
1587 * @return $stateInstance A Stateable instance
1589 public final function getStateInstance () {
1590 return $this->stateInstance;
1594 * Setter for output instance
1596 * @param $outputInstance The debug output instance
1599 public final function setOutputInstance (OutputStreamer $outputInstance) {
1600 $this->outputInstance = $outputInstance;
1604 * Getter for output instance
1606 * @return $outputInstance The debug output instance
1608 public final function getOutputInstance () {
1609 return $this->outputInstance;
1613 * Setter for command name
1615 * @param $commandName Last validated command name
1618 protected final function setCommandName ($commandName) {
1619 $this->commandName = $commandName;
1623 * Getter for command name
1625 * @return $commandName Last validated command name
1627 protected final function getCommandName () {
1628 return $this->commandName;
1632 * Setter for controller name
1634 * @param $controllerName Last validated controller name
1637 protected final function setControllerName ($controllerName) {
1638 $this->controllerName = $controllerName;
1642 * Getter for controller name
1644 * @return $controllerName Last validated controller name
1646 protected final function getControllerName () {
1647 return $this->controllerName;
1651 * Getter for protocol name
1653 * @return $protocolName Name of used protocol
1655 public final function getProtocolName () {
1656 return $this->protocolName;
1660 * Setter for protocol name
1662 * @param $protocolName Name of used protocol
1665 protected final function setProtocolName ($protocolName) {
1666 $this->protocolName = $protocolName;
1670 * Checks whether an object equals this object. You should overwrite this
1671 * method to implement own equality checks
1673 * @param $objectInstance An instance of a FrameworkInterface object
1674 * @return $equals Whether both objects equals
1676 public function equals (FrameworkInterface $objectInstance) {
1679 $this->__toString() == $objectInstance->__toString()
1681 $this->hashCode() == $objectInstance->hashCode()
1684 // Return the result
1689 * Generates a generic hash code of this class. You should really overwrite
1690 * this method with your own hash code generator code. But keep KISS in mind.
1692 * @return $hashCode A generic hash code respresenting this whole class
1694 public function hashCode () {
1696 return crc32($this->__toString());
1700 * Formats computer generated price values into human-understandable formats
1701 * with thousand and decimal separators.
1703 * @param $value The in computer format value for a price
1704 * @param $currency The currency symbol (use HTML-valid characters!)
1705 * @param $decNum Number of decimals after commata
1706 * @return $price The for the current language formated price string
1707 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1708 * thousands separator
1711 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1712 // Are all required attriutes set?
1713 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1714 // Throw an exception
1715 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1719 $value = (float) $value;
1721 // Reformat the US number
1722 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1724 // Return as string...
1729 * Appends a trailing slash to a string
1731 * @param $str A string (maybe) without trailing slash
1732 * @return $str A string with an auto-appended trailing slash
1734 public final function addMissingTrailingSlash ($str) {
1735 // Is there a trailing slash?
1736 if (substr($str, -1, 1) != '/') {
1740 // Return string with trailing slash
1745 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1746 * application helper instance (ApplicationHelper by default).
1748 * @param $applicationInstance An application helper instance or
1749 * null if we shall use the default
1750 * @return $templateInstance The template engine instance
1751 * @throws NullPointerException If the discovered application
1752 * instance is still null
1754 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1755 // Is the application instance set?
1756 if (is_null($applicationInstance)) {
1757 // Get the current instance
1758 $applicationInstance = $this->getApplicationInstance();
1761 if (is_null($applicationInstance)) {
1762 // Thrown an exception
1763 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1767 // Initialize the template engine
1768 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1770 // Return the prepared instance
1771 return $templateInstance;
1775 * Debugs this instance by putting out it's full content
1777 * @param $message Optional message to show in debug output
1780 public final function debugInstance ($message = '') {
1781 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1782 restore_error_handler();
1787 // Is a message set?
1788 if (!empty($message)) {
1789 // Construct message
1790 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1793 // Generate the output
1794 $content .= sprintf('<pre>%s</pre>',
1797 print_r($this, TRUE)
1803 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>',
1804 $this->__toString(),
1806 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1811 * Replaces control characters with printable output
1813 * @param $str String with control characters
1814 * @return $str Replaced string
1816 protected function replaceControlCharacters ($str) {
1819 chr(13), '[r]', str_replace(
1820 chr(10), '[n]', str_replace(
1830 * Output a partial stub message for the caller method
1832 * @param $message An optional message to display
1835 protected function partialStub ($message = '') {
1836 // Get the backtrace
1837 $backtrace = debug_backtrace();
1839 // Generate the class::method string
1840 $methodName = 'UnknownClass->unknownMethod';
1841 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1842 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1845 // Construct the full message
1846 $stubMessage = sprintf('[%s:] Partial stub!',
1850 // Is the extra message given?
1851 if (!empty($message)) {
1852 // Then add it as well
1853 $stubMessage .= ' Message: ' . $message;
1856 // Debug instance is there?
1857 if (!is_null($this->getDebugInstance())) {
1858 // Output stub message
1859 self::createDebugInstance(__CLASS__)->debugOutput($stubMessage);
1862 trigger_error($stubMessage);
1868 * Outputs a debug backtrace and stops further script execution
1870 * @param $message An optional message to output
1871 * @param $doExit Whether exit the program (TRUE is default)
1874 public function debugBackTrace ($message = '', $doExit = TRUE) {
1875 // Sorry, there is no other way getting this nice backtrace
1876 if (!empty($message)) {
1878 printf('Message: %s<br />' . PHP_EOL, $message);
1882 debug_print_backtrace();
1886 if ($doExit === TRUE) {
1892 * Creates an instance of a debugger instance
1894 * @param $className Name of the class (currently unsupported)
1895 * @return $debugInstance An instance of a debugger class
1896 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1898 public final static function createDebugInstance ($className) {
1899 // Is the instance set?
1900 if (!Registry::getRegistry()->instanceExists('debug')) {
1901 // Init debug instance
1902 $debugInstance = NULL;
1906 // Get a debugger instance
1907 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1908 } catch (NullPointerException $e) {
1909 // Didn't work, no instance there
1910 exit('Cannot create debugInstance! Exception=' . $e->__toString() . ', message=' . $e->getMessage());
1913 // Empty string should be ignored and used for testing the middleware
1914 DebugMiddleware::getSelfInstance()->output('');
1916 // Set it in its own class. This will set it in the registry
1917 $debugInstance->setDebugInstance($debugInstance);
1919 // Get instance from registry
1920 $debugInstance = Registry::getRegistry()->getDebugInstance();
1924 return $debugInstance;
1928 * Simple output of a message with line-break
1930 * @param $message Message to output
1933 public function outputLine ($message) {
1935 print($message . PHP_EOL);
1939 * Outputs a debug message whether to debug instance (should be set!) or
1940 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1941 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1943 * @param $message Message we shall send out...
1944 * @param $doPrint Whether print or die here (default: print)
1945 * @paran $stripTags Whether to strip tags (default: FALSE)
1948 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1949 // Set debug instance to NULL
1950 $debugInstance = NULL;
1954 // Get debug instance
1955 $debugInstance = $this->getDebugInstance();
1956 } catch (NullPointerException $e) {
1957 // The debug instance is not set (yet)
1960 // Is the debug instance there?
1961 if (is_object($debugInstance)) {
1962 // Use debug output handler
1963 $debugInstance->output($message, $stripTags);
1965 if ($doPrint === FALSE) {
1966 // Die here if not printed
1970 // Are debug times enabled?
1971 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1973 $message = $this->getPrintableExecutionTime() . $message;
1977 if ($doPrint === TRUE) {
1979 $this->outputLine($message);
1988 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1990 * @param $str The string, what ever it is needs to be converted
1991 * @return $className Generated class name
1993 public static final function convertToClassName ($str) {
1997 // Convert all dashes in underscores
1998 $str = self::convertDashesToUnderscores($str);
2000 // Now use that underscores to get classname parts for hungarian style
2001 foreach (explode('_', $str) as $strPart) {
2002 // Make the class name part lower case and first upper case
2003 $className .= ucfirst(strtolower($strPart));
2006 // Return class name
2011 * Converts dashes to underscores, e.g. useable for configuration entries
2013 * @param $str The string with maybe dashes inside
2014 * @return $str The converted string with no dashed, but underscores
2016 public static final function convertDashesToUnderscores ($str) {
2018 $str = str_replace('-', '_', $str);
2020 // Return converted string
2025 * Marks up the code by adding e.g. line numbers
2027 * @param $phpCode Unmarked PHP code
2028 * @return $markedCode Marked PHP code
2030 public function markupCode ($phpCode) {
2035 $errorArray = error_get_last();
2037 // Init the code with error message
2038 if (is_array($errorArray)) {
2040 $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>',
2041 basename($errorArray['file']),
2042 $errorArray['line'],
2043 $errorArray['message'],
2048 // Add line number to the code
2049 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2051 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2053 htmlentities($code, ENT_QUOTES)
2062 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2063 * beatiful for web-based front-ends. If null is given a message id
2064 * null_timestamp will be resolved and returned.
2066 * @param $timestamp Timestamp to prepare (filter) for display
2067 * @return $readable A readable timestamp
2069 public function doFilterFormatTimestamp ($timestamp) {
2070 // Default value to return
2073 // Is the timestamp null?
2074 if (is_null($timestamp)) {
2075 // Get a message string
2076 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2078 switch ($this->getLanguageInstance()->getLanguageCode()) {
2079 case 'de': // German format is a bit different to default
2080 // Split the GMT stamp up
2081 $dateTime = explode(' ', $timestamp );
2082 $dateArray = explode('-', $dateTime[0]);
2083 $timeArray = explode(':', $dateTime[1]);
2085 // Construct the timestamp
2086 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2096 default: // Default is pass-through
2097 $readable = $timestamp;
2107 * Filter a given number into a localized number
2109 * @param $value The raw value from e.g. database
2110 * @return $localized Localized value
2112 public function doFilterFormatNumber ($value) {
2113 // Generate it from config and localize dependencies
2114 switch ($this->getLanguageInstance()->getLanguageCode()) {
2115 case 'de': // German format is a bit different to default
2116 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2119 default: // US, etc.
2120 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2129 * "Getter" for databse entry
2131 * @return $entry An array with database entries
2132 * @throws NullPointerException If the database result is not found
2133 * @throws InvalidDatabaseResultException If the database result is invalid
2135 protected final function getDatabaseEntry () {
2136 // Is there an instance?
2137 if (!$this->getResultInstance() instanceof SearchableResult) {
2138 // Throw an exception here
2139 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2143 $this->getResultInstance()->rewind();
2145 // Do we have an entry?
2146 if ($this->getResultInstance()->valid() === FALSE) {
2147 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2148 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2152 $this->getResultInstance()->next();
2155 $entry = $this->getResultInstance()->current();
2162 * Getter for field name
2164 * @param $fieldName Field name which we shall get
2165 * @return $fieldValue Field value from the user
2166 * @throws NullPointerException If the result instance is null
2168 public final function getField ($fieldName) {
2169 // Default field value
2172 // Get result instance
2173 $resultInstance = $this->getResultInstance();
2175 // Is this instance null?
2176 if (is_null($resultInstance)) {
2177 // Then the user instance is no longer valid (expired cookies?)
2178 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2181 // Get current array
2182 $fieldArray = $resultInstance->current();
2183 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2185 // Convert dashes to underscore
2186 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2188 // Does the field exist?
2189 if ($this->isFieldSet($fieldName)) {
2191 $fieldValue = $fieldArray[$fieldName2];
2192 } elseif (defined('DEVELOPER')) {
2193 // Missing field entry, may require debugging
2194 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2196 // Missing field entry, may require debugging
2197 self::createDebugInstance(__CLASS__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2205 * Checks if given field is set
2207 * @param $fieldName Field name to check
2208 * @return $isSet Whether the given field name is set
2209 * @throws NullPointerException If the result instance is null
2211 public function isFieldSet ($fieldName) {
2212 // Get result instance
2213 $resultInstance = $this->getResultInstance();
2215 // Is this instance null?
2216 if (is_null($resultInstance)) {
2217 // Then the user instance is no longer valid (expired cookies?)
2218 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2221 // Get current array
2222 $fieldArray = $resultInstance->current();
2223 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2225 // Convert dashes to underscore
2226 $fieldName = self::convertDashesToUnderscores($fieldName);
2229 $isSet = isset($fieldArray[$fieldName]);
2236 * Flushs all pending updates to the database layer
2240 public function flushPendingUpdates () {
2241 // Get result instance
2242 $resultInstance = $this->getResultInstance();
2244 // Do we have data to update?
2245 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2246 // Get wrapper class name config entry
2247 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2249 // Create object instance
2250 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2252 // Yes, then send the whole result to the database layer
2253 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2258 * Outputs a deprecation warning to the developer.
2260 * @param $message The message we shall output to the developer
2262 * @todo Write a logging mechanism for productive mode
2264 public function deprecationWarning ($message) {
2265 // Is developer mode active?
2266 if (defined('DEVELOPER')) {
2267 // Debug instance is there?
2268 if (!is_null($this->getDebugInstance())) {
2269 // Output stub message
2270 self::createDebugInstance(__CLASS__)->debugOutput($message);
2273 trigger_error($message . "<br />\n");
2277 // @TODO Finish this part!
2278 $this->partialStub('Developer mode inactive. Message:' . $message);
2283 * Checks whether the given PHP extension is loaded
2285 * @param $phpExtension The PHP extension we shall check
2286 * @return $isLoaded Whether the PHP extension is loaded
2288 public final function isPhpExtensionLoaded ($phpExtension) {
2290 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2297 * "Getter" as a time() replacement but with milliseconds. You should use this
2298 * method instead of the encapsulated getimeofday() function.
2300 * @return $milliTime Timestamp with milliseconds
2302 public function getMilliTime () {
2303 // Get the time of day as float
2304 $milliTime = gettimeofday(TRUE);
2311 * Idles (sleeps) for given milliseconds
2313 * @return $hasSlept Whether it goes fine
2315 public function idle ($milliSeconds) {
2316 // Sleep is fine by default
2319 // Idle so long with found function
2320 if (function_exists('time_sleep_until')) {
2321 // Get current time and add idle time
2322 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2324 // New PHP 5.1.0 function found, ignore errors
2325 $hasSlept = @time_sleep_until($sleepUntil);
2328 * My Sun station doesn't have that function even with latest PHP
2331 usleep($milliSeconds * 1000);
2338 * Converts a hexadecimal string, even with negative sign as first string to
2339 * a decimal number using BC functions.
2341 * This work is based on comment #86673 on php.net documentation page at:
2342 * <http://de.php.net/manual/en/function.dechex.php#86673>
2344 * @param $hex Hexadecimal string
2345 * @return $dec Decimal number
2347 protected function hex2dec ($hex) {
2348 // Convert to all lower-case
2349 $hex = strtolower($hex);
2351 // Detect sign (negative/positive numbers)
2353 if (substr($hex, 0, 1) == '-') {
2355 $hex = substr($hex, 1);
2358 // Decode the hexadecimal string into a decimal number
2360 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2361 $factor = self::$hexdec[substr($hex, $i, 1)];
2362 $dec = bcadd($dec, bcmul($factor, $e));
2365 // Return the decimal number
2366 return $sign . $dec;
2370 * Converts even very large decimal numbers, also signed, to a hexadecimal
2373 * This work is based on comment #97756 on php.net documentation page at:
2374 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2376 * @param $dec Decimal number, even with negative sign
2377 * @param $maxLength Optional maximum length of the string
2378 * @return $hex Hexadecimal string
2380 protected function dec2hex ($dec, $maxLength = 0) {
2381 // maxLength can be zero or devideable by 2
2382 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2384 // Detect sign (negative/positive numbers)
2391 // Encode the decimal number into a hexadecimal string
2394 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2396 } while ($dec >= 1);
2399 * Leading zeros are required for hex-decimal "numbers". In some
2400 * situations more leading zeros are wanted, so check for both
2403 if ($maxLength > 0) {
2404 // Prepend more zeros
2405 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2406 } elseif ((strlen($hex) % 2) != 0) {
2407 // Only make string's length dividable by 2
2411 // Return the hexadecimal string
2412 return $sign . $hex;
2416 * Converts a ASCII string (0 to 255) into a decimal number.
2418 * @param $asc The ASCII string to be converted
2419 * @return $dec Decimal number
2421 protected function asc2dec ($asc) {
2422 // Convert it into a hexadecimal number
2423 $hex = bin2hex($asc);
2425 // And back into a decimal number
2426 $dec = $this->hex2dec($hex);
2433 * Converts a decimal number into an ASCII string.
2435 * @param $dec Decimal number
2436 * @return $asc An ASCII string
2438 protected function dec2asc ($dec) {
2439 // First convert the number into a hexadecimal string
2440 $hex = $this->dec2hex($dec);
2442 // Then convert it into the ASCII string
2443 $asc = $this->hex2asc($hex);
2450 * Converts a hexadecimal number into an ASCII string. Negative numbers
2453 * @param $hex Hexadecimal string
2454 * @return $asc An ASCII string
2456 protected function hex2asc ($hex) {
2457 // Check for length, it must be devideable by 2
2458 //* DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput('hex='.$hex);
2459 assert((strlen($hex) % 2) == 0);
2463 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2464 // Get the decimal number of the chunk
2465 $part = hexdec(substr($hex, $idx, 2));
2467 // Add it to the final string
2471 // Return the final string
2476 * Checks whether the given encoded data was encoded with Base64
2478 * @param $encodedData Encoded data we shall check
2479 * @return $isBase64 Whether the encoded data is Base64
2481 protected function isBase64Encoded ($encodedData) {
2483 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2490 * "Getter" to get response/request type from analysis of the system.
2492 * @return $responseType Analyzed response type
2494 protected static function getResponseTypeFromSystem () {
2495 // Default is console
2496 $responseType = 'console';
2498 // Is 'HTTP_HOST' set?
2499 if (isset($_SERVER['HTTP_HOST'])) {
2501 * Then it is a HTML response/request as RSS and so on may be
2502 * transfered over HTTP as well.
2504 $responseType = 'html';
2508 return $responseType;
2512 * Gets a cache key from Criteria instance
2514 * @param $criteriaInstance An instance of a Criteria class
2515 * @param $onlyKeys Only use these keys for a cache key
2516 * @return $cacheKey A cache key suitable for lookup/storage purposes
2518 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2520 $cacheKey = sprintf('%s@%s',
2521 $this->__toString(),
2522 $criteriaInstance->getCacheKey($onlyKeys)
2526 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2531 * Getter for startup time in miliseconds
2533 * @return $startupTime Startup time in miliseconds
2535 protected function getStartupTime () {
2536 return self::$startupTime;
2540 * "Getter" for a printable currently execution time in nice braces
2542 * @return $executionTime Current execution time in nice braces
2544 protected function getPrintableExecutionTime () {
2545 // Caculate the execution time
2546 $executionTime = microtime(TRUE) - $this->getStartupTime();
2548 // Pack it in nice braces
2549 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2552 return $executionTime;
2556 * Hashes a given string with a simple but stronger hash function (no salt)
2557 * and hex-encode it.
2559 * @param $str The string to be hashed
2560 * @return $hash The hash from string $str
2562 public static final function hash ($str) {
2563 // Hash given string with (better secure) hasher
2564 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2571 * "Getter" for length of hash() output. This will be "cached" to speed up
2574 * @return $length Length of hash() output
2576 public static final function getHashLength () {
2578 if (is_null(self::$hashLength)) {
2579 // No, then hash a string and save its length.
2580 self::$hashLength = strlen(self::hash('abc123'));
2584 return self::$hashLength;
2588 * Checks whether the given number is really a number (only chars 0-9).
2590 * @param $num A string consisting only chars between 0 and 9
2591 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2592 * @param $assertMismatch Whether to assert mismatches
2593 * @return $ret The (hopefully) secured numbered value
2595 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2596 // Filter all numbers out
2597 $ret = preg_replace('/[^0123456789]/', '', $num);
2600 if ($castValue === TRUE) {
2601 // Cast to biggest numeric type
2602 $ret = (double) $ret;
2605 // Assert only if requested
2606 if ($assertMismatch === TRUE) {
2607 // Has the whole value changed?
2608 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2616 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2618 * @param $num A string consisting only chars between 0 and 9
2619 * @param $assertMismatch Whether to assert mismatches
2620 * @return $ret The (hopefully) secured hext-numbered value
2622 public function hexval ($num, $assertMismatch = FALSE) {
2623 // Filter all numbers out
2624 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2626 // Assert only if requested
2627 if ($assertMismatch === TRUE) {
2628 // Has the whole value changed?
2629 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2637 * Checks whether start/end marker are set
2639 * @param $data Data to be checked
2640 * @return $isset Whether start/end marker are set
2642 public final function ifStartEndMarkersSet ($data) {
2644 $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));
2646 // ... and return it
2651 * Determines if an element is set in the generic array
2653 * @param $keyGroup Main group for the key
2654 * @param $subGroup Sub group for the key
2655 * @param $key Key to check
2656 * @param $element Element to check
2657 * @return $isset Whether the given key is set
2659 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2661 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2664 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2670 * Determines if a key is set in the generic array
2672 * @param $keyGroup Main group for the key
2673 * @param $subGroup Sub group for the key
2674 * @param $key Key to check
2675 * @return $isset Whether the given key is set
2677 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2679 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2682 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2690 * Determines if a group is set in the generic array
2692 * @param $keyGroup Main group
2693 * @param $subGroup Sub group
2694 * @return $isset Whether the given group is set
2696 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2698 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2701 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2708 * Getter for sub key group
2710 * @param $keyGroup Main key group
2711 * @param $subGroup Sub key group
2712 * @return $array An array with all array elements
2714 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2716 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2717 // No, then abort here
2718 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2723 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2726 return $this->genericArray[$keyGroup][$subGroup];
2730 * Unsets a given key in generic array
2732 * @param $keyGroup Main group for the key
2733 * @param $subGroup Sub group for the key
2734 * @param $key Key to unset
2737 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2739 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2742 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2746 * Unsets a given element in generic array
2748 * @param $keyGroup Main group for the key
2749 * @param $subGroup Sub group for the key
2750 * @param $key Key to unset
2751 * @param $element Element to unset
2754 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2756 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2759 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2763 * Append a string to a given generic array key
2765 * @param $keyGroup Main group for the key
2766 * @param $subGroup Sub group for the key
2767 * @param $key Key to unset
2768 * @param $value Value to add/append
2771 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2773 //* 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);
2775 // Is it already there?
2776 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2778 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2781 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2786 * Append a string to a 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 unset
2791 * @param $element Element to check
2792 * @param $value Value to add/append
2795 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2797 //* 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);
2799 // Is it already there?
2800 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2802 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2805 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2810 * Sets a string in a given generic array element
2812 * @param $keyGroup Main group for the key
2813 * @param $subGroup Sub group for the key
2814 * @param $key Key to unset
2815 * @param $element Element to check
2816 * @param $value Value to add/append
2819 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2821 //* 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);
2824 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2828 * Initializes given generic array group
2830 * @param $keyGroup Main group for the key
2831 * @param $subGroup Sub group for the key
2832 * @param $key Key to use
2833 * @param $forceInit Optionally force initialization
2836 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2838 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2840 // Is it already set?
2841 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2842 // Already initialized
2843 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2848 $this->genericArray[$keyGroup][$subGroup] = array();
2852 * Initializes given generic array key
2854 * @param $keyGroup Main group for the key
2855 * @param $subGroup Sub group for the key
2856 * @param $key Key to use
2857 * @param $forceInit Optionally force initialization
2860 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2862 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2864 // Is it already set?
2865 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2866 // Already initialized
2867 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2872 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2876 * Initializes given generic array element
2878 * @param $keyGroup Main group for the key
2879 * @param $subGroup Sub group for the key
2880 * @param $key Key to use
2881 * @param $element Element to use
2882 * @param $forceInit Optionally force initialization
2885 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2887 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2889 // Is it already set?
2890 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2891 // Already initialized
2892 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2897 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2901 * Pushes an element to a generic key
2903 * @param $keyGroup Main group for the key
2904 * @param $subGroup Sub group for the key
2905 * @param $key Key to use
2906 * @param $value Value to add/append
2907 * @return $count Number of array elements
2909 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2911 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2914 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2916 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2920 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2923 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2924 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2929 * Pushes an element to a generic array element
2931 * @param $keyGroup Main group for the key
2932 * @param $subGroup Sub group for the key
2933 * @param $key Key to use
2934 * @param $element Element to check
2935 * @param $value Value to add/append
2936 * @return $count Number of array elements
2938 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2940 //* 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));
2943 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2945 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2949 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2952 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2953 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2958 * Pops an element from a generic group
2960 * @param $keyGroup Main group for the key
2961 * @param $subGroup Sub group for the key
2962 * @param $key Key to unset
2963 * @return $value Last "popped" value
2965 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2967 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2970 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2972 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2977 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2980 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2981 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2986 * Shifts an element from a generic group
2988 * @param $keyGroup Main group for the key
2989 * @param $subGroup Sub group for the key
2990 * @param $key Key to unset
2991 * @return $value Last "popped" value
2993 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2995 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2998 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3000 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3005 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3008 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3009 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3014 * Count generic array group
3016 * @param $keyGroup Main group for the key
3017 * @return $count Count of given group
3019 protected final function countGenericArray ($keyGroup) {
3021 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3024 if (!isset($this->genericArray[$keyGroup])) {
3026 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3031 $count = count($this->genericArray[$keyGroup]);
3034 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3041 * Count generic array sub group
3043 * @param $keyGroup Main group for the key
3044 * @param $subGroup Sub group for the key
3045 * @return $count Count of given group
3047 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3049 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3052 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3054 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3059 $count = count($this->genericArray[$keyGroup][$subGroup]);
3062 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3069 * Count generic array elements
3071 * @param $keyGroup Main group for the key
3072 * @param $subGroup Sub group for the key
3073 * @para $key Key to count
3074 * @return $count Count of given key
3076 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3078 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3081 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3083 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3085 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3087 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3092 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3095 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3102 * Getter for whole generic group array
3104 * @param $keyGroup Key group to get
3105 * @return $array Whole generic array group
3107 protected final function getGenericArray ($keyGroup) {
3109 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3112 if (!isset($this->genericArray[$keyGroup])) {
3114 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3119 return $this->genericArray[$keyGroup];
3123 * Setter for generic array key
3125 * @param $keyGroup Key group to get
3126 * @param $subGroup Sub group for the key
3127 * @param $key Key to unset
3128 * @param $value Mixed value from generic array element
3131 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3133 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3136 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3140 * Getter for generic array key
3142 * @param $keyGroup Key group to get
3143 * @param $subGroup Sub group for the key
3144 * @param $key Key to unset
3145 * @return $value Mixed value from generic array element
3147 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3149 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3152 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3154 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3159 return $this->genericArray[$keyGroup][$subGroup][$key];
3163 * Sets a value in given generic array key/element
3165 * @param $keyGroup Main group for the key
3166 * @param $subGroup Sub group for the key
3167 * @param $key Key to set
3168 * @param $element Element to set
3169 * @param $value Value to set
3172 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3174 //* 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));
3177 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3181 * Getter for generic array element
3183 * @param $keyGroup Key group to get
3184 * @param $subGroup Sub group for the key
3185 * @param $key Key to look for
3186 * @param $element Element to look for
3187 * @return $value Mixed value from generic array element
3189 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3191 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3194 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3196 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3201 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3205 * Checks if a given sub group is valid (array)
3207 * @param $keyGroup Key group to get
3208 * @param $subGroup Sub group for the key
3209 * @return $isValid Whether given sub group is valid
3211 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3213 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3216 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3223 * Checks if a given key is valid (array)
3225 * @param $keyGroup Key group to get
3226 * @param $subGroup Sub group for the key
3227 * @param $key Key to check
3228 * @return $isValid Whether given sub group is valid
3230 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3232 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3235 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3242 * Initializes the web output instance
3246 protected function initWebOutputInstance () {
3247 // Get application instance
3248 $applicationInstance = Registry::getRegistry()->getInstance('app');
3250 // Is this a response instance?
3251 if ($this instanceof Responseable) {
3252 // Then set it in application instance
3253 $applicationInstance->setResponseInstance($this);
3256 // Init web output instance
3257 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3260 $this->setWebOutputInstance($outputInstance);
3264 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3266 * @param $boolean Boolean value
3267 * @return $translated Translated boolean value
3269 public static final function translateBooleanToYesNo ($boolean) {
3270 // Make sure it is really boolean
3271 assert(is_bool($boolean));
3274 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3276 // ... and return it
3281 * Encodes raw data (almost any type) by "serializing" it and then pack it
3282 * into a "binary format".
3284 * @param $rawData Raw data (almost any type)
3285 * @return $encoded Encoded data
3287 protected function encodeData ($rawData) {
3288 // Make sure no objects or resources pass through
3289 assert(!is_object($rawData));
3290 assert(!is_resource($rawData));
3292 // First "serialize" it (json_encode() is faster than serialize())
3293 $encoded = $this->packString(json_encode($rawData));
3300 * Pack a string into a "binary format". Please execuse me that this is
3301 * widely undocumented. :-(
3303 * @param $str Unpacked string
3304 * @return $packed Packed string
3305 * @todo Improve documentation
3307 protected function packString ($str) {
3309 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('str=' . $str . ' - CALLED!');
3311 // First compress the string (gzcompress is okay)
3312 $str = gzcompress($str);
3317 // And start the "encoding" loop
3318 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3320 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3321 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3323 if (($idx + $i) <= strlen($str)) {
3324 $ord = ord(substr($str, ($idx + $i), 1));
3326 $add = $ord * pow(256, $factor);
3330 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3334 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3335 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3337 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3338 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3344 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__)->debugOutput('packed=' . $packed . ' - EXIT!');
3349 * Checks whether the given file/path is in open_basedir(). This does not
3350 * gurantee that the file is actually readable and/or writeable. If you need
3351 * such gurantee then please use isReadableFile() instead.
3353 * @param $filePathName Name of the file/path to be checked
3354 * @return $isReachable Whether it is within open_basedir()
3356 protected static function isReachableFilePath ($filePathName) {
3357 // Is not reachable by default
3358 $isReachable = FALSE;
3360 // Get open_basedir parameter
3361 $openBaseDir = ini_get('open_basedir');
3364 if (!empty($openBaseDir)) {
3365 // Check all entries
3366 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3367 // Check on existence
3368 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3370 $isReachable = TRUE;
3374 // If open_basedir is not set, all is allowed
3375 $isReachable = TRUE;
3379 return $isReachable;
3383 * Checks whether the give file is within open_basedir() (done by
3384 * isReachableFilePath()), is actually a file and is readable.
3386 * @param $fileName Name of the file to be checked
3387 * @return $isReadable Whether the file is readable (and therefor exists)
3389 public static function isReadableFile ($fileName) {
3390 // Default is not readable
3391 $isReadable = FALSE;
3393 // Is within parameters, so check if it is a file and readable
3394 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3401 * Creates a full-qualified file name (FQFN) for given file name by adding
3402 * a configured temporary file path to it.
3404 * @param $fileName Name for temporary file
3405 * @return $fqfn Full-qualified file name
3406 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3407 * @throws FileIoException If the file cannot be written
3409 protected static function createTempPathForFile ($fileName) {
3411 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3413 // Is the path writeable?
3414 if (!is_writable($basePath)) {
3415 // Path is write-protected
3416 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3420 $fqfn = $basePath . '/' . $fileName;
3423 if (!self::isReachableFilePath($fqfn)) {
3425 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3433 * "Getter" for a printable state name
3435 * @return $stateName Name of the node's state in a printable format
3437 public final function getPrintableState () {
3438 // Default is 'null'
3439 $stateName = 'null';
3441 // Get the state instance
3442 $stateInstance = $this->getStateInstance();
3444 // Is it an instance of Stateable?
3445 if ($stateInstance instanceof Stateable) {
3446 // Then use that state name
3447 $stateName = $stateInstance->getStateName();
3455 * Handles socket error for given socket resource and peer data. This method
3456 * validates $socketResource if it is a valid resource (see is_resource())
3457 * but assumes valid data in array $recipientData, except that
3458 * count($recipientData) is always 2.
3460 * @param $method Value of __METHOD__ from calling method
3461 * @param $line Value of __LINE__ from calling method
3462 * @param $socketResource A valid socket resource
3463 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3465 * @throws InvalidSocketException If $socketResource is no socket resource
3466 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3467 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3469 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3470 // This method handles only socket resources
3471 if (!is_resource($socketResource)) {
3472 // No resource, abort here
3473 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3476 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3477 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3478 assert(isset($socketData[0]));
3479 assert(isset($socketData[1]));
3481 // Get error code for first validation (0 is not an error)
3482 $errorCode = socket_last_error($socketResource);
3484 // If the error code is zero, someone called this method without an error
3485 if ($errorCode == 0) {
3486 // No error detected (or previously cleared outside this method)
3487 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3490 // Get handler (method) name
3491 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3493 // Call-back the error handler method
3494 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3496 // Finally clear the error because it has been handled
3497 socket_clear_error($socketResource);