3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Configuration\FrameworkConfiguration;
7 use CoreFramework\Controller\Controller;
8 use CoreFramework\Criteria\Criteria;
9 use CoreFramework\Criteria\Local\LocalSearchCriteria;
10 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
11 use CoreFramework\Factory\ObjectFactory;
12 use CoreFramework\Filesystem\FrameworkDirectory;
13 use CoreFramework\Generic\FrameworkInterface;
14 use CoreFramework\Generic\NullPointerException;
15 use CoreFramework\Handler\Stream\IoHandler;
16 use CoreFramework\Loader\ClassLoader;
17 use CoreFramework\Manager\ManageableApplication;
18 use CoreFramework\Middleware\Compressor\CompressorChannel;
19 use CoreFramework\Middleware\Debug\DebugMiddleware;
20 use CoreFramework\Registry\Register;
21 use CoreFramework\Registry\Registry;
22 use CoreFramework\Request\Requestable;
23 use CoreFramework\Resolver\Resolver;
24 use CoreFramework\Response\Responseable;
25 use CoreFramework\Stream\Output\OutputStreamer;
26 use CoreFramework\Template\CompileableTemplate;
32 * The simulator system class is the super class of all other classes. This
33 * class handles saving of games etc.
35 * @author Roland Haeder <webmaster@shipsimu.org>
37 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
38 * @license GNU GPL 3.0 or any newer version
39 * @link http://www.shipsimu.org
41 * This program is free software: you can redistribute it and/or modify
42 * it under the terms of the GNU General Public License as published by
43 * the Free Software Foundation, either version 3 of the License, or
44 * (at your option) any later version.
46 * This program is distributed in the hope that it will be useful,
47 * but WITHOUT ANY WARRANTY; without even the implied warranty of
48 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
49 * GNU General Public License for more details.
51 * You should have received a copy of the GNU General Public License
52 * along with this program. If not, see <http://www.gnu.org/licenses/>.
54 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
56 * Length of output from hash()
58 private static $hashLength = NULL;
63 private $realClass = 'BaseFrameworkSystem';
66 * Instance of a Requestable class
68 private $requestInstance = NULL;
71 * Instance of a Responseable class
73 private $responseInstance = NULL;
76 * Search criteria instance
78 private $searchInstance = NULL;
81 * Update criteria instance
83 private $updateInstance = NULL;
86 * The file I/O instance for the template loader
88 private $fileIoInstance = NULL;
93 private $resolverInstance = NULL;
96 * Template engine instance
98 private $templateInstance = NULL;
101 * Database result instance
103 private $resultInstance = NULL;
106 * Instance for user class
108 private $userInstance = NULL;
111 * A controller instance
113 private $controllerInstance = NULL;
118 private $rngInstance = NULL;
121 * Instance of a crypto helper
123 private $cryptoInstance = NULL;
126 * Instance of an Iterator class
128 private $iteratorInstance = NULL;
131 * Instance of the list
133 private $listInstance = NULL;
138 private $menuInstance = NULL;
141 * Instance of the image
143 private $imageInstance = NULL;
146 * Instance of the stacker
148 private $stackInstance = NULL;
151 * A Compressor instance
153 private $compressorInstance = NULL;
156 * A Parseable instance
158 private $parserInstance = NULL;
161 * A HandleableProtocol instance
163 private $protocolInstance = NULL;
166 * A database wrapper instance
168 private $databaseInstance = NULL;
171 * A helper instance for the form
173 private $helperInstance = NULL;
176 * An instance of a Source class
178 private $sourceInstance = NULL;
181 * An instance of a UrlSource class
183 private $urlSourceInstance = NULL;
186 * An instance of a InputStream class
188 private $inputStreamInstance = NULL;
191 * An instance of a OutputStream class
193 private $outputStreamInstance = NULL;
196 * Networkable handler instance
198 private $handlerInstance = NULL;
201 * Visitor handler instance
203 private $visitorInstance = NULL;
208 private $dhtInstance = NULL;
211 * An instance of a database wrapper class
213 private $wrapperInstance = NULL;
216 * An instance of a file I/O pointer class (not handler)
218 private $pointerInstance = NULL;
221 * An instance of an Indexable class
223 private $indexInstance = NULL;
226 * An instance of a Block class
228 private $blockInstance = NULL;
233 private $minableInstance = NULL;
236 * A FrameworkDirectory instance
238 private $directoryInstance = NULL;
243 private $listenerInstance = NULL;
246 * An instance of a communicator
248 private $communicatorInstance = NULL;
251 * The concrete output instance
253 private $outputInstance = NULL;
258 private $stateInstance = NULL;
261 * Thousands separator
263 private $thousands = '.'; // German
268 private $decimals = ','; // German
273 private $socketResource = FALSE;
276 * Regular expression to use for validation
278 private $regularExpression = '';
283 private $packageData = array();
288 private $genericArray = array();
293 private $commandName = '';
298 private $controllerName = '';
301 * Name of used protocol
303 private $protocolName = 'invalid';
306 * Array with bitmasks and such for pack/unpack methods to support both
307 * 32-bit and 64-bit systems
309 private $packingData = array(
312 'left' => 0xffff0000,
313 'right' => 0x0000ffff,
319 'left' => 0xffffffff00000000,
320 'right' => 0x00000000ffffffff,
327 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
329 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
331 private $archArrayElement = FALSE;
333 /***********************
334 * Exception codes.... *
335 ***********************/
337 // @todo Try to clean these constants up
338 const EXCEPTION_IS_NULL_POINTER = 0x001;
339 const EXCEPTION_IS_NO_OBJECT = 0x002;
340 const EXCEPTION_IS_NO_ARRAY = 0x003;
341 const EXCEPTION_MISSING_METHOD = 0x004;
342 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
343 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
344 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
345 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
346 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
347 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
348 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
349 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
350 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
351 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
352 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
353 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
354 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
355 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
356 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
357 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
358 const EXCEPTION_PATH_NOT_FOUND = 0x015;
359 const EXCEPTION_INVALID_PATH_NAME = 0x016;
360 const EXCEPTION_READ_PROTECED_PATH = 0x017;
361 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
362 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
363 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
364 const EXCEPTION_INVALID_RESOURCE = 0x01b;
365 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
366 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
367 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
368 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
369 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
370 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
371 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
372 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
373 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
374 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
375 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
376 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
377 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
378 const EXCEPTION_INVALID_STRING = 0x029;
379 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
380 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
381 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
382 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
383 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
384 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
385 const EXCEPTION_MISSING_ELEMENT = 0x030;
386 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
387 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
388 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
389 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
390 const EXCEPTION_FATAL_ERROR = 0x035;
391 const EXCEPTION_FILE_NOT_FOUND = 0x036;
392 const EXCEPTION_ASSERTION_FAILED = 0x037;
393 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
394 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
395 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
396 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
397 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
398 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
401 * Hexadecimal->Decimal translation array
403 private static $hexdec = array(
423 * Decimal->hexadecimal translation array
425 private static $dechex = array(
445 * Startup time in miliseconds
447 private static $startupTime = 0;
450 * Protected super constructor
452 * @param $className Name of the class
455 protected function __construct ($className) {
457 $this->setRealClass($className);
459 // Set configuration instance if no registry ...
460 if (!$this instanceof Register) {
461 // ... because registries doesn't need to be configured
462 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
465 // Is the startup time set? (0 cannot be TRUE anymore)
466 if (self::$startupTime == 0) {
468 self::$startupTime = microtime(TRUE);
472 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
476 * Destructor for all classes. You should not call this method on your own.
480 public function __destruct () {
481 // Flush any updated entries to the database
482 $this->flushPendingUpdates();
484 // Is this object already destroyed?
485 if ($this->__toString() != 'DestructedObject') {
486 // Destroy all informations about this class but keep some text about it alive
487 $this->setRealClass('DestructedObject');
488 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
489 // Already destructed object
490 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
495 // Do not call this twice
496 trigger_error(__METHOD__ . ': Called twice.');
502 * The __call() method where all non-implemented methods end up
504 * @param $methodName Name of the missing method
505 * @args $args Arguments passed to the method
508 public final function __call ($methodName, $args) {
509 return self::__callStatic($methodName, $args);
513 * The __callStatic() method where all non-implemented static methods end up
515 * @param $methodName Name of the missing method
516 * @args $args Arguments passed to the method
519 public static final function __callStatic ($methodName, $args) {
521 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
523 // Init argument string
526 // Is it NULL, empty or an array?
527 if (is_null($args)) {
529 $argsString = 'NULL';
530 } elseif (is_array($args)) {
534 // Some arguments are there
535 foreach ($args as $arg) {
536 // Add data about the argument
537 $argsString .= gettype($arg) . ':';
540 // Found a NULL argument
541 $argsString .= 'NULL';
542 } elseif (is_string($arg)) {
543 // Add length for strings
544 $argsString .= strlen($arg);
545 } elseif ((is_int($arg)) || (is_float($arg))) {
548 } elseif (is_array($arg)) {
549 // .. or size if array
550 $argsString .= count($arg);
551 } elseif (is_object($arg)) {
553 $reflection = new ReflectionClass($arg);
555 // Is an other object, maybe no __toString() available
556 $argsString .= $reflection->getName();
557 } elseif ($arg === TRUE) {
558 // ... is boolean 'TRUE'
559 $argsString .= 'TRUE';
560 } elseif ($arg === FALSE) {
561 // ... is boolean 'FALSE'
562 $argsString .= 'FALSE';
565 // Comma for next one
570 if (substr($argsString, -2, 1) == ',') {
571 $argsString = substr($argsString, 0, -2);
577 // Invalid arguments!
578 $argsString = '!INVALID:' . gettype($args) . '!';
581 // Output stub message
582 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
583 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
593 * Getter for $realClass
595 * @return $realClass The name of the real class (not BaseFrameworkSystem)
597 public function __toString () {
598 return $this->realClass;
602 * Magic method to catch setting of missing but set class fields/attributes
604 * @param $name Name of the field/attribute
605 * @param $value Value to store
608 public final function __set ($name, $value) {
609 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
612 print_r($value, TRUE)
617 * Magic method to catch getting of missing fields/attributes
619 * @param $name Name of the field/attribute
622 public final function __get ($name) {
623 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
629 * Magic method to catch unsetting of missing fields/attributes
631 * @param $name Name of the field/attribute
634 public final function __unset ($name) {
635 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
641 * Magic method to catch object serialization
643 * @return $unsupported Unsupported method
644 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
646 public final function __sleep () {
647 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
651 * Magic method to catch object deserialization
653 * @return $unsupported Unsupported method
654 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
656 public final function __wakeup () {
657 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
661 * Magic method to catch calls when an object instance is called
663 * @return $unsupported Unsupported method
664 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
666 public final function __invoke () {
667 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
671 * Setter for the real class name
673 * @param $realClass Class name (string)
676 public final function setRealClass ($realClass) {
678 $this->realClass = (string) $realClass;
682 * Setter for database result instance
684 * @param $resultInstance An instance of a database result class
686 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
688 protected final function setResultInstance (SearchableResult $resultInstance) {
689 $this->resultInstance = $resultInstance;
693 * Getter for database result instance
695 * @return $resultInstance An instance of a database result class
697 public final function getResultInstance () {
698 return $this->resultInstance;
702 * Setter for template engine instances
704 * @param $templateInstance An instance of a template engine class
707 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
708 $this->templateInstance = $templateInstance;
712 * Getter for template engine instances
714 * @return $templateInstance An instance of a template engine class
716 protected final function getTemplateInstance () {
717 return $this->templateInstance;
721 * Setter for search instance
723 * @param $searchInstance Searchable criteria instance
726 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
727 $this->searchInstance = $searchInstance;
731 * Getter for search instance
733 * @return $searchInstance Searchable criteria instance
735 public final function getSearchInstance () {
736 return $this->searchInstance;
740 * Setter for update instance
742 * @param $updateInstance Searchable criteria instance
745 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
746 $this->updateInstance = $updateInstance;
750 * Getter for update instance
752 * @return $updateInstance Updateable criteria instance
754 public final function getUpdateInstance () {
755 return $this->updateInstance;
759 * Setter for resolver instance
761 * @param $resolverInstance Instance of a command resolver class
764 public final function setResolverInstance (Resolver $resolverInstance) {
765 $this->resolverInstance = $resolverInstance;
769 * Getter for resolver instance
771 * @return $resolverInstance Instance of a command resolver class
773 public final function getResolverInstance () {
774 return $this->resolverInstance;
778 * Setter for language instance
780 * @param $configInstance The configuration instance which shall
781 * be FrameworkConfiguration
784 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
785 Registry::getRegistry()->addInstance('config', $configInstance);
789 * Getter for configuration instance
791 * @return $configInstance Configuration instance
793 public final function getConfigInstance () {
794 $configInstance = Registry::getRegistry()->getInstance('config');
795 return $configInstance;
799 * Setter for debug instance
801 * @param $debugInstance The instance for debug output class
804 public final function setDebugInstance (DebugMiddleware $debugInstance) {
805 Registry::getRegistry()->addInstance('debug', $debugInstance);
809 * Getter for debug instance
811 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
813 public final function getDebugInstance () {
814 // Get debug instance
815 $debugInstance = Registry::getRegistry()->getInstance('debug');
818 return $debugInstance;
822 * Setter for web output instance
824 * @param $webInstance The instance for web output class
827 public final function setWebOutputInstance (OutputStreamer $webInstance) {
828 Registry::getRegistry()->addInstance('web_output', $webInstance);
832 * Getter for web output instance
834 * @return $webOutputInstance - Instance to class WebOutput
836 public final function getWebOutputInstance () {
837 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
838 return $webOutputInstance;
842 * Setter for database instance
844 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
847 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
848 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
852 * Getter for database layer
854 * @return $databaseInstance The database layer instance
856 public final function getDatabaseInstance () {
858 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
861 return $databaseInstance;
865 * Setter for compressor channel
867 * @param $compressorInstance An instance of CompressorChannel
870 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
871 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
875 * Getter for compressor channel
877 * @return $compressorInstance The compressor channel
879 public final function getCompressorChannel () {
880 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
881 return $compressorInstance;
885 * Protected getter for a manageable application helper class
887 * @return $applicationInstance An instance of a manageable application helper class
889 protected final function getApplicationInstance () {
890 $applicationInstance = Registry::getRegistry()->getInstance('application');
891 return $applicationInstance;
895 * Setter for a manageable application helper class
897 * @param $applicationInstance An instance of a manageable application helper class
900 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
901 Registry::getRegistry()->addInstance('application', $applicationInstance);
905 * Setter for request instance
907 * @param $requestInstance An instance of a Requestable class
910 public final function setRequestInstance (Requestable $requestInstance) {
911 $this->requestInstance = $requestInstance;
915 * Getter for request instance
917 * @return $requestInstance An instance of a Requestable class
919 public final function getRequestInstance () {
920 return $this->requestInstance;
924 * Setter for response instance
926 * @param $responseInstance An instance of a Responseable class
929 public final function setResponseInstance (Responseable $responseInstance) {
930 $this->responseInstance = $responseInstance;
934 * Getter for response instance
936 * @return $responseInstance An instance of a Responseable class
938 public final function getResponseInstance () {
939 return $this->responseInstance;
943 * Private getter for language instance
945 * @return $langInstance An instance to the language sub-system
947 protected final function getLanguageInstance () {
948 $langInstance = Registry::getRegistry()->getInstance('language');
949 return $langInstance;
953 * Setter for language instance
955 * @param $langInstance An instance to the language sub-system
957 * @see LanguageSystem
959 public final function setLanguageInstance (ManageableLanguage $langInstance) {
960 Registry::getRegistry()->addInstance('language', $langInstance);
964 * Private getter for file IO instance
966 * @return $fileIoInstance An instance to the file I/O sub-system
968 protected final function getFileIoInstance () {
969 return $this->fileIoInstance;
973 * Setter for file I/O instance
975 * @param $fileIoInstance An instance to the file I/O sub-system
978 public final function setFileIoInstance (IoHandler $fileIoInstance) {
979 $this->fileIoInstance = $fileIoInstance;
983 * Protected setter for user instance
985 * @param $userInstance An instance of a user class
988 protected final function setUserInstance (ManageableAccount $userInstance) {
989 $this->userInstance = $userInstance;
993 * Getter for user instance
995 * @return $userInstance An instance of a user class
997 public final function getUserInstance () {
998 return $this->userInstance;
1002 * Setter for controller instance (this surely breaks a bit the MVC patterm)
1004 * @param $controllerInstance An instance of the controller
1007 public final function setControllerInstance (Controller $controllerInstance) {
1008 $this->controllerInstance = $controllerInstance;
1012 * Getter for controller instance (this surely breaks a bit the MVC patterm)
1014 * @return $controllerInstance An instance of the controller
1016 public final function getControllerInstance () {
1017 return $this->controllerInstance;
1021 * Setter for RNG instance
1023 * @param $rngInstance An instance of a random number generator (RNG)
1026 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1027 $this->rngInstance = $rngInstance;
1031 * Getter for RNG instance
1033 * @return $rngInstance An instance of a random number generator (RNG)
1035 public final function getRngInstance () {
1036 return $this->rngInstance;
1040 * Setter for Cryptable instance
1042 * @param $cryptoInstance An instance of a Cryptable class
1045 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1046 $this->cryptoInstance = $cryptoInstance;
1050 * Getter for Cryptable instance
1052 * @return $cryptoInstance An instance of a Cryptable class
1054 public final function getCryptoInstance () {
1055 return $this->cryptoInstance;
1059 * Setter for the list instance
1061 * @param $listInstance A list of Listable
1064 protected final function setListInstance (Listable $listInstance) {
1065 $this->listInstance = $listInstance;
1069 * Getter for the list instance
1071 * @return $listInstance A list of Listable
1073 protected final function getListInstance () {
1074 return $this->listInstance;
1078 * Setter for the menu instance
1080 * @param $menuInstance A RenderableMenu instance
1083 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1084 $this->menuInstance = $menuInstance;
1088 * Getter for the menu instance
1090 * @return $menuInstance A RenderableMenu instance
1092 protected final function getMenuInstance () {
1093 return $this->menuInstance;
1097 * Setter for image instance
1099 * @param $imageInstance An instance of an image
1102 public final function setImageInstance (BaseImage $imageInstance) {
1103 $this->imageInstance = $imageInstance;
1107 * Getter for image instance
1109 * @return $imageInstance An instance of an image
1111 public final function getImageInstance () {
1112 return $this->imageInstance;
1116 * Setter for stacker instance
1118 * @param $stackInstance An instance of an stacker
1121 public final function setStackInstance (Stackable $stackInstance) {
1122 $this->stackInstance = $stackInstance;
1126 * Getter for stacker instance
1128 * @return $stackInstance An instance of an stacker
1130 public final function getStackInstance () {
1131 return $this->stackInstance;
1135 * Setter for compressor instance
1137 * @param $compressorInstance An instance of an compressor
1140 public final function setCompressorInstance (Compressor $compressorInstance) {
1141 $this->compressorInstance = $compressorInstance;
1145 * Getter for compressor instance
1147 * @return $compressorInstance An instance of an compressor
1149 public final function getCompressorInstance () {
1150 return $this->compressorInstance;
1154 * Setter for Parseable instance
1156 * @param $parserInstance An instance of an Parseable
1159 public final function setParserInstance (Parseable $parserInstance) {
1160 $this->parserInstance = $parserInstance;
1164 * Getter for Parseable instance
1166 * @return $parserInstance An instance of an Parseable
1168 public final function getParserInstance () {
1169 return $this->parserInstance;
1173 * Setter for HandleableProtocol instance
1175 * @param $protocolInstance An instance of an HandleableProtocol
1178 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1179 $this->protocolInstance = $protocolInstance;
1183 * Getter for HandleableProtocol instance
1185 * @return $protocolInstance An instance of an HandleableProtocol
1187 public final function getProtocolInstance () {
1188 return $this->protocolInstance;
1192 * Setter for DatabaseWrapper instance
1194 * @param $wrapperInstance An instance of an DatabaseWrapper
1197 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1198 $this->wrapperInstance = $wrapperInstance;
1202 * Getter for DatabaseWrapper instance
1204 * @return $wrapperInstance An instance of an DatabaseWrapper
1206 public final function getWrapperInstance () {
1207 return $this->wrapperInstance;
1211 * Setter for socket resource
1213 * @param $socketResource A valid socket resource
1216 public final function setSocketResource ($socketResource) {
1217 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1218 $this->socketResource = $socketResource;
1222 * Getter for socket resource
1224 * @return $socketResource A valid socket resource
1226 public final function getSocketResource () {
1227 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1228 return $this->socketResource;
1232 * Setter for regular expression
1234 * @param $regularExpression A valid regular expression
1237 public final function setRegularExpression ($regularExpression) {
1238 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1239 $this->regularExpression = $regularExpression;
1243 * Getter for regular expression
1245 * @return $regularExpression A valid regular expression
1247 public final function getRegularExpression () {
1248 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1249 return $this->regularExpression;
1253 * Setter for helper instance
1255 * @param $helperInstance An instance of a helper class
1258 protected final function setHelperInstance (Helper $helperInstance) {
1259 $this->helperInstance = $helperInstance;
1263 * Getter for helper instance
1265 * @return $helperInstance An instance of a helper class
1267 public final function getHelperInstance () {
1268 return $this->helperInstance;
1272 * Setter for a Source instance
1274 * @param $sourceInstance An instance of a Source class
1277 protected final function setSourceInstance (Source $sourceInstance) {
1278 $this->sourceInstance = $sourceInstance;
1282 * Getter for a Source instance
1284 * @return $sourceInstance An instance of a Source class
1286 protected final function getSourceInstance () {
1287 return $this->sourceInstance;
1291 * Setter for a UrlSource instance
1293 * @param $sourceInstance An instance of a UrlSource class
1296 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1297 $this->urlSourceInstance = $urlSourceInstance;
1301 * Getter for a UrlSource instance
1303 * @return $urlSourceInstance An instance of a UrlSource class
1305 protected final function getUrlSourceInstance () {
1306 return $this->urlSourceInstance;
1310 * Getter for a InputStream instance
1312 * @param $inputStreamInstance The InputStream instance
1314 protected final function getInputStreamInstance () {
1315 return $this->inputStreamInstance;
1319 * Setter for a InputStream instance
1321 * @param $inputStreamInstance The InputStream instance
1324 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1325 $this->inputStreamInstance = $inputStreamInstance;
1329 * Getter for a OutputStream instance
1331 * @param $outputStreamInstance The OutputStream instance
1333 protected final function getOutputStreamInstance () {
1334 return $this->outputStreamInstance;
1338 * Setter for a OutputStream instance
1340 * @param $outputStreamInstance The OutputStream instance
1343 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1344 $this->outputStreamInstance = $outputStreamInstance;
1348 * Setter for handler instance
1350 * @param $handlerInstance An instance of a Handleable class
1353 protected final function setHandlerInstance (Handleable $handlerInstance) {
1354 $this->handlerInstance = $handlerInstance;
1358 * Getter for handler instance
1360 * @return $handlerInstance A Networkable instance
1362 protected final function getHandlerInstance () {
1363 return $this->handlerInstance;
1367 * Setter for visitor instance
1369 * @param $visitorInstance A Visitor instance
1372 protected final function setVisitorInstance (Visitor $visitorInstance) {
1373 $this->visitorInstance = $visitorInstance;
1377 * Getter for visitor instance
1379 * @return $visitorInstance A Visitor instance
1381 protected final function getVisitorInstance () {
1382 return $this->visitorInstance;
1386 * Setter for DHT instance
1388 * @param $dhtInstance A Distributable instance
1391 protected final function setDhtInstance (Distributable $dhtInstance) {
1392 $this->dhtInstance = $dhtInstance;
1396 * Getter for DHT instance
1398 * @return $dhtInstance A Distributable instance
1400 protected final function getDhtInstance () {
1401 return $this->dhtInstance;
1405 * Setter for raw package Data
1407 * @param $packageData Raw package Data
1410 public final function setPackageData (array $packageData) {
1411 $this->packageData = $packageData;
1415 * Getter for raw package Data
1417 * @return $packageData Raw package Data
1419 public function getPackageData () {
1420 return $this->packageData;
1425 * Setter for Iterator instance
1427 * @param $iteratorInstance An instance of an Iterator
1430 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1431 $this->iteratorInstance = $iteratorInstance;
1435 * Getter for Iterator instance
1437 * @return $iteratorInstance An instance of an Iterator
1439 public final function getIteratorInstance () {
1440 return $this->iteratorInstance;
1444 * Setter for FilePointer instance
1446 * @param $pointerInstance An instance of an FilePointer class
1449 protected final function setPointerInstance (FilePointer $pointerInstance) {
1450 $this->pointerInstance = $pointerInstance;
1454 * Getter for FilePointer instance
1456 * @return $pointerInstance An instance of an FilePointer class
1458 public final function getPointerInstance () {
1459 return $this->pointerInstance;
1463 * Unsets pointer instance which triggers a call of __destruct() if the
1464 * instance is still there. This is surely not fatal on already "closed"
1465 * file pointer instances.
1467 * I don't want to mess around with above setter by giving it a default
1468 * value NULL as setter should always explicitly only set (existing) object
1469 * instances and NULL is NULL.
1473 protected final function unsetPointerInstance () {
1474 // Simply it to NULL
1475 $this->pointerInstance = NULL;
1479 * Setter for Indexable instance
1481 * @param $indexInstance An instance of an Indexable class
1484 protected final function setIndexInstance (Indexable $indexInstance) {
1485 $this->indexInstance = $indexInstance;
1489 * Getter for Indexable instance
1491 * @return $indexInstance An instance of an Indexable class
1493 public final function getIndexInstance () {
1494 return $this->indexInstance;
1498 * Setter for Block instance
1500 * @param $blockInstance An instance of an Block class
1503 protected final function setBlockInstance (Block $blockInstance) {
1504 $this->blockInstance = $blockInstance;
1508 * Getter for Block instance
1510 * @return $blockInstance An instance of an Block class
1512 public final function getBlockInstance () {
1513 return $this->blockInstance;
1517 * Setter for Minable instance
1519 * @param $minableInstance A Minable instance
1522 protected final function setMinableInstance (Minable $minableInstance) {
1523 $this->minableInstance = $minableInstance;
1527 * Getter for minable instance
1529 * @return $minableInstance A Minable instance
1531 protected final function getMinableInstance () {
1532 return $this->minableInstance;
1536 * Setter for FrameworkDirectory instance
1538 * @param $directoryInstance A FrameworkDirectory instance
1541 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1542 $this->directoryInstance = $directoryInstance;
1546 * Getter for FrameworkDirectory instance
1548 * @return $directoryInstance A FrameworkDirectory instance
1550 protected final function getDirectoryInstance () {
1551 return $this->directoryInstance;
1555 * Setter for listener instance
1557 * @param $listenerInstance A Listenable instance
1560 protected final function setListenerInstance (Listenable $listenerInstance) {
1561 $this->listenerInstance = $listenerInstance;
1565 * Getter for listener instance
1567 * @return $listenerInstance A Listenable instance
1569 protected final function getListenerInstance () {
1570 return $this->listenerInstance;
1574 * Getter for communicator instance
1576 * @return $communicatorInstance An instance of a Communicator class
1578 public final function getCommunicatorInstance () {
1579 return $this->communicatorInstance;
1583 * Setter for communicator instance
1585 * @param $communicatorInstance An instance of a Communicator class
1588 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1589 $this->communicatorInstance = $communicatorInstance;
1593 * Setter for state instance
1595 * @param $stateInstance A Stateable instance
1598 public final function setStateInstance (Stateable $stateInstance) {
1599 $this->stateInstance = $stateInstance;
1603 * Getter for state instance
1605 * @return $stateInstance A Stateable instance
1607 public final function getStateInstance () {
1608 return $this->stateInstance;
1612 * Setter for output instance
1614 * @param $outputInstance The debug output instance
1617 public final function setOutputInstance (OutputStreamer $outputInstance) {
1618 $this->outputInstance = $outputInstance;
1622 * Getter for output instance
1624 * @return $outputInstance The debug output instance
1626 public final function getOutputInstance () {
1627 return $this->outputInstance;
1631 * Setter for command name
1633 * @param $commandName Last validated command name
1636 protected final function setCommandName ($commandName) {
1637 $this->commandName = $commandName;
1641 * Getter for command name
1643 * @return $commandName Last validated command name
1645 protected final function getCommandName () {
1646 return $this->commandName;
1650 * Setter for controller name
1652 * @param $controllerName Last validated controller name
1655 protected final function setControllerName ($controllerName) {
1656 $this->controllerName = $controllerName;
1660 * Getter for controller name
1662 * @return $controllerName Last validated controller name
1664 protected final function getControllerName () {
1665 return $this->controllerName;
1669 * Getter for protocol name
1671 * @return $protocolName Name of used protocol
1673 public final function getProtocolName () {
1674 return $this->protocolName;
1678 * Setter for protocol name
1680 * @param $protocolName Name of used protocol
1683 protected final function setProtocolName ($protocolName) {
1684 $this->protocolName = $protocolName;
1688 * Checks whether an object equals this object. You should overwrite this
1689 * method to implement own equality checks
1691 * @param $objectInstance An instance of a FrameworkInterface object
1692 * @return $equals Whether both objects equals
1694 public function equals (FrameworkInterface $objectInstance) {
1697 $this->__toString() == $objectInstance->__toString()
1699 $this->hashCode() == $objectInstance->hashCode()
1702 // Return the result
1707 * Generates a generic hash code of this class. You should really overwrite
1708 * this method with your own hash code generator code. But keep KISS in mind.
1710 * @return $hashCode A generic hash code respresenting this whole class
1712 public function hashCode () {
1714 return crc32($this->__toString());
1718 * Formats computer generated price values into human-understandable formats
1719 * with thousand and decimal separators.
1721 * @param $value The in computer format value for a price
1722 * @param $currency The currency symbol (use HTML-valid characters!)
1723 * @param $decNum Number of decimals after commata
1724 * @return $price The for the current language formated price string
1725 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1726 * thousands separator
1729 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1730 // Are all required attriutes set?
1731 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1732 // Throw an exception
1733 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1737 $value = (float) $value;
1739 // Reformat the US number
1740 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1742 // Return as string...
1747 * Appends a trailing slash to a string
1749 * @param $str A string (maybe) without trailing slash
1750 * @return $str A string with an auto-appended trailing slash
1752 public final function addMissingTrailingSlash ($str) {
1753 // Is there a trailing slash?
1754 if (substr($str, -1, 1) != '/') {
1758 // Return string with trailing slash
1763 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1764 * application helper instance (ApplicationHelper by default).
1766 * @param $applicationInstance An application helper instance or
1767 * null if we shall use the default
1768 * @return $templateInstance The template engine instance
1769 * @throws NullPointerException If the discovered application
1770 * instance is still null
1772 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1773 // Is the application instance set?
1774 if (is_null($applicationInstance)) {
1775 // Get the current instance
1776 $applicationInstance = $this->getApplicationInstance();
1779 if (is_null($applicationInstance)) {
1780 // Thrown an exception
1781 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1785 // Initialize the template engine
1786 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1788 // Return the prepared instance
1789 return $templateInstance;
1793 * Debugs this instance by putting out it's full content
1795 * @param $message Optional message to show in debug output
1798 public final function debugInstance ($message = '') {
1799 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1800 restore_error_handler();
1805 // Is a message set?
1806 if (!empty($message)) {
1807 // Construct message
1808 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1811 // Generate the output
1812 $content .= sprintf('<pre>%s</pre>',
1815 print_r($this, TRUE)
1821 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>',
1822 $this->__toString(),
1824 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1829 * Replaces control characters with printable output
1831 * @param $str String with control characters
1832 * @return $str Replaced string
1834 protected function replaceControlCharacters ($str) {
1837 chr(13), '[r]', str_replace(
1838 chr(10), '[n]', str_replace(
1848 * Output a partial stub message for the caller method
1850 * @param $message An optional message to display
1853 protected function partialStub ($message = '') {
1854 // Get the backtrace
1855 $backtrace = debug_backtrace();
1857 // Generate the class::method string
1858 $methodName = 'UnknownClass->unknownMethod';
1859 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1860 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1863 // Construct the full message
1864 $stubMessage = sprintf('[%s:] Partial stub!',
1868 // Is the extra message given?
1869 if (!empty($message)) {
1870 // Then add it as well
1871 $stubMessage .= ' Message: ' . $message;
1874 // Debug instance is there?
1875 if (!is_null($this->getDebugInstance())) {
1876 // Output stub message
1877 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1880 trigger_error($stubMessage);
1886 * Outputs a debug backtrace and stops further script execution
1888 * @param $message An optional message to output
1889 * @param $doExit Whether exit the program (TRUE is default)
1892 public function debugBackTrace ($message = '', $doExit = TRUE) {
1893 // Sorry, there is no other way getting this nice backtrace
1894 if (!empty($message)) {
1896 printf('Message: %s<br />' . PHP_EOL, $message);
1900 debug_print_backtrace();
1904 if ($doExit === TRUE) {
1910 * Creates an instance of a debugger instance
1912 * @param $className Name of the class (currently unsupported)
1913 * @param $lineNumber Line number where the call was made
1914 * @return $debugInstance An instance of a debugger class
1915 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1917 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1918 // Is the instance set?
1919 if (!Registry::getRegistry()->instanceExists('debug')) {
1920 // Init debug instance
1921 $debugInstance = NULL;
1925 // Get a debugger instance
1926 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_class'), $className);
1927 } catch (NullPointerException $e) {
1928 // Didn't work, no instance there
1929 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1932 // Empty string should be ignored and used for testing the middleware
1933 DebugMiddleware::getSelfInstance()->output('');
1935 // Set it in its own class. This will set it in the registry
1936 $debugInstance->setDebugInstance($debugInstance);
1938 // Get instance from registry
1939 $debugInstance = Registry::getRegistry()->getDebugInstance();
1943 return $debugInstance;
1947 * Simple output of a message with line-break
1949 * @param $message Message to output
1952 public function outputLine ($message) {
1954 print($message . PHP_EOL);
1958 * Outputs a debug message whether to debug instance (should be set!) or
1959 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1960 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1962 * @param $message Message we shall send out...
1963 * @param $doPrint Whether print or die here (default: print)
1964 * @paran $stripTags Whether to strip tags (default: FALSE)
1967 public function debugOutput ($message, $doPrint = TRUE, $stripTags = FALSE) {
1968 // Set debug instance to NULL
1969 $debugInstance = NULL;
1973 // Get debug instance
1974 $debugInstance = $this->getDebugInstance();
1975 } catch (NullPointerException $e) {
1976 // The debug instance is not set (yet)
1979 // Is the debug instance there?
1980 if (is_object($debugInstance)) {
1981 // Use debug output handler
1982 $debugInstance->output($message, $stripTags);
1984 if ($doPrint === FALSE) {
1985 // Die here if not printed
1989 // Are debug times enabled?
1990 if ($this->getConfigInstance()->getConfigEntry('debug_' . self::getResponseTypeFromSystem() . '_output_timings') == 'Y') {
1992 $message = $this->getPrintableExecutionTime() . $message;
1996 if ($doPrint === TRUE) {
1998 $this->outputLine($message);
2007 * Converts e.g. a command from URL to a valid class by keeping out bad characters
2009 * @param $str The string, what ever it is needs to be converted
2010 * @return $className Generated class name
2012 public static final function convertToClassName ($str) {
2016 // Convert all dashes in underscores
2017 $str = self::convertDashesToUnderscores($str);
2019 // Now use that underscores to get classname parts for hungarian style
2020 foreach (explode('_', $str) as $strPart) {
2021 // Make the class name part lower case and first upper case
2022 $className .= ucfirst(strtolower($strPart));
2025 // Return class name
2030 * Converts dashes to underscores, e.g. useable for configuration entries
2032 * @param $str The string with maybe dashes inside
2033 * @return $str The converted string with no dashed, but underscores
2035 public static final function convertDashesToUnderscores ($str) {
2037 $str = str_replace('-', '_', $str);
2039 // Return converted string
2044 * Marks up the code by adding e.g. line numbers
2046 * @param $phpCode Unmarked PHP code
2047 * @return $markedCode Marked PHP code
2049 public function markupCode ($phpCode) {
2054 $errorArray = error_get_last();
2056 // Init the code with error message
2057 if (is_array($errorArray)) {
2059 $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>',
2060 basename($errorArray['file']),
2061 $errorArray['line'],
2062 $errorArray['message'],
2067 // Add line number to the code
2068 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2070 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2072 htmlentities($code, ENT_QUOTES)
2081 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2082 * beatiful for web-based front-ends. If null is given a message id
2083 * null_timestamp will be resolved and returned.
2085 * @param $timestamp Timestamp to prepare (filter) for display
2086 * @return $readable A readable timestamp
2088 public function doFilterFormatTimestamp ($timestamp) {
2089 // Default value to return
2092 // Is the timestamp null?
2093 if (is_null($timestamp)) {
2094 // Get a message string
2095 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2097 switch ($this->getLanguageInstance()->getLanguageCode()) {
2098 case 'de': // German format is a bit different to default
2099 // Split the GMT stamp up
2100 $dateTime = explode(' ', $timestamp );
2101 $dateArray = explode('-', $dateTime[0]);
2102 $timeArray = explode(':', $dateTime[1]);
2104 // Construct the timestamp
2105 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2115 default: // Default is pass-through
2116 $readable = $timestamp;
2126 * Filter a given number into a localized number
2128 * @param $value The raw value from e.g. database
2129 * @return $localized Localized value
2131 public function doFilterFormatNumber ($value) {
2132 // Generate it from config and localize dependencies
2133 switch ($this->getLanguageInstance()->getLanguageCode()) {
2134 case 'de': // German format is a bit different to default
2135 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2138 default: // US, etc.
2139 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2148 * "Getter" for databse entry
2150 * @return $entry An array with database entries
2151 * @throws NullPointerException If the database result is not found
2152 * @throws InvalidDatabaseResultException If the database result is invalid
2154 protected final function getDatabaseEntry () {
2155 // Is there an instance?
2156 if (!$this->getResultInstance() instanceof SearchableResult) {
2157 // Throw an exception here
2158 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2162 $this->getResultInstance()->rewind();
2164 // Do we have an entry?
2165 if ($this->getResultInstance()->valid() === FALSE) {
2166 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2167 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2171 $this->getResultInstance()->next();
2174 $entry = $this->getResultInstance()->current();
2181 * Getter for field name
2183 * @param $fieldName Field name which we shall get
2184 * @return $fieldValue Field value from the user
2185 * @throws NullPointerException If the result instance is null
2187 public final function getField ($fieldName) {
2188 // Default field value
2191 // Get result instance
2192 $resultInstance = $this->getResultInstance();
2194 // Is this instance null?
2195 if (is_null($resultInstance)) {
2196 // Then the user instance is no longer valid (expired cookies?)
2197 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2200 // Get current array
2201 $fieldArray = $resultInstance->current();
2202 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, TRUE).'</pre>');
2204 // Convert dashes to underscore
2205 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2207 // Does the field exist?
2208 if ($this->isFieldSet($fieldName)) {
2210 $fieldValue = $fieldArray[$fieldName2];
2211 } elseif (defined('DEVELOPER')) {
2212 // Missing field entry, may require debugging
2213 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, TRUE) . '</pre>,fieldName=' . $fieldName . ' not found!');
2215 // Missing field entry, may require debugging
2216 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2224 * Checks if given field is set
2226 * @param $fieldName Field name to check
2227 * @return $isSet Whether the given field name is set
2228 * @throws NullPointerException If the result instance is null
2230 public function isFieldSet ($fieldName) {
2231 // Get result instance
2232 $resultInstance = $this->getResultInstance();
2234 // Is this instance null?
2235 if (is_null($resultInstance)) {
2236 // Then the user instance is no longer valid (expired cookies?)
2237 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2240 // Get current array
2241 $fieldArray = $resultInstance->current();
2242 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, TRUE).'</pre>');
2244 // Convert dashes to underscore
2245 $fieldName = self::convertDashesToUnderscores($fieldName);
2248 $isSet = isset($fieldArray[$fieldName]);
2255 * Flushs all pending updates to the database layer
2259 public function flushPendingUpdates () {
2260 // Get result instance
2261 $resultInstance = $this->getResultInstance();
2263 // Do we have data to update?
2264 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2265 // Get wrapper class name config entry
2266 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2268 // Create object instance
2269 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2271 // Yes, then send the whole result to the database layer
2272 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2277 * Outputs a deprecation warning to the developer.
2279 * @param $message The message we shall output to the developer
2281 * @todo Write a logging mechanism for productive mode
2283 public function deprecationWarning ($message) {
2284 // Is developer mode active?
2285 if (defined('DEVELOPER')) {
2286 // Debug instance is there?
2287 if (!is_null($this->getDebugInstance())) {
2288 // Output stub message
2289 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2292 trigger_error($message . "<br />\n");
2296 // @TODO Finish this part!
2297 $this->partialStub('Developer mode inactive. Message:' . $message);
2302 * Checks whether the given PHP extension is loaded
2304 * @param $phpExtension The PHP extension we shall check
2305 * @return $isLoaded Whether the PHP extension is loaded
2307 public final function isPhpExtensionLoaded ($phpExtension) {
2309 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2316 * "Getter" as a time() replacement but with milliseconds. You should use this
2317 * method instead of the encapsulated getimeofday() function.
2319 * @return $milliTime Timestamp with milliseconds
2321 public function getMilliTime () {
2322 // Get the time of day as float
2323 $milliTime = gettimeofday(TRUE);
2330 * Idles (sleeps) for given milliseconds
2332 * @return $hasSlept Whether it goes fine
2334 public function idle ($milliSeconds) {
2335 // Sleep is fine by default
2338 // Idle so long with found function
2339 if (function_exists('time_sleep_until')) {
2340 // Get current time and add idle time
2341 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2343 // New PHP 5.1.0 function found, ignore errors
2344 $hasSlept = @time_sleep_until($sleepUntil);
2347 * My Sun station doesn't have that function even with latest PHP
2350 usleep($milliSeconds * 1000);
2357 * Converts a hexadecimal string, even with negative sign as first string to
2358 * a decimal number using BC functions.
2360 * This work is based on comment #86673 on php.net documentation page at:
2361 * <http://de.php.net/manual/en/function.dechex.php#86673>
2363 * @param $hex Hexadecimal string
2364 * @return $dec Decimal number
2366 protected function hex2dec ($hex) {
2367 // Convert to all lower-case
2368 $hex = strtolower($hex);
2370 // Detect sign (negative/positive numbers)
2372 if (substr($hex, 0, 1) == '-') {
2374 $hex = substr($hex, 1);
2377 // Decode the hexadecimal string into a decimal number
2379 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2380 $factor = self::$hexdec[substr($hex, $i, 1)];
2381 $dec = bcadd($dec, bcmul($factor, $e));
2384 // Return the decimal number
2385 return $sign . $dec;
2389 * Converts even very large decimal numbers, also signed, to a hexadecimal
2392 * This work is based on comment #97756 on php.net documentation page at:
2393 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2395 * @param $dec Decimal number, even with negative sign
2396 * @param $maxLength Optional maximum length of the string
2397 * @return $hex Hexadecimal string
2399 protected function dec2hex ($dec, $maxLength = 0) {
2400 // maxLength can be zero or devideable by 2
2401 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2403 // Detect sign (negative/positive numbers)
2410 // Encode the decimal number into a hexadecimal string
2413 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2415 } while ($dec >= 1);
2418 * Leading zeros are required for hex-decimal "numbers". In some
2419 * situations more leading zeros are wanted, so check for both
2422 if ($maxLength > 0) {
2423 // Prepend more zeros
2424 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2425 } elseif ((strlen($hex) % 2) != 0) {
2426 // Only make string's length dividable by 2
2430 // Return the hexadecimal string
2431 return $sign . $hex;
2435 * Converts a ASCII string (0 to 255) into a decimal number.
2437 * @param $asc The ASCII string to be converted
2438 * @return $dec Decimal number
2440 protected function asc2dec ($asc) {
2441 // Convert it into a hexadecimal number
2442 $hex = bin2hex($asc);
2444 // And back into a decimal number
2445 $dec = $this->hex2dec($hex);
2452 * Converts a decimal number into an ASCII string.
2454 * @param $dec Decimal number
2455 * @return $asc An ASCII string
2457 protected function dec2asc ($dec) {
2458 // First convert the number into a hexadecimal string
2459 $hex = $this->dec2hex($dec);
2461 // Then convert it into the ASCII string
2462 $asc = $this->hex2asc($hex);
2469 * Converts a hexadecimal number into an ASCII string. Negative numbers
2472 * @param $hex Hexadecimal string
2473 * @return $asc An ASCII string
2475 protected function hex2asc ($hex) {
2476 // Check for length, it must be devideable by 2
2477 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2478 assert((strlen($hex) % 2) == 0);
2482 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2483 // Get the decimal number of the chunk
2484 $part = hexdec(substr($hex, $idx, 2));
2486 // Add it to the final string
2490 // Return the final string
2495 * Checks whether the given encoded data was encoded with Base64
2497 * @param $encodedData Encoded data we shall check
2498 * @return $isBase64 Whether the encoded data is Base64
2500 protected function isBase64Encoded ($encodedData) {
2502 $isBase64 = (@base64_decode($encodedData, TRUE) !== FALSE);
2509 * "Getter" to get response/request type from analysis of the system.
2511 * @return $responseType Analyzed response type
2513 protected static function getResponseTypeFromSystem () {
2514 // Default is console
2515 $responseType = 'console';
2517 // Is 'HTTP_HOST' set?
2518 if (isset($_SERVER['HTTP_HOST'])) {
2520 * Then it is a HTML response/request as RSS and so on may be
2521 * transfered over HTTP as well.
2523 $responseType = 'html';
2527 return $responseType;
2531 * Gets a cache key from Criteria instance
2533 * @param $criteriaInstance An instance of a Criteria class
2534 * @param $onlyKeys Only use these keys for a cache key
2535 * @return $cacheKey A cache key suitable for lookup/storage purposes
2537 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2539 $cacheKey = sprintf('%s@%s',
2540 $this->__toString(),
2541 $criteriaInstance->getCacheKey($onlyKeys)
2545 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2550 * Getter for startup time in miliseconds
2552 * @return $startupTime Startup time in miliseconds
2554 protected function getStartupTime () {
2555 return self::$startupTime;
2559 * "Getter" for a printable currently execution time in nice braces
2561 * @return $executionTime Current execution time in nice braces
2563 protected function getPrintableExecutionTime () {
2564 // Caculate the execution time
2565 $executionTime = microtime(TRUE) - $this->getStartupTime();
2567 // Pack it in nice braces
2568 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2571 return $executionTime;
2575 * Hashes a given string with a simple but stronger hash function (no salt)
2576 * and hex-encode it.
2578 * @param $str The string to be hashed
2579 * @return $hash The hash from string $str
2581 public static final function hash ($str) {
2582 // Hash given string with (better secure) hasher
2583 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2590 * "Getter" for length of hash() output. This will be "cached" to speed up
2593 * @return $length Length of hash() output
2595 public static final function getHashLength () {
2597 if (is_null(self::$hashLength)) {
2598 // No, then hash a string and save its length.
2599 self::$hashLength = strlen(self::hash('abc123'));
2603 return self::$hashLength;
2607 * Checks whether the given number is really a number (only chars 0-9).
2609 * @param $num A string consisting only chars between 0 and 9
2610 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2611 * @param $assertMismatch Whether to assert mismatches
2612 * @return $ret The (hopefully) secured numbered value
2614 public function bigintval ($num, $castValue = TRUE, $assertMismatch = FALSE) {
2615 // Filter all numbers out
2616 $ret = preg_replace('/[^0123456789]/', '', $num);
2619 if ($castValue === TRUE) {
2620 // Cast to biggest numeric type
2621 $ret = (double) $ret;
2624 // Assert only if requested
2625 if ($assertMismatch === TRUE) {
2626 // Has the whole value changed?
2627 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2635 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2637 * @param $num A string consisting only chars between 0 and 9
2638 * @param $assertMismatch Whether to assert mismatches
2639 * @return $ret The (hopefully) secured hext-numbered value
2641 public function hexval ($num, $assertMismatch = FALSE) {
2642 // Filter all numbers out
2643 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2645 // Assert only if requested
2646 if ($assertMismatch === TRUE) {
2647 // Has the whole value changed?
2648 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2656 * Checks whether start/end marker are set
2658 * @param $data Data to be checked
2659 * @return $isset Whether start/end marker are set
2661 public final function ifStartEndMarkersSet ($data) {
2663 $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));
2665 // ... and return it
2670 * Determines if an element 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 * @param $element Element to check
2676 * @return $isset Whether the given key is set
2678 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2680 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2683 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2689 * Determines if a key is set in the generic array
2691 * @param $keyGroup Main group for the key
2692 * @param $subGroup Sub group for the key
2693 * @param $key Key to check
2694 * @return $isset Whether the given key is set
2696 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2698 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2701 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2709 * Determines if a group is set in the generic array
2711 * @param $keyGroup Main group
2712 * @param $subGroup Sub group
2713 * @return $isset Whether the given group is set
2715 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2717 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2720 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2727 * Getter for sub key group
2729 * @param $keyGroup Main key group
2730 * @param $subGroup Sub key group
2731 * @return $array An array with all array elements
2733 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2735 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2736 // No, then abort here
2737 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2742 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], TRUE));
2745 return $this->genericArray[$keyGroup][$subGroup];
2749 * Unsets a given key in generic array
2751 * @param $keyGroup Main group for the key
2752 * @param $subGroup Sub group for the key
2753 * @param $key Key to unset
2756 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2758 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2761 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2765 * Unsets a given element in generic array
2767 * @param $keyGroup Main group for the key
2768 * @param $subGroup Sub group for the key
2769 * @param $key Key to unset
2770 * @param $element Element to unset
2773 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2775 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2778 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2782 * Append a string to a given generic array key
2784 * @param $keyGroup Main group for the key
2785 * @param $subGroup Sub group for the key
2786 * @param $key Key to unset
2787 * @param $value Value to add/append
2790 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2792 //* 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);
2794 // Is it already there?
2795 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2797 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2800 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2805 * Append a string to a given generic array element
2807 * @param $keyGroup Main group for the key
2808 * @param $subGroup Sub group for the key
2809 * @param $key Key to unset
2810 * @param $element Element to check
2811 * @param $value Value to add/append
2814 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2816 //* 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);
2818 // Is it already there?
2819 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2821 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2824 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2829 * Sets a string in a given generic array element
2831 * @param $keyGroup Main group for the key
2832 * @param $subGroup Sub group for the key
2833 * @param $key Key to unset
2834 * @param $element Element to check
2835 * @param $value Value to add/append
2838 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2840 //* 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);
2843 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2847 * Initializes given generic array group
2849 * @param $keyGroup Main group for the key
2850 * @param $subGroup Sub group for the key
2851 * @param $key Key to use
2852 * @param $forceInit Optionally force initialization
2855 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = FALSE) {
2857 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2859 // Is it already set?
2860 if (($forceInit === FALSE) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2861 // Already initialized
2862 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2867 $this->genericArray[$keyGroup][$subGroup] = array();
2871 * Initializes given generic array key
2873 * @param $keyGroup Main group for the key
2874 * @param $subGroup Sub group for the key
2875 * @param $key Key to use
2876 * @param $forceInit Optionally force initialization
2879 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = FALSE) {
2881 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2883 // Is it already set?
2884 if (($forceInit === FALSE) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2885 // Already initialized
2886 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2891 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2895 * Initializes given generic array element
2897 * @param $keyGroup Main group for the key
2898 * @param $subGroup Sub group for the key
2899 * @param $key Key to use
2900 * @param $element Element to use
2901 * @param $forceInit Optionally force initialization
2904 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = FALSE) {
2906 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2908 // Is it already set?
2909 if (($forceInit === FALSE) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2910 // Already initialized
2911 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2916 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2920 * Pushes an element to a generic key
2922 * @param $keyGroup Main group for the key
2923 * @param $subGroup Sub group for the key
2924 * @param $key Key to use
2925 * @param $value Value to add/append
2926 * @return $count Number of array elements
2928 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2930 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
2933 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2935 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2939 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2942 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2943 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2948 * Pushes an element to a generic array element
2950 * @param $keyGroup Main group for the key
2951 * @param $subGroup Sub group for the key
2952 * @param $key Key to use
2953 * @param $element Element to check
2954 * @param $value Value to add/append
2955 * @return $count Number of array elements
2957 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2959 //* 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));
2962 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2964 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2968 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2971 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
2972 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2977 * Pops an element from a generic group
2979 * @param $keyGroup Main group for the key
2980 * @param $subGroup Sub group for the key
2981 * @param $key Key to unset
2982 * @return $value Last "popped" value
2984 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2986 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2989 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2991 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2996 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2999 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3000 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3005 * Shifts an element from a generic group
3007 * @param $keyGroup Main group for the key
3008 * @param $subGroup Sub group for the key
3009 * @param $key Key to unset
3010 * @return $value Last "popped" value
3012 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
3014 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3017 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3019 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
3024 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
3027 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], TRUE));
3028 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, TRUE) . PHP_EOL);
3033 * Count generic array group
3035 * @param $keyGroup Main group for the key
3036 * @return $count Count of given group
3038 protected final function countGenericArray ($keyGroup) {
3040 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3043 if (!isset($this->genericArray[$keyGroup])) {
3045 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3050 $count = count($this->genericArray[$keyGroup]);
3053 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3060 * Count generic array sub group
3062 * @param $keyGroup Main group for the key
3063 * @param $subGroup Sub group for the key
3064 * @return $count Count of given group
3066 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3068 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3071 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3073 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3078 $count = count($this->genericArray[$keyGroup][$subGroup]);
3081 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3088 * Count generic array elements
3090 * @param $keyGroup Main group for the key
3091 * @param $subGroup Sub group for the key
3092 * @para $key Key to count
3093 * @return $count Count of given key
3095 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3097 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3100 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3102 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3104 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3106 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3111 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3114 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3121 * Getter for whole generic group array
3123 * @param $keyGroup Key group to get
3124 * @return $array Whole generic array group
3126 protected final function getGenericArray ($keyGroup) {
3128 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3131 if (!isset($this->genericArray[$keyGroup])) {
3133 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3138 return $this->genericArray[$keyGroup];
3142 * Setter for generic array key
3144 * @param $keyGroup Key group to get
3145 * @param $subGroup Sub group for the key
3146 * @param $key Key to unset
3147 * @param $value Mixed value from generic array element
3150 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3152 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, TRUE));
3155 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3159 * Getter for generic array key
3161 * @param $keyGroup Key group to get
3162 * @param $subGroup Sub group for the key
3163 * @param $key Key to unset
3164 * @return $value Mixed value from generic array element
3166 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3168 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3171 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3173 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3178 return $this->genericArray[$keyGroup][$subGroup][$key];
3182 * Sets a value in given generic array key/element
3184 * @param $keyGroup Main group for the key
3185 * @param $subGroup Sub group for the key
3186 * @param $key Key to set
3187 * @param $element Element to set
3188 * @param $value Value to set
3191 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3193 //* 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));
3196 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3200 * Getter for generic array element
3202 * @param $keyGroup Key group to get
3203 * @param $subGroup Sub group for the key
3204 * @param $key Key to look for
3205 * @param $element Element to look for
3206 * @return $value Mixed value from generic array element
3208 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3210 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3213 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3215 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3220 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3224 * Checks if a given sub group is valid (array)
3226 * @param $keyGroup Key group to get
3227 * @param $subGroup Sub group for the key
3228 * @return $isValid Whether given sub group is valid
3230 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3232 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3235 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3242 * Checks if a given key is valid (array)
3244 * @param $keyGroup Key group to get
3245 * @param $subGroup Sub group for the key
3246 * @param $key Key to check
3247 * @return $isValid Whether given sub group is valid
3249 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3251 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3254 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3261 * Initializes the web output instance
3265 protected function initWebOutputInstance () {
3266 // Get application instance
3267 $applicationInstance = Registry::getRegistry()->getInstance('app');
3269 // Is this a response instance?
3270 if ($this instanceof Responseable) {
3271 // Then set it in application instance
3272 $applicationInstance->setResponseInstance($this);
3275 // Init web output instance
3276 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3279 $this->setWebOutputInstance($outputInstance);
3283 * Translates boolean TRUE to 'Y' and FALSE to 'N'
3285 * @param $boolean Boolean value
3286 * @return $translated Translated boolean value
3288 public static final function translateBooleanToYesNo ($boolean) {
3289 // Make sure it is really boolean
3290 assert(is_bool($boolean));
3293 $translated = ($boolean === TRUE) ? 'Y' : 'N';
3295 // ... and return it
3300 * Encodes raw data (almost any type) by "serializing" it and then pack it
3301 * into a "binary format".
3303 * @param $rawData Raw data (almost any type)
3304 * @return $encoded Encoded data
3306 protected function encodeData ($rawData) {
3307 // Make sure no objects or resources pass through
3308 assert(!is_object($rawData));
3309 assert(!is_resource($rawData));
3311 // First "serialize" it (json_encode() is faster than serialize())
3312 $encoded = $this->packString(json_encode($rawData));
3319 * Pack a string into a "binary format". Please execuse me that this is
3320 * widely undocumented. :-(
3322 * @param $str Unpacked string
3323 * @return $packed Packed string
3324 * @todo Improve documentation
3326 protected function packString ($str) {
3328 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3330 // First compress the string (gzcompress is okay)
3331 $str = gzcompress($str);
3336 // And start the "encoding" loop
3337 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3339 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3340 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3342 if (($idx + $i) <= strlen($str)) {
3343 $ord = ord(substr($str, ($idx + $i), 1));
3345 $add = $ord * pow(256, $factor);
3349 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3353 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3354 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3356 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3357 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3363 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3368 * Checks whether the given file/path is in open_basedir(). This does not
3369 * gurantee that the file is actually readable and/or writeable. If you need
3370 * such gurantee then please use isReadableFile() instead.
3372 * @param $filePathName Name of the file/path to be checked
3373 * @return $isReachable Whether it is within open_basedir()
3375 protected static function isReachableFilePath ($filePathName) {
3376 // Is not reachable by default
3377 $isReachable = FALSE;
3379 // Get open_basedir parameter
3380 $openBaseDir = ini_get('open_basedir');
3383 if (!empty($openBaseDir)) {
3384 // Check all entries
3385 foreach (explode(PATH_SEPARATOR, $openBaseDir) as $dir) {
3386 // Check on existence
3387 if (substr($filePathName, 0, strlen($dir)) == $dir) {
3389 $isReachable = TRUE;
3393 // If open_basedir is not set, all is allowed
3394 $isReachable = TRUE;
3398 return $isReachable;
3402 * Checks whether the give file is within open_basedir() (done by
3403 * isReachableFilePath()), is actually a file and is readable.
3405 * @param $fileName Name of the file to be checked
3406 * @return $isReadable Whether the file is readable (and therefor exists)
3408 public static function isReadableFile ($fileName) {
3409 // Default is not readable
3410 $isReadable = FALSE;
3412 // Is within parameters, so check if it is a file and readable
3413 $isReadable = ((self::isReachableFilePath($fileName)) && (file_exists($fileName)) && (is_file($fileName)) && (is_readable($fileName)));
3420 * Creates a full-qualified file name (FQFN) for given file name by adding
3421 * a configured temporary file path to it.
3423 * @param $fileName Name for temporary file
3424 * @return $fqfn Full-qualified file name
3425 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3426 * @throws FileIoException If the file cannot be written
3428 protected static function createTempPathForFile ($fileName) {
3430 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3432 // Is the path writeable?
3433 if (!is_writable($basePath)) {
3434 // Path is write-protected
3435 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3439 $fqfn = $basePath . '/' . $fileName;
3442 if (!self::isReachableFilePath($fqfn)) {
3444 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3452 * "Getter" for a printable state name
3454 * @return $stateName Name of the node's state in a printable format
3456 public final function getPrintableState () {
3457 // Default is 'null'
3458 $stateName = 'null';
3460 // Get the state instance
3461 $stateInstance = $this->getStateInstance();
3463 // Is it an instance of Stateable?
3464 if ($stateInstance instanceof Stateable) {
3465 // Then use that state name
3466 $stateName = $stateInstance->getStateName();
3474 * Handles socket error for given socket resource and peer data. This method
3475 * validates $socketResource if it is a valid resource (see is_resource())
3476 * but assumes valid data in array $recipientData, except that
3477 * count($recipientData) is always 2.
3479 * @param $method Value of __METHOD__ from calling method
3480 * @param $line Value of __LINE__ from calling method
3481 * @param $socketResource A valid socket resource
3482 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3484 * @throws InvalidSocketException If $socketResource is no socket resource
3485 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3486 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3488 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3489 // This method handles only socket resources
3490 if (!is_resource($socketResource)) {
3491 // No resource, abort here
3492 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3495 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3496 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, TRUE));
3497 assert(isset($socketData[0]));
3498 assert(isset($socketData[1]));
3500 // Get error code for first validation (0 is not an error)
3501 $errorCode = socket_last_error($socketResource);
3503 // If the error code is zero, someone called this method without an error
3504 if ($errorCode == 0) {
3505 // No error detected (or previously cleared outside this method)
3506 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3509 // Get handler (method) name
3510 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3512 // Call-back the error handler method
3513 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3515 // Finally clear the error because it has been handled
3516 socket_clear_error($socketResource);