3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Factory\ObjectFactory;
8 use CoreFramework\Generic\FrameworkInterface;
9 use CoreFramework\Generic\NullPointerException;
10 use CoreFramework\Handler\Stream\IoHandler;
11 use CoreFramework\Loader\ClassLoader;
12 use CoreFramework\Manager\ManageableApplication;
13 use CoreFramework\Middleware\Debug\DebugMiddleware;
14 use CoreFramework\Registry\Register;
15 use CoreFramework\Registry\Registry;
16 use CoreFramework\Request\Requestable;
17 use CoreFramework\Response\Responseable;
18 use CoreFramework\Stream\Output\OutputStreamer;
19 use CoreFramework\Template\CompileableTemplate;
25 * The simulator system class is the super class of all other classes. This
26 * class handles saving of games etc.
28 * @author Roland Haeder <webmaster@shipsimu.org>
30 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
31 * @license GNU GPL 3.0 or any newer version
32 * @link http://www.shipsimu.org
34 * This program is free software: you can redistribute it and/or modify
35 * it under the terms of the GNU General Public License as published by
36 * the Free Software Foundation, either version 3 of the License, or
37 * (at your option) any later version.
39 * This program is distributed in the hope that it will be useful,
40 * but WITHOUT ANY WARRANTY; without even the implied warranty of
41 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
42 * GNU General Public License for more details.
44 * You should have received a copy of the GNU General Public License
45 * along with this program. If not, see <http://www.gnu.org/licenses/>.
47 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
49 * Length of output from hash()
51 private static $hashLength = NULL;
56 private $realClass = 'BaseFrameworkSystem';
59 * Instance of a Requestable class
61 private $requestInstance = NULL;
64 * Instance of a Responseable class
66 private $responseInstance = NULL;
69 * Search criteria instance
71 private $searchInstance = NULL;
74 * Update criteria instance
76 private $updateInstance = NULL;
79 * The file I/O instance for the template loader
81 private $fileIoInstance = NULL;
86 private $resolverInstance = NULL;
89 * Template engine instance
91 private $templateInstance = NULL;
94 * Database result instance
96 private $resultInstance = NULL;
99 * Instance for user class
101 private $userInstance = NULL;
104 * A controller instance
106 private $controllerInstance = NULL;
111 private $rngInstance = NULL;
114 * Instance of a crypto helper
116 private $cryptoInstance = NULL;
119 * Instance of an Iterator class
121 private $iteratorInstance = NULL;
124 * Instance of the list
126 private $listInstance = NULL;
131 private $menuInstance = NULL;
134 * Instance of the image
136 private $imageInstance = NULL;
139 * Instance of the stacker
141 private $stackInstance = NULL;
144 * A Compressor instance
146 private $compressorInstance = NULL;
149 * A Parseable instance
151 private $parserInstance = NULL;
154 * A HandleableProtocol instance
156 private $protocolInstance = NULL;
159 * A database wrapper instance
161 private $databaseInstance = NULL;
164 * A helper instance for the form
166 private $helperInstance = NULL;
169 * An instance of a Source class
171 private $sourceInstance = NULL;
174 * An instance of a UrlSource class
176 private $urlSourceInstance = NULL;
179 * An instance of a InputStream class
181 private $inputStreamInstance = NULL;
184 * An instance of a OutputStream class
186 private $outputStreamInstance = NULL;
189 * Networkable handler instance
191 private $handlerInstance = NULL;
194 * Visitor handler instance
196 private $visitorInstance = NULL;
201 private $dhtInstance = NULL;
204 * An instance of a database wrapper class
206 private $wrapperInstance = NULL;
209 * An instance of a file I/O pointer class (not handler)
211 private $pointerInstance = NULL;
214 * An instance of an Indexable class
216 private $indexInstance = NULL;
219 * An instance of a Block class
221 private $blockInstance = NULL;
226 private $minableInstance = NULL;
229 * A FrameworkDirectory instance
231 private $directoryInstance = NULL;
236 private $listenerInstance = NULL;
239 * An instance of a communicator
241 private $communicatorInstance = NULL;
244 * The concrete output instance
246 private $outputInstance = NULL;
251 private $stateInstance = NULL;
254 * Thousands separator
256 private $thousands = '.'; // German
261 private $decimals = ','; // German
266 private $socketResource = FALSE;
269 * Regular expression to use for validation
271 private $regularExpression = '';
276 private $packageData = array();
281 private $genericArray = array();
286 private $commandName = '';
291 private $controllerName = '';
294 * Name of used protocol
296 private $protocolName = 'invalid';
299 * Array with bitmasks and such for pack/unpack methods to support both
300 * 32-bit and 64-bit systems
302 private $packingData = array(
305 'left' => 0xffff0000,
306 'right' => 0x0000ffff,
312 'left' => 0xffffffff00000000,
313 'right' => 0x00000000ffffffff,
320 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
322 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
324 private $archArrayElement = FALSE;
326 /***********************
327 * Exception codes.... *
328 ***********************/
330 // @todo Try to clean these constants up
331 const EXCEPTION_IS_NULL_POINTER = 0x001;
332 const EXCEPTION_IS_NO_OBJECT = 0x002;
333 const EXCEPTION_IS_NO_ARRAY = 0x003;
334 const EXCEPTION_MISSING_METHOD = 0x004;
335 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
336 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
337 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
338 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
339 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
340 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
341 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
342 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
343 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
344 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
345 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
346 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
347 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
348 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
349 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
350 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
351 const EXCEPTION_PATH_NOT_FOUND = 0x015;
352 const EXCEPTION_INVALID_PATH_NAME = 0x016;
353 const EXCEPTION_READ_PROTECED_PATH = 0x017;
354 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
355 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
356 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
357 const EXCEPTION_INVALID_RESOURCE = 0x01b;
358 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
359 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
360 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
361 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
362 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
363 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
364 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
365 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
366 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
367 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
368 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
369 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
370 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
371 const EXCEPTION_INVALID_STRING = 0x029;
372 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
373 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
374 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
375 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
376 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
377 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
378 const EXCEPTION_MISSING_ELEMENT = 0x030;
379 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
380 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
381 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
382 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
383 const EXCEPTION_FATAL_ERROR = 0x035;
384 const EXCEPTION_FILE_NOT_FOUND = 0x036;
385 const EXCEPTION_ASSERTION_FAILED = 0x037;
386 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
387 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
388 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
389 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
390 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
391 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
394 * Hexadecimal->Decimal translation array
396 private static $hexdec = array(
416 * Decimal->hexadecimal translation array
418 private static $dechex = array(
438 * Startup time in miliseconds
440 private static $startupTime = 0;
443 * Protected super constructor
445 * @param $className Name of the class
448 protected function __construct ($className) {
450 $this->setRealClass($className);
452 // Set configuration instance if no registry ...
453 if (!$this instanceof Register) {
454 // ... because registries doesn't need to be configured
455 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
458 // Is the startup time set? (0 cannot be TRUE anymore)
459 if (self::$startupTime == 0) {
461 self::$startupTime = microtime(TRUE);
465 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
469 * Destructor for all classes. You should not call this method on your own.
473 public function __destruct () {
474 // Flush any updated entries to the database
475 $this->flushPendingUpdates();
477 // Is this object already destroyed?
478 if ($this->__toString() != 'DestructedObject') {
479 // Destroy all informations about this class but keep some text about it alive
480 $this->setRealClass('DestructedObject');
481 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
482 // Already destructed object
483 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
488 // Do not call this twice
489 trigger_error(__METHOD__ . ': Called twice.');
495 * The __call() method where all non-implemented methods end up
497 * @param $methodName Name of the missing method
498 * @args $args Arguments passed to the method
501 public final function __call ($methodName, $args) {
502 return self::__callStatic($methodName, $args);
506 * The __callStatic() method where all non-implemented static methods end up
508 * @param $methodName Name of the missing method
509 * @args $args Arguments passed to the method
512 public static final function __callStatic ($methodName, $args) {
514 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
516 // Init argument string
519 // Is it NULL, empty or an array?
520 if (is_null($args)) {
522 $argsString = 'NULL';
523 } elseif (is_array($args)) {
527 // Some arguments are there
528 foreach ($args as $arg) {
529 // Add data about the argument
530 $argsString .= gettype($arg) . ':';
533 // Found a NULL argument
534 $argsString .= 'NULL';
535 } elseif (is_string($arg)) {
536 // Add length for strings
537 $argsString .= strlen($arg);
538 } elseif ((is_int($arg)) || (is_float($arg))) {
541 } elseif (is_array($arg)) {
542 // .. or size if array
543 $argsString .= count($arg);
544 } elseif (is_object($arg)) {
546 $reflection = new ReflectionClass($arg);
548 // Is an other object, maybe no __toString() available
549 $argsString .= $reflection->getName();
550 } elseif ($arg === TRUE) {
551 // ... is boolean 'TRUE'
552 $argsString .= 'TRUE';
553 } elseif ($arg === FALSE) {
554 // ... is boolean 'FALSE'
555 $argsString .= 'FALSE';
558 // Comma for next one
563 if (substr($argsString, -2, 1) == ',') {
564 $argsString = substr($argsString, 0, -2);
570 // Invalid arguments!
571 $argsString = '!INVALID:' . gettype($args) . '!';
574 // Output stub message
575 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
576 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
586 * Getter for $realClass
588 * @return $realClass The name of the real class (not BaseFrameworkSystem)
590 public function __toString () {
591 return $this->realClass;
595 * Magic method to catch setting of missing but set class fields/attributes
597 * @param $name Name of the field/attribute
598 * @param $value Value to store
601 public final function __set ($name, $value) {
602 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
605 print_r($value, TRUE)
610 * Magic method to catch getting of missing fields/attributes
612 * @param $name Name of the field/attribute
615 public final function __get ($name) {
616 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
622 * Magic method to catch unsetting of missing fields/attributes
624 * @param $name Name of the field/attribute
627 public final function __unset ($name) {
628 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
634 * Magic method to catch object serialization
636 * @return $unsupported Unsupported method
637 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
639 public final function __sleep () {
640 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
644 * Magic method to catch object deserialization
646 * @return $unsupported Unsupported method
647 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
649 public final function __wakeup () {
650 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
654 * Magic method to catch calls when an object instance is called
656 * @return $unsupported Unsupported method
657 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
659 public final function __invoke () {
660 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
664 * Setter for the real class name
666 * @param $realClass Class name (string)
669 public final function setRealClass ($realClass) {
671 $this->realClass = (string) $realClass;
675 * Setter for database result instance
677 * @param $resultInstance An instance of a database result class
679 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
681 protected final function setResultInstance (SearchableResult $resultInstance) {
682 $this->resultInstance = $resultInstance;
686 * Getter for database result instance
688 * @return $resultInstance An instance of a database result class
690 public final function getResultInstance () {
691 return $this->resultInstance;
695 * Setter for template engine instances
697 * @param $templateInstance An instance of a template engine class
700 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
701 $this->templateInstance = $templateInstance;
705 * Getter for template engine instances
707 * @return $templateInstance An instance of a template engine class
709 protected final function getTemplateInstance () {
710 return $this->templateInstance;
714 * Setter for search instance
716 * @param $searchInstance Searchable criteria instance
719 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
720 $this->searchInstance = $searchInstance;
724 * Getter for search instance
726 * @return $searchInstance Searchable criteria instance
728 public final function getSearchInstance () {
729 return $this->searchInstance;
733 * Setter for update instance
735 * @param $updateInstance Searchable criteria instance
738 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
739 $this->updateInstance = $updateInstance;
743 * Getter for update instance
745 * @return $updateInstance Updateable criteria instance
747 public final function getUpdateInstance () {
748 return $this->updateInstance;
752 * Setter for resolver instance
754 * @param $resolverInstance Instance of a command resolver class
757 public final function setResolverInstance (Resolver $resolverInstance) {
758 $this->resolverInstance = $resolverInstance;
762 * Getter for resolver instance
764 * @return $resolverInstance Instance of a command resolver class
766 public final function getResolverInstance () {
767 return $this->resolverInstance;
771 * Setter for language instance
773 * @param $configInstance The configuration instance which shall
774 * be FrameworkConfiguration
777 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
778 Registry::getRegistry()->addInstance('config', $configInstance);
782 * Getter for configuration instance
784 * @return $configInstance Configuration instance
786 public final function getConfigInstance () {
787 $configInstance = Registry::getRegistry()->getInstance('config');
788 return $configInstance;
792 * Setter for debug instance
794 * @param $debugInstance The instance for debug output class
797 public final function setDebugInstance (DebugMiddleware $debugInstance) {
798 Registry::getRegistry()->addInstance('debug', $debugInstance);
802 * Getter for debug instance
804 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
806 public final function getDebugInstance () {
807 // Get debug instance
808 $debugInstance = Registry::getRegistry()->getInstance('debug');
811 return $debugInstance;
815 * Setter for web output instance
817 * @param $webInstance The instance for web output class
820 public final function setWebOutputInstance (OutputStreamer $webInstance) {
821 Registry::getRegistry()->addInstance('web_output', $webInstance);
825 * Getter for web output instance
827 * @return $webOutputInstance - Instance to class WebOutput
829 public final function getWebOutputInstance () {
830 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
831 return $webOutputInstance;
835 * Setter for database instance
837 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
840 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
841 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
845 * Getter for database layer
847 * @return $databaseInstance The database layer instance
849 public final function getDatabaseInstance () {
851 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
854 return $databaseInstance;
858 * Setter for compressor channel
860 * @param $compressorInstance An instance of CompressorChannel
863 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
864 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
868 * Getter for compressor channel
870 * @return $compressorInstance The compressor channel
872 public final function getCompressorChannel () {
873 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
874 return $compressorInstance;
878 * Protected getter for a manageable application helper class
880 * @return $applicationInstance An instance of a manageable application helper class
882 protected final function getApplicationInstance () {
883 $applicationInstance = Registry::getRegistry()->getInstance('application');
884 return $applicationInstance;
888 * Setter for a manageable application helper class
890 * @param $applicationInstance An instance of a manageable application helper class
893 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
894 Registry::getRegistry()->addInstance('application', $applicationInstance);
898 * Setter for request instance
900 * @param $requestInstance An instance of a Requestable class
903 public final function setRequestInstance (Requestable $requestInstance) {
904 $this->requestInstance = $requestInstance;
908 * Getter for request instance
910 * @return $requestInstance An instance of a Requestable class
912 public final function getRequestInstance () {
913 return $this->requestInstance;
917 * Setter for response instance
919 * @param $responseInstance An instance of a Responseable class
922 public final function setResponseInstance (Responseable $responseInstance) {
923 $this->responseInstance = $responseInstance;
927 * Getter for response instance
929 * @return $responseInstance An instance of a Responseable class
931 public final function getResponseInstance () {
932 return $this->responseInstance;
936 * Private getter for language instance
938 * @return $langInstance An instance to the language sub-system
940 protected final function getLanguageInstance () {
941 $langInstance = Registry::getRegistry()->getInstance('language');
942 return $langInstance;
946 * Setter for language instance
948 * @param $langInstance An instance to the language sub-system
950 * @see LanguageSystem
952 public final function setLanguageInstance (ManageableLanguage $langInstance) {
953 Registry::getRegistry()->addInstance('language', $langInstance);
957 * Private getter for file IO instance
959 * @return $fileIoInstance An instance to the file I/O sub-system
961 protected final function getFileIoInstance () {
962 return $this->fileIoInstance;
966 * Setter for file I/O instance
968 * @param $fileIoInstance An instance to the file I/O sub-system
971 public final function setFileIoInstance (IoHandler $fileIoInstance) {
972 $this->fileIoInstance = $fileIoInstance;
976 * Protected setter for user instance
978 * @param $userInstance An instance of a user class
981 protected final function setUserInstance (ManageableAccount $userInstance) {
982 $this->userInstance = $userInstance;
986 * Getter for user instance
988 * @return $userInstance An instance of a user class
990 public final function getUserInstance () {
991 return $this->userInstance;
995 * Setter for controller instance (this surely breaks a bit the MVC patterm)
997 * @param $controllerInstance An instance of the controller
1000 public final function setControllerInstance (Controller $controllerInstance) {
1001 $this->controllerInstance = $controllerInstance;
1005 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1007 * @return $controllerInstance An instance of the controller
1009 public final function getControllerInstance () {
1010 return $this->controllerInstance;
1014 * Setter for RNG instance
1016 * @param $rngInstance An instance of a random number generator (RNG)
1019 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1020 $this->rngInstance = $rngInstance;
1024 * Getter for RNG instance
1026 * @return $rngInstance An instance of a random number generator (RNG)
1028 public final function getRngInstance () {
1029 return $this->rngInstance;
1033 * Setter for Cryptable instance
1035 * @param $cryptoInstance An instance of a Cryptable class
1038 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1039 $this->cryptoInstance = $cryptoInstance;
1043 * Getter for Cryptable instance
1045 * @return $cryptoInstance An instance of a Cryptable class
1047 public final function getCryptoInstance () {
1048 return $this->cryptoInstance;
1052 * Setter for the list instance
1054 * @param $listInstance A list of Listable
1057 protected final function setListInstance (Listable $listInstance) {
1058 $this->listInstance = $listInstance;
1062 * Getter for the list instance
1064 * @return $listInstance A list of Listable
1066 protected final function getListInstance () {
1067 return $this->listInstance;
1071 * Setter for the menu instance
1073 * @param $menuInstance A RenderableMenu instance
1076 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1077 $this->menuInstance = $menuInstance;
1081 * Getter for the menu instance
1083 * @return $menuInstance A RenderableMenu instance
1085 protected final function getMenuInstance () {
1086 return $this->menuInstance;
1090 * Setter for image instance
1092 * @param $imageInstance An instance of an image
1095 public final function setImageInstance (BaseImage $imageInstance) {
1096 $this->imageInstance = $imageInstance;
1100 * Getter for image instance
1102 * @return $imageInstance An instance of an image
1104 public final function getImageInstance () {
1105 return $this->imageInstance;
1109 * Setter for stacker instance
1111 * @param $stackInstance An instance of an stacker
1114 public final function setStackInstance (Stackable $stackInstance) {
1115 $this->stackInstance = $stackInstance;
1119 * Getter for stacker instance
1121 * @return $stackInstance An instance of an stacker
1123 public final function getStackInstance () {
1124 return $this->stackInstance;
1128 * Setter for compressor instance
1130 * @param $compressorInstance An instance of an compressor
1133 public final function setCompressorInstance (Compressor $compressorInstance) {
1134 $this->compressorInstance = $compressorInstance;
1138 * Getter for compressor instance
1140 * @return $compressorInstance An instance of an compressor
1142 public final function getCompressorInstance () {
1143 return $this->compressorInstance;
1147 * Setter for Parseable instance
1149 * @param $parserInstance An instance of an Parseable
1152 public final function setParserInstance (Parseable $parserInstance) {
1153 $this->parserInstance = $parserInstance;
1157 * Getter for Parseable instance
1159 * @return $parserInstance An instance of an Parseable
1161 public final function getParserInstance () {
1162 return $this->parserInstance;
1166 * Setter for HandleableProtocol instance
1168 * @param $protocolInstance An instance of an HandleableProtocol
1171 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1172 $this->protocolInstance = $protocolInstance;
1176 * Getter for HandleableProtocol instance
1178 * @return $protocolInstance An instance of an HandleableProtocol
1180 public final function getProtocolInstance () {
1181 return $this->protocolInstance;
1185 * Setter for DatabaseWrapper instance
1187 * @param $wrapperInstance An instance of an DatabaseWrapper
1190 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1191 $this->wrapperInstance = $wrapperInstance;
1195 * Getter for DatabaseWrapper instance
1197 * @return $wrapperInstance An instance of an DatabaseWrapper
1199 public final function getWrapperInstance () {
1200 return $this->wrapperInstance;
1204 * Setter for socket resource
1206 * @param $socketResource A valid socket resource
1209 public final function setSocketResource ($socketResource) {
1210 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1211 $this->socketResource = $socketResource;
1215 * Getter for socket resource
1217 * @return $socketResource A valid socket resource
1219 public final function getSocketResource () {
1220 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1221 return $this->socketResource;
1225 * Setter for regular expression
1227 * @param $regularExpression A valid regular expression
1230 public final function setRegularExpression ($regularExpression) {
1231 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1232 $this->regularExpression = $regularExpression;
1236 * Getter for regular expression
1238 * @return $regularExpression A valid regular expression
1240 public final function getRegularExpression () {
1241 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1242 return $this->regularExpression;
1246 * Setter for helper instance
1248 * @param $helperInstance An instance of a helper class
1251 protected final function setHelperInstance (Helper $helperInstance) {
1252 $this->helperInstance = $helperInstance;
1256 * Getter for helper instance
1258 * @return $helperInstance An instance of a helper class
1260 public final function getHelperInstance () {
1261 return $this->helperInstance;
1265 * Setter for a Source instance
1267 * @param $sourceInstance An instance of a Source class
1270 protected final function setSourceInstance (Source $sourceInstance) {
1271 $this->sourceInstance = $sourceInstance;
1275 * Getter for a Source instance
1277 * @return $sourceInstance An instance of a Source class
1279 protected final function getSourceInstance () {
1280 return $this->sourceInstance;
1284 * Setter for a UrlSource instance
1286 * @param $sourceInstance An instance of a UrlSource class
1289 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1290 $this->urlSourceInstance = $urlSourceInstance;
1294 * Getter for a UrlSource instance
1296 * @return $urlSourceInstance An instance of a UrlSource class
1298 protected final function getUrlSourceInstance () {
1299 return $this->urlSourceInstance;
1303 * Getter for a InputStream instance
1305 * @param $inputStreamInstance The InputStream instance
1307 protected final function getInputStreamInstance () {
1308 return $this->inputStreamInstance;
1312 * Setter for a InputStream instance
1314 * @param $inputStreamInstance The InputStream instance
1317 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1318 $this->inputStreamInstance = $inputStreamInstance;
1322 * Getter for a OutputStream instance
1324 * @param $outputStreamInstance The OutputStream instance
1326 protected final function getOutputStreamInstance () {
1327 return $this->outputStreamInstance;
1331 * Setter for a OutputStream instance
1333 * @param $outputStreamInstance The OutputStream instance
1336 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1337 $this->outputStreamInstance = $outputStreamInstance;
1341 * Setter for handler instance
1343 * @param $handlerInstance An instance of a Handleable class
1346 protected final function setHandlerInstance (Handleable $handlerInstance) {
1347 $this->handlerInstance = $handlerInstance;
1351 * Getter for handler instance
1353 * @return $handlerInstance A Networkable instance
1355 protected final function getHandlerInstance () {
1356 return $this->handlerInstance;
1360 * Setter for visitor instance
1362 * @param $visitorInstance A Visitor instance
1365 protected final function setVisitorInstance (Visitor $visitorInstance) {
1366 $this->visitorInstance = $visitorInstance;
1370 * Getter for visitor instance
1372 * @return $visitorInstance A Visitor instance
1374 protected final function getVisitorInstance () {
1375 return $this->visitorInstance;
1379 * Setter for DHT instance
1381 * @param $dhtInstance A Distributable instance
1384 protected final function setDhtInstance (Distributable $dhtInstance) {
1385 $this->dhtInstance = $dhtInstance;
1389 * Getter for DHT instance
1391 * @return $dhtInstance A Distributable instance
1393 protected final function getDhtInstance () {
1394 return $this->dhtInstance;
1398 * Setter for raw package Data
1400 * @param $packageData Raw package Data
1403 public final function setPackageData (array $packageData) {
1404 $this->packageData = $packageData;
1408 * Getter for raw package Data
1410 * @return $packageData Raw package Data
1412 public function getPackageData () {
1413 return $this->packageData;
1418 * Setter for Iterator instance
1420 * @param $iteratorInstance An instance of an Iterator
1423 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1424 $this->iteratorInstance = $iteratorInstance;
1428 * Getter for Iterator instance
1430 * @return $iteratorInstance An instance of an Iterator
1432 public final function getIteratorInstance () {
1433 return $this->iteratorInstance;
1437 * Setter for FilePointer instance
1439 * @param $pointerInstance An instance of an FilePointer class
1442 protected final function setPointerInstance (FilePointer $pointerInstance) {
1443 $this->pointerInstance = $pointerInstance;
1447 * Getter for FilePointer instance
1449 * @return $pointerInstance An instance of an FilePointer class
1451 public final function getPointerInstance () {
1452 return $this->pointerInstance;
1456 * Unsets pointer instance which triggers a call of __destruct() if the
1457 * instance is still there. This is surely not fatal on already "closed"
1458 * file pointer instances.
1460 * I don't want to mess around with above setter by giving it a default
1461 * value NULL as setter should always explicitly only set (existing) object
1462 * instances and NULL is NULL.
1466 protected final function unsetPointerInstance () {
1467 // Simply it to NULL
1468 $this->pointerInstance = NULL;
1472 * Setter for Indexable instance
1474 * @param $indexInstance An instance of an Indexable class
1477 protected final function setIndexInstance (Indexable $indexInstance) {
1478 $this->indexInstance = $indexInstance;
1482 * Getter for Indexable instance
1484 * @return $indexInstance An instance of an Indexable class
1486 public final function getIndexInstance () {
1487 return $this->indexInstance;
1491 * Setter for Block instance
1493 * @param $blockInstance An instance of an Block class
1496 protected final function setBlockInstance (Block $blockInstance) {
1497 $this->blockInstance = $blockInstance;
1501 * Getter for Block instance
1503 * @return $blockInstance An instance of an Block class
1505 public final function getBlockInstance () {
1506 return $this->blockInstance;
1510 * Setter for Minable instance
1512 * @param $minableInstance A Minable instance
1515 protected final function setMinableInstance (Minable $minableInstance) {
1516 $this->minableInstance = $minableInstance;
1520 * Getter for minable instance
1522 * @return $minableInstance A Minable instance
1524 protected final function getMinableInstance () {
1525 return $this->minableInstance;
1529 * Setter for FrameworkDirectory instance
1531 * @param $directoryInstance A FrameworkDirectoryPointer instance
1534 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1535 $this->directoryInstance = $directoryInstance;
1539 * Getter for FrameworkDirectory instance
1541 * @return $directoryInstance A FrameworkDirectory instance
1543 protected final function getDirectoryInstance () {
1544 return $this->directoryInstance;
1548 * Setter for listener instance
1550 * @param $listenerInstance A Listenable instance
1553 protected final function setListenerInstance (Listenable $listenerInstance) {
1554 $this->listenerInstance = $listenerInstance;
1558 * Getter for listener instance
1560 * @return $listenerInstance A Listenable instance
1562 protected final function getListenerInstance () {
1563 return $this->listenerInstance;
1567 * Getter for communicator instance
1569 * @return $communicatorInstance An instance of a Communicator class
1571 public final function getCommunicatorInstance () {
1572 return $this->communicatorInstance;
1576 * Setter for communicator instance
1578 * @param $communicatorInstance An instance of a Communicator class
1581 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1582 $this->communicatorInstance = $communicatorInstance;
1586 * Setter for state instance
1588 * @param $stateInstance A Stateable instance
1591 public final function setStateInstance (Stateable $stateInstance) {
1592 $this->stateInstance = $stateInstance;
1596 * Getter for state instance
1598 * @return $stateInstance A Stateable instance
1600 public final function getStateInstance () {
1601 return $this->stateInstance;
1605 * Setter for output instance
1607 * @param $outputInstance The debug output instance
1610 public final function setOutputInstance (OutputStreamer $outputInstance) {
1611 $this->outputInstance = $outputInstance;
1615 * Getter for output instance
1617 * @return $outputInstance The debug output instance
1619 public final function getOutputInstance () {
1620 return $this->outputInstance;
1624 * Setter for command name
1626 * @param $commandName Last validated command name
1629 protected final function setCommandName ($commandName) {
1630 $this->commandName = $commandName;
1634 * Getter for command name
1636 * @return $commandName Last validated command name
1638 protected final function getCommandName () {
1639 return $this->commandName;
1643 * Setter for controller name
1645 * @param $controllerName Last validated controller name
1648 protected final function setControllerName ($controllerName) {
1649 $this->controllerName = $controllerName;
1653 * Getter for controller name
1655 * @return $controllerName Last validated controller name
1657 protected final function getControllerName () {
1658 return $this->controllerName;
1662 * Getter for protocol name
1664 * @return $protocolName Name of used protocol
1666 public final function getProtocolName () {
1667 return $this->protocolName;
1671 * Setter for protocol name
1673 * @param $protocolName Name of used protocol
1676 protected final function setProtocolName ($protocolName) {
1677 $this->protocolName = $protocolName;
1681 * Checks whether an object equals this object. You should overwrite this
1682 * method to implement own equality checks
1684 * @param $objectInstance An instance of a FrameworkInterface object
1685 * @return $equals Whether both objects equals
1687 public function equals (FrameworkInterface $objectInstance) {
1690 $this->__toString() == $objectInstance->__toString()
1692 $this->hashCode() == $objectInstance->hashCode()
1695 // Return the result
1700 * Generates a generic hash code of this class. You should really overwrite
1701 * this method with your own hash code generator code. But keep KISS in mind.
1703 * @return $hashCode A generic hash code respresenting this whole class
1705 public function hashCode () {
1707 return crc32($this->__toString());
1711 * Formats computer generated price values into human-understandable formats
1712 * with thousand and decimal separators.
1714 * @param $value The in computer format value for a price
1715 * @param $currency The currency symbol (use HTML-valid characters!)
1716 * @param $decNum Number of decimals after commata
1717 * @return $price The for the current language formated price string
1718 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1719 * thousands separator
1722 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1723 // Are all required attriutes set?
1724 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1725 // Throw an exception
1726 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1730 $value = (float) $value;
1732 // Reformat the US number
1733 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1735 // Return as string...
1740 * Appends a trailing slash to a string
1742 * @param $str A string (maybe) without trailing slash
1743 * @return $str A string with an auto-appended trailing slash
1745 public final function addMissingTrailingSlash ($str) {
1746 // Is there a trailing slash?
1747 if (substr($str, -1, 1) != '/') {
1751 // Return string with trailing slash
1756 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1757 * application helper instance (ApplicationHelper by default).
1759 * @param $applicationInstance An application helper instance or
1760 * null if we shall use the default
1761 * @return $templateInstance The template engine instance
1762 * @throws NullPointerException If the discovered application
1763 * instance is still null
1765 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1766 // Is the application instance set?
1767 if (is_null($applicationInstance)) {
1768 // Get the current instance
1769 $applicationInstance = $this->getApplicationInstance();
1772 if (is_null($applicationInstance)) {
1773 // Thrown an exception
1774 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1778 // Initialize the template engine
1779 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1781 // Return the prepared instance
1782 return $templateInstance;
1786 * Debugs this instance by putting out it's full content
1788 * @param $message Optional message to show in debug output
1791 public final function debugInstance ($message = '') {
1792 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1793 restore_error_handler();
1798 // Is a message set?
1799 if (!empty($message)) {
1800 // Construct message
1801 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1804 // Generate the output
1805 $content .= sprintf('<pre>%s</pre>',
1808 print_r($this, TRUE)
1814 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>',
1815 $this->__toString(),
1817 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1822 * Replaces control characters with printable output
1824 * @param $str String with control characters
1825 * @return $str Replaced string
1827 protected function replaceControlCharacters ($str) {
1830 chr(13), '[r]', str_replace(
1831 chr(10), '[n]', str_replace(
1841 * Output a partial stub message for the caller method
1843 * @param $message An optional message to display
1846 protected function partialStub ($message = '') {
1847 // Get the backtrace
1848 $backtrace = debug_backtrace();
1850 // Generate the class::method string
1851 $methodName = 'UnknownClass->unknownMethod';
1852 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1853 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1856 // Construct the full message
1857 $stubMessage = sprintf('[%s:] Partial stub!',
1861 // Is the extra message given?
1862 if (!empty($message)) {
1863 // Then add it as well
1864 $stubMessage .= ' Message: ' . $message;
1867 // Debug instance is there?
1868 if (!is_null($this->getDebugInstance())) {
1869 // Output stub message
1870 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1873 trigger_error($stubMessage);
1879 * Outputs a debug backtrace and stops further script execution
1881 * @param $message An optional message to output
1882 * @param $doExit Whether exit the program (TRUE is default)
1885 public function debugBackTrace ($message = '', $doExit = TRUE) {
1886 // Sorry, there is no other way getting this nice backtrace
1887 if (!empty($message)) {
1889 printf('Message: %s<br />' . PHP_EOL, $message);
1893 debug_print_backtrace();
1897 if ($doExit === TRUE) {
1903 * Creates an instance of a debugger instance
1905 * @param $className Name of the class (currently unsupported)
1906 * @param $lineNumber Line number where the call was made
1907 * @return $debugInstance An instance of a debugger class
1908 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1910 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1911 // Is the instance set?
1912 if (!Registry::getRegistry()->instanceExists('debug')) {
1913 // Init debug instance
1914 $debugInstance = NULL;
1918 // Get a debugger instance
1919 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1920 } catch (NullPointerException $e) {
1921 // Didn't work, no instance there
1922 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1925 // Empty string should be ignored and used for testing the middleware
1926 DebugMiddleware::getSelfInstance()->output('');
1928 // Set it in its own class. This will set it in the registry
1929 $debugInstance->setDebugInstance($debugInstance);
1931 // Get instance from registry
1932 $debugInstance = Registry::getRegistry()->getDebugInstance();
1936 return $debugInstance;
1940 * Simple output of a message with line-break
1942 * @param $message Message to output
1945 public function outputLine ($message) {
1947 print($message . PHP_EOL);
1951 * Outputs a debug message whether to debug instance (should be set!) or
1952 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1953 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1955 * @param $message Message we shall send out...
1956 * @param $doPrint Whether print or die here (default: print)
1957 * @paran $stripTags Whether to strip tags (default: FALSE)
1960 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1961 // Set debug instance to NULL
1962 $debugInstance = NULL;
1966 // Get debug instance
1967 $debugInstance = $this->getDebugInstance();
1968 } catch (NullPointerException $e) {
1969 // The debug instance is not set (yet)
1972 // Is the debug instance there?
1973 if (is_object($debugInstance)) {
1974 // Use debug output handler
1975 $debugInstance->output($message, $stripTags);
1977 if ($doPrint === FALSE) {
1978 // Die here if not printed
1982 // Are debug times enabled?
1983 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1985 $message = $this->getPrintableExecutionTime() . $message;
1989 if ($doPrint === TRUE) {
1991 $this->outputLine($message);
2000 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2002 * @param $str The string, what ever it is needs to be converted
2003 * @return $className Generated class name
2005 public static final function convertToClassName ($str) {
2009 // Convert all dashes in underscores
2010 $str = self::convertDashesToUnderscores($str);
2012 // Now use that underscores to get classname parts for hungarian style
2013 foreach (explode('_', $str) as $strPart) {
2014 // Make the class name part lower case and first upper case
2015 $className .= ucfirst(strtolower($strPart));
2018 // Return class name
2023 * Converts dashes to underscores, e.g. useable for configuration entries
2025 * @param $str The string with maybe dashes inside
2026 * @return $str The converted string with no dashed, but underscores
2028 public static final function convertDashesToUnderscores ($str) {
2030 $str = str_replace('-', '_', $str);
2032 // Return converted string
2037 * Marks up the code by adding e.g. line numbers
2039 * @param $phpCode Unmarked PHP code
2040 * @return $markedCode Marked PHP code
2042 public function markupCode ($phpCode) {
2047 $errorArray = error_get_last();
2049 // Init the code with error message
2050 if (is_array($errorArray)) {
2052 $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>',
2053 basename($errorArray['file']),
2054 $errorArray['line'],
2055 $errorArray['message'],
2060 // Add line number to the code
2061 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2063 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2065 htmlentities($code, ENT_QUOTES)
2074 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2075 * beatiful for web-based front-ends. If null is given a message id
2076 * null_timestamp will be resolved and returned.
2078 * @param $timestamp Timestamp to prepare (filter) for display
2079 * @return $readable A readable timestamp
2081 public function doFilterFormatTimestamp ($timestamp) {
2082 // Default value to return
2085 // Is the timestamp null?
2086 if (is_null($timestamp)) {
2087 // Get a message string
2088 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2090 switch ($this->getLanguageInstance()->getLanguageCode()) {
2091 case 'de': // German format is a bit different to default
2092 // Split the GMT stamp up
2093 $dateTime = explode(' ', $timestamp );
2094 $dateArray = explode('-', $dateTime[0]);
2095 $timeArray = explode(':', $dateTime[1]);
2097 // Construct the timestamp
2098 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2108 default: // Default is pass-through
2109 $readable = $timestamp;
2119 * Filter a given number into a localized number
2121 * @param $value The raw value from e.g. database
2122 * @return $localized Localized value
2124 public function doFilterFormatNumber ($value) {
2125 // Generate it from config and localize dependencies
2126 switch ($this->getLanguageInstance()->getLanguageCode()) {
2127 case 'de': // German format is a bit different to default
2128 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2131 default: // US, etc.
2132 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2141 * "Getter" for databse entry
2143 * @return $entry An array with database entries
2144 * @throws NullPointerException If the database result is not found
2145 * @throws InvalidDatabaseResultException If the database result is invalid
2147 protected final function getDatabaseEntry () {
2148 // Is there an instance?
2149 if (!$this->getResultInstance() instanceof SearchableResult) {
2150 // Throw an exception here
2151 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2155 $this->getResultInstance()->rewind();
2157 // Do we have an entry?
2158 if ($this->getResultInstance()->valid() === FALSE) {
2159 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2160 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2164 $this->getResultInstance()->next();
2167 $entry = $this->getResultInstance()->current();
2174 * Getter for field name
2176 * @param $fieldName Field name which we shall get
2177 * @return $fieldValue Field value from the user
2178 * @throws NullPointerException If the result instance is null
2180 public final function getField ($fieldName) {
2181 // Default field value
2184 // Get result instance
2185 $resultInstance = $this->getResultInstance();
2187 // Is this instance null?
2188 if (is_null($resultInstance)) {
2189 // Then the user instance is no longer valid (expired cookies?)
2190 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2193 // Get current array
2194 $fieldArray = $resultInstance->current();
2195 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2197 // Convert dashes to underscore
2198 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2200 // Does the field exist?
2201 if ($this->isFieldSet($fieldName)) {
2203 $fieldValue = $fieldArray[$fieldName2];
2204 } elseif (defined('DEVELOPER')) {
2205 // Missing field entry, may require debugging
2206 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2208 // Missing field entry, may require debugging
2209 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2217 * Checks if given field is set
2219 * @param $fieldName Field name to check
2220 * @return $isSet Whether the given field name is set
2221 * @throws NullPointerException If the result instance is null
2223 public function isFieldSet ($fieldName) {
2224 // Get result instance
2225 $resultInstance = $this->getResultInstance();
2227 // Is this instance null?
2228 if (is_null($resultInstance)) {
2229 // Then the user instance is no longer valid (expired cookies?)
2230 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2233 // Get current array
2234 $fieldArray = $resultInstance->current();
2235 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2237 // Convert dashes to underscore
2238 $fieldName = self::convertDashesToUnderscores($fieldName);
2241 $isSet = isset($fieldArray[$fieldName]);
2248 * Flushs all pending updates to the database layer
2252 public function flushPendingUpdates () {
2253 // Get result instance
2254 $resultInstance = $this->getResultInstance();
2256 // Do we have data to update?
2257 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2258 // Get wrapper class name config entry
2259 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2261 // Create object instance
2262 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2264 // Yes, then send the whole result to the database layer
2265 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2270 * Outputs a deprecation warning to the developer.
2272 * @param $message The message we shall output to the developer
2274 * @todo Write a logging mechanism for productive mode
2276 public function deprecationWarning ($message) {
2277 // Is developer mode active?
2278 if (defined('DEVELOPER')) {
2279 // Debug instance is there?
2280 if (!is_null($this->getDebugInstance())) {
2281 // Output stub message
2282 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2285 trigger_error($message . "<br />\n");
2289 // @TODO Finish this part!
2290 $this->partialStub('Developer mode inactive. Message:' . $message);
2295 * Checks whether the given PHP extension is loaded
2297 * @param $phpExtension The PHP extension we shall check
2298 * @return $isLoaded Whether the PHP extension is loaded
2300 public final function isPhpExtensionLoaded ($phpExtension) {
2302 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2309 * "Getter" as a time() replacement but with milliseconds. You should use this
2310 * method instead of the encapsulated getimeofday() function.
2312 * @return $milliTime Timestamp with milliseconds
2314 public function getMilliTime () {
2315 // Get the time of day as float
2316 $milliTime = gettimeofday(TRUE);
2323 * Idles (sleeps) for given milliseconds
2325 * @return $hasSlept Whether it goes fine
2327 public function idle ($milliSeconds) {
2328 // Sleep is fine by default
2331 // Idle so long with found function
2332 if (function_exists('time_sleep_until')) {
2333 // Get current time and add idle time
2334 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2336 // New PHP 5.1.0 function found, ignore errors
2337 $hasSlept = @time_sleep_until($sleepUntil);
2340 * My Sun station doesn't have that function even with latest PHP
2343 usleep($milliSeconds * 1000);
2350 * Converts a hexadecimal string, even with negative sign as first string to
2351 * a decimal number using BC functions.
2353 * This work is based on comment #86673 on php.net documentation page at:
2354 * <http://de.php.net/manual/en/function.dechex.php#86673>
2356 * @param $hex Hexadecimal string
2357 * @return $dec Decimal number
2359 protected function hex2dec ($hex) {
2360 // Convert to all lower-case
2361 $hex = strtolower($hex);
2363 // Detect sign (negative/positive numbers)
2365 if (substr($hex, 0, 1) == '-') {
2367 $hex = substr($hex, 1);
2370 // Decode the hexadecimal string into a decimal number
2372 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2373 $factor = self::$hexdec[substr($hex, $i, 1)];
2374 $dec = bcadd($dec, bcmul($factor, $e));
2377 // Return the decimal number
2378 return $sign . $dec;
2382 * Converts even very large decimal numbers, also signed, to a hexadecimal
2385 * This work is based on comment #97756 on php.net documentation page at:
2386 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2388 * @param $dec Decimal number, even with negative sign
2389 * @param $maxLength Optional maximum length of the string
2390 * @return $hex Hexadecimal string
2392 protected function dec2hex ($dec, $maxLength = 0) {
2393 // maxLength can be zero or devideable by 2
2394 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2396 // Detect sign (negative/positive numbers)
2403 // Encode the decimal number into a hexadecimal string
2406 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2408 } while ($dec >= 1);
2411 * Leading zeros are required for hex-decimal "numbers". In some
2412 * situations more leading zeros are wanted, so check for both
2415 if ($maxLength > 0) {
2416 // Prepend more zeros
2417 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2418 } elseif ((strlen($hex) % 2) != 0) {
2419 // Only make string's length dividable by 2
2423 // Return the hexadecimal string
2424 return $sign . $hex;
2428 * Converts a ASCII string (0 to 255) into a decimal number.
2430 * @param $asc The ASCII string to be converted
2431 * @return $dec Decimal number
2433 protected function asc2dec ($asc) {
2434 // Convert it into a hexadecimal number
2435 $hex = bin2hex($asc);
2437 // And back into a decimal number
2438 $dec = $this->hex2dec($hex);
2445 * Converts a decimal number into an ASCII string.
2447 * @param $dec Decimal number
2448 * @return $asc An ASCII string
2450 protected function dec2asc ($dec) {
2451 // First convert the number into a hexadecimal string
2452 $hex = $this->dec2hex($dec);
2454 // Then convert it into the ASCII string
2455 $asc = $this->hex2asc($hex);
2462 * Converts a hexadecimal number into an ASCII string. Negative numbers
2465 * @param $hex Hexadecimal string
2466 * @return $asc An ASCII string
2468 protected function hex2asc ($hex) {
2469 // Check for length, it must be devideable by 2
2470 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2471 assert((strlen($hex) % 2) == 0);
2475 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2476 // Get the decimal number of the chunk
2477 $part = hexdec(substr($hex, $idx, 2));
2479 // Add it to the final string
2483 // Return the final string
2488 * Checks whether the given encoded data was encoded with Base64
2490 * @param $encodedData Encoded data we shall check
2491 * @return $isBase64 Whether the encoded data is Base64
2493 protected function isBase64Encoded ($encodedData) {
2495 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2502 * "Getter" to get response/request type from analysis of the system.
2504 * @return $responseType Analyzed response type
2506 protected static function getResponseTypeFromSystem () {
2507 // Default is console
2508 $responseType = 'console';
2510 // Is 'HTTP_HOST' set?
2511 if (isset($_SERVER['HTTP_HOST'])) {
2513 * Then it is a HTML response/request as RSS and so on may be
2514 * transfered over HTTP as well.
2516 $responseType = 'html';
2520 return $responseType;
2524 * Gets a cache key from Criteria instance
2526 * @param $criteriaInstance An instance of a Criteria class
2527 * @param $onlyKeys Only use these keys for a cache key
2528 * @return $cacheKey A cache key suitable for lookup/storage purposes
2530 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2532 $cacheKey = sprintf('%s@%s',
2533 $this->__toString(),
2534 $criteriaInstance->getCacheKey($onlyKeys)
2538 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2543 * Getter for startup time in miliseconds
2545 * @return $startupTime Startup time in miliseconds
2547 protected function getStartupTime () {
2548 return self::$startupTime;
2552 * "Getter" for a printable currently execution time in nice braces
2554 * @return $executionTime Current execution time in nice braces
2556 protected function getPrintableExecutionTime () {
2557 // Caculate the execution time
2558 $executionTime = microtime(TRUE) - $this->getStartupTime();
2560 // Pack it in nice braces
2561 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2564 return $executionTime;
2568 * Hashes a given string with a simple but stronger hash function (no salt)
2569 * and hex-encode it.
2571 * @param $str The string to be hashed
2572 * @return $hash The hash from string $str
2574 public static final function hash ($str) {
2575 // Hash given string with (better secure) hasher
2576 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2583 * "Getter" for length of hash() output. This will be "cached" to speed up
2586 * @return $length Length of hash() output
2588 public static final function getHashLength () {
2590 if (is_null(self::$hashLength)) {
2591 // No, then hash a string and save its length.
2592 self::$hashLength = strlen(self::hash('abc123'));
2596 return self::$hashLength;
2600 * Checks whether the given number is really a number (only chars 0-9).
2602 * @param $num A string consisting only chars between 0 and 9
2603 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2604 * @param $assertMismatch Whether to assert mismatches
2605 * @return $ret The (hopefully) secured numbered value
2607 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2608 // Filter all numbers out
2609 $ret = preg_replace('/[^0123456789]/', '', $num);
2612 if ($castValue === TRUE) {
2613 // Cast to biggest numeric type
2614 $ret = (double) $ret;
2617 // Assert only if requested
2618 if ($assertMismatch === TRUE) {
2619 // Has the whole value changed?
2620 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2628 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2630 * @param $num A string consisting only chars between 0 and 9
2631 * @param $assertMismatch Whether to assert mismatches
2632 * @return $ret The (hopefully) secured hext-numbered value
2634 public function hexval ($num, $assertMismatch = FALSE) {
2635 // Filter all numbers out
2636 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2638 // Assert only if requested
2639 if ($assertMismatch === TRUE) {
2640 // Has the whole value changed?
2641 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2649 * Checks whether start/end marker are set
2651 * @param $data Data to be checked
2652 * @return $isset Whether start/end marker are set
2654 public final function ifStartEndMarkersSet ($data) {
2656 $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));
2658 // ... and return it
2663 * Determines if an element is set in the generic array
2665 * @param $keyGroup Main group for the key
2666 * @param $subGroup Sub group for the key
2667 * @param $key Key to check
2668 * @param $element Element to check
2669 * @return $isset Whether the given key is set
2671 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2673 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2676 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2682 * Determines if a key is set in the generic array
2684 * @param $keyGroup Main group for the key
2685 * @param $subGroup Sub group for the key
2686 * @param $key Key to check
2687 * @return $isset Whether the given key is set
2689 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2691 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2694 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2702 * Determines if a group is set in the generic array
2704 * @param $keyGroup Main group
2705 * @param $subGroup Sub group
2706 * @return $isset Whether the given group is set
2708 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2710 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2713 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2720 * Getter for sub key group
2722 * @param $keyGroup Main key group
2723 * @param $subGroup Sub key group
2724 * @return $array An array with all array elements
2726 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2728 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2729 // No, then abort here
2730 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2735 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2738 return $this->genericArray[$keyGroup][$subGroup];
2742 * Unsets a given key in generic array
2744 * @param $keyGroup Main group for the key
2745 * @param $subGroup Sub group for the key
2746 * @param $key Key to unset
2749 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2751 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2754 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2758 * Unsets a given element in generic array
2760 * @param $keyGroup Main group for the key
2761 * @param $subGroup Sub group for the key
2762 * @param $key Key to unset
2763 * @param $element Element to unset
2766 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2768 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2771 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2775 * Append a string to a given generic array key
2777 * @param $keyGroup Main group for the key
2778 * @param $subGroup Sub group for the key
2779 * @param $key Key to unset
2780 * @param $value Value to add/append
2783 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2785 //* 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);
2787 // Is it already there?
2788 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2790 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2793 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2798 * Append a string to a given generic array element
2800 * @param $keyGroup Main group for the key
2801 * @param $subGroup Sub group for the key
2802 * @param $key Key to unset
2803 * @param $element Element to check
2804 * @param $value Value to add/append
2807 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2809 //* 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);
2811 // Is it already there?
2812 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2814 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2817 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2822 * Sets a string in a given generic array element
2824 * @param $keyGroup Main group for the key
2825 * @param $subGroup Sub group for the key
2826 * @param $key Key to unset
2827 * @param $element Element to check
2828 * @param $value Value to add/append
2831 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2833 //* 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);
2836 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2840 * Initializes given generic array group
2842 * @param $keyGroup Main group for the key
2843 * @param $subGroup Sub group for the key
2844 * @param $key Key to use
2845 * @param $forceInit Optionally force initialization
2848 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2850 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2852 // Is it already set?
2853 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2854 // Already initialized
2855 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2860 $this->genericArray[$keyGroup][$subGroup] = array();
2864 * Initializes given generic array key
2866 * @param $keyGroup Main group for the key
2867 * @param $subGroup Sub group for the key
2868 * @param $key Key to use
2869 * @param $forceInit Optionally force initialization
2872 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2874 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2876 // Is it already set?
2877 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2878 // Already initialized
2879 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2884 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2888 * Initializes given generic array element
2890 * @param $keyGroup Main group for the key
2891 * @param $subGroup Sub group for the key
2892 * @param $key Key to use
2893 * @param $element Element to use
2894 * @param $forceInit Optionally force initialization
2897 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2899 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2901 // Is it already set?
2902 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2903 // Already initialized
2904 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2909 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2913 * Pushes an element to a generic key
2915 * @param $keyGroup Main group for the key
2916 * @param $subGroup Sub group for the key
2917 * @param $key Key to use
2918 * @param $value Value to add/append
2919 * @return $count Number of array elements
2921 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2923 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2926 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2928 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2932 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2935 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2936 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2941 * Pushes an element to a generic array element
2943 * @param $keyGroup Main group for the key
2944 * @param $subGroup Sub group for the key
2945 * @param $key Key to use
2946 * @param $element Element to check
2947 * @param $value Value to add/append
2948 * @return $count Number of array elements
2950 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2952 //* 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));
2955 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2957 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2961 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2964 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2965 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2970 * Pops an element from a generic group
2972 * @param $keyGroup Main group for the key
2973 * @param $subGroup Sub group for the key
2974 * @param $key Key to unset
2975 * @return $value Last "popped" value
2977 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2979 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2982 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2984 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2989 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2992 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2993 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
2998 * Shifts an element from a generic group
3000 * @param $keyGroup Main group for the key
3001 * @param $subGroup Sub group for the key
3002 * @param $key Key to unset
3003 * @return $value Last "popped" value
3005 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3007 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3010 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3012 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3017 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3020 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3021 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3026 * Count generic array group
3028 * @param $keyGroup Main group for the key
3029 * @return $count Count of given group
3031 protected final function countGenericArray ($keyGroup) {
3033 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3036 if (!isset($this->genericArray[$keyGroup])) {
3038 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3043 $count = count($this->genericArray[$keyGroup]);
3046 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3053 * Count generic array sub group
3055 * @param $keyGroup Main group for the key
3056 * @param $subGroup Sub group for the key
3057 * @return $count Count of given group
3059 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3061 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3064 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3066 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3071 $count = count($this->genericArray[$keyGroup][$subGroup]);
3074 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3081 * Count generic array elements
3083 * @param $keyGroup Main group for the key
3084 * @param $subGroup Sub group for the key
3085 * @para $key Key to count
3086 * @return $count Count of given key
3088 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3090 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3093 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3095 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3097 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3099 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3104 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3107 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3114 * Getter for whole generic group array
3116 * @param $keyGroup Key group to get
3117 * @return $array Whole generic array group
3119 protected final function getGenericArray ($keyGroup) {
3121 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3124 if (!isset($this->genericArray[$keyGroup])) {
3126 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3131 return $this->genericArray[$keyGroup];
3135 * Setter for generic array key
3137 * @param $keyGroup Key group to get
3138 * @param $subGroup Sub group for the key
3139 * @param $key Key to unset
3140 * @param $value Mixed value from generic array element
3143 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3145 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3148 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3152 * Getter for generic array key
3154 * @param $keyGroup Key group to get
3155 * @param $subGroup Sub group for the key
3156 * @param $key Key to unset
3157 * @return $value Mixed value from generic array element
3159 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3161 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3164 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3166 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3171 return $this->genericArray[$keyGroup][$subGroup][$key];
3175 * Sets a value in given generic array key/element
3177 * @param $keyGroup Main group for the key
3178 * @param $subGroup Sub group for the key
3179 * @param $key Key to set
3180 * @param $element Element to set
3181 * @param $value Value to set
3184 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3186 //* 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));
3189 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3193 * Getter for generic array element
3195 * @param $keyGroup Key group to get
3196 * @param $subGroup Sub group for the key
3197 * @param $key Key to look for
3198 * @param $element Element to look for
3199 * @return $value Mixed value from generic array element
3201 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3203 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3206 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3208 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3213 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3217 * Checks if a given sub group is valid (array)
3219 * @param $keyGroup Key group to get
3220 * @param $subGroup Sub group for the key
3221 * @return $isValid Whether given sub group is valid
3223 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3225 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3228 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3235 * Checks if a given key is valid (array)
3237 * @param $keyGroup Key group to get
3238 * @param $subGroup Sub group for the key
3239 * @param $key Key to check
3240 * @return $isValid Whether given sub group is valid
3242 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3244 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3247 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3254 * Initializes the web output instance
3258 protected function initWebOutputInstance () {
3259 // Get application instance
3260 $applicationInstance = Registry::getRegistry()->getInstance('app');
3262 // Is this a response instance?
3263 if ($this instanceof Responseable) {
3264 // Then set it in application instance
3265 $applicationInstance->setResponseInstance($this);
3268 // Init web output instance
3269 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3272 $this->setWebOutputInstance($outputInstance);
3276 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3278 * @param $boolean Boolean value
3279 * @return $translated Translated boolean value
3281 public static final function translateBooleanToYesNo ($boolean) {
3282 // Make sure it is really boolean
3283 assert(is_bool($boolean));
3286 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3288 // ... and return it
3293 * Encodes raw data (almost any type) by "serializing" it and then pack it
3294 * into a "binary format".
3296 * @param $rawData Raw data (almost any type)
3297 * @return $encoded Encoded data
3299 protected function encodeData ($rawData) {
3300 // Make sure no objects or resources pass through
3301 assert(!is_object($rawData));
3302 assert(!is_resource($rawData));
3304 // First "serialize" it (json_encode() is faster than serialize())
3305 $encoded = $this->packString(json_encode($rawData));
3312 * Pack a string into a "binary format". Please execuse me that this is
3313 * widely undocumented. :-(
3315 * @param $str Unpacked string
3316 * @return $packed Packed string
3317 * @todo Improve documentation
3319 protected function packString ($str) {
3321 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3323 // First compress the string (gzcompress is okay)
3324 $str = gzcompress($str);
3329 // And start the "encoding" loop
3330 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3332 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3333 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3335 if (($idx + $i) <= strlen($str)) {
3336 $ord = ord(substr($str, ($idx + $i), 1));
3338 $add = $ord * pow(256, $factor);
3342 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3346 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3347 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3349 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3350 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3356 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3361 * Checks whether the given file/path is in open_basedir(). This does not
3362 * gurantee that the file is actually readable and/or writeable. If you need
3363 * such gurantee then please use isReadableFile() instead.
3365 * @param $filePathName Name of the file/path to be checked
3366 * @return $isReachable Whether it is within open_basedir()
3368 protected static function isReachableFilePath ($filePathName) {
3369 // Is not reachable by default
3370 $isReachable = FALSE;
3372 // Get open_basedir parameter
3373 $openBaseDir = ini_get('open_basedir');
3376 if (!empty($openBaseDir)) {
3377 // Check all entries
3378 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3379 // Check on existence
3380 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3382 $isReachable = TRUE;
3386 // If open_basedir is not set, all is allowed
3387 $isReachable = TRUE;
3391 return $isReachable;
3395 * Checks whether the give file is within open_basedir() (done by
3396 * isReachableFilePath()), is actually a file and is readable.
3398 * @param $fileName Name of the file to be checked
3399 * @return $isReadable Whether the file is readable (and therefor exists)
3401 public static function isReadableFile ($fileName) {
3402 // Default is not readable
3403 $isReadable = FALSE;
3405 // Is within parameters, so check if it is a file and readable
3406 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3413 * Creates a full-qualified file name (FQFN) for given file name by adding
3414 * a configured temporary file path to it.
3416 * @param $fileName Name for temporary file
3417 * @return $fqfn Full-qualified file name
3418 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3419 * @throws FileIoException If the file cannot be written
3421 protected static function createTempPathForFile ($fileName) {
3423 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3425 // Is the path writeable?
3426 if (!is_writable($basePath)) {
3427 // Path is write-protected
3428 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3432 $fqfn = $basePath . '/' . $fileName;
3435 if (!self::isReachableFilePath($fqfn)) {
3437 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3445 * "Getter" for a printable state name
3447 * @return $stateName Name of the node's state in a printable format
3449 public final function getPrintableState () {
3450 // Default is 'null'
3451 $stateName = 'null';
3453 // Get the state instance
3454 $stateInstance = $this->getStateInstance();
3456 // Is it an instance of Stateable?
3457 if ($stateInstance instanceof Stateable) {
3458 // Then use that state name
3459 $stateName = $stateInstance->getStateName();
3467 * Handles socket error for given socket resource and peer data. This method
3468 * validates $socketResource if it is a valid resource (see is_resource())
3469 * but assumes valid data in array $recipientData, except that
3470 * count($recipientData) is always 2.
3472 * @param $method Value of __METHOD__ from calling method
3473 * @param $line Value of __LINE__ from calling method
3474 * @param $socketResource A valid socket resource
3475 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3477 * @throws InvalidSocketException If $socketResource is no socket resource
3478 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3479 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3481 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3482 // This method handles only socket resources
3483 if (!is_resource($socketResource)) {
3484 // No resource, abort here
3485 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3488 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3489 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3490 assert(isset($socketData[0]));
3491 assert(isset($socketData[1]));
3493 // Get error code for first validation (0 is not an error)
3494 $errorCode = socket_last_error($socketResource);
3496 // If the error code is zero, someone called this method without an error
3497 if ($errorCode == 0) {
3498 // No error detected (or previously cleared outside this method)
3499 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3502 // Get handler (method) name
3503 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3505 // Call-back the error handler method
3506 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3508 // Finally clear the error because it has been handled
3509 socket_clear_error($socketResource);