3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Bootstrap\FrameworkBootstrap;
7 use CoreFramework\Compressor\Compressor;
8 use CoreFramework\Configuration\FrameworkConfiguration;
9 use CoreFramework\Connection\Database\DatabaseConnection;
10 use CoreFramework\Controller\Controller;
11 use CoreFramework\Criteria\Criteria;
12 use CoreFramework\Criteria\Local\LocalSearchCriteria;
13 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
14 use CoreFramework\Crypto\Cryptable;
15 use CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
16 use CoreFramework\Database\Frontend\DatabaseWrapper;
17 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
18 use CoreFramework\Factory\ObjectFactory;
19 use CoreFramework\Filesystem\Block;
20 use CoreFramework\Filesystem\FilePointer;
21 use CoreFramework\Filesystem\FrameworkDirectory;
22 use CoreFramework\Filesystem\PathWriteProtectedException;
23 use CoreFramework\Generic\FrameworkInterface;
24 use CoreFramework\Generic\NullPointerException;
25 use CoreFramework\Generic\UnsupportedOperationException;
26 use CoreFramework\Handler\Stream\IoHandler;
27 use CoreFramework\Index\Indexable;
28 use CoreFramework\Listener\BaseListener;
29 use CoreFramework\Listener\Listenable;
30 use CoreFramework\Lists\Listable;
31 use CoreFramework\Loader\ClassLoader;
32 use CoreFramework\Manager\ManageableApplication;
33 use CoreFramework\Middleware\Compressor\CompressorChannel;
34 use CoreFramework\Middleware\Debug\DebugMiddleware;
35 use CoreFramework\Parser\Parseable;
36 use CoreFramework\Registry\Register;
37 use CoreFramework\Registry\Registry;
38 use CoreFramework\Resolver\Resolver;
39 use CoreFramework\Result\Database\CachedDatabaseResult;
40 use CoreFramework\Result\Search\SearchableResult;
41 use CoreFramework\Stacker\Stackable;
42 use CoreFramework\State\Stateable;
43 use CoreFramework\Stream\Output\OutputStreamer;
44 use CoreFramework\Template\CompileableTemplate;
45 use CoreFramework\User\ManageableAccount;
46 use CoreFramework\Visitor\Visitor;
54 * The simulator system class is the super class of all other classes. This
55 * class handles saving of games etc.
57 * @author Roland Haeder <webmaster@shipsimu.org>
59 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
60 * @license GNU GPL 3.0 or any newer version
61 * @link http://www.shipsimu.org
63 * This program is free software: you can redistribute it and/or modify
64 * it under the terms of the GNU General Public License as published by
65 * the Free Software Foundation, either version 3 of the License, or
66 * (at your option) any later version.
68 * This program is distributed in the hope that it will be useful,
69 * but WITHOUT ANY WARRANTY; without even the implied warranty of
70 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
71 * GNU General Public License for more details.
73 * You should have received a copy of the GNU General Public License
74 * along with this program. If not, see <http://www.gnu.org/licenses/>.
76 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
78 * Length of output from hash()
80 private static $hashLength = NULL;
85 private $realClass = 'BaseFrameworkSystem';
88 * Search criteria instance
90 private $searchInstance = NULL;
93 * Update criteria instance
95 private $updateInstance = NULL;
98 * The file I/O instance for the template loader
100 private $fileIoInstance = NULL;
105 private $resolverInstance = NULL;
108 * Template engine instance
110 private $templateInstance = NULL;
113 * Database result instance
115 private $resultInstance = NULL;
118 * Instance for user class
120 private $userInstance = NULL;
123 * A controller instance
125 private $controllerInstance = NULL;
130 private $rngInstance = NULL;
133 * Instance of a crypto helper
135 private $cryptoInstance = NULL;
138 * Instance of an Iterator class
140 private $iteratorInstance = NULL;
143 * Instance of the list
145 private $listInstance = NULL;
150 private $menuInstance = NULL;
153 * Instance of the image
155 private $imageInstance = NULL;
158 * Instance of the stacker
160 private $stackInstance = NULL;
163 * A Compressor instance
165 private $compressorInstance = NULL;
168 * A Parseable instance
170 private $parserInstance = NULL;
173 * A HandleableProtocol instance
175 private $protocolInstance = NULL;
178 * A database wrapper instance
180 private $databaseInstance = NULL;
183 * A helper instance for the form
185 private $helperInstance = NULL;
188 * An instance of a Source class
190 private $sourceInstance = NULL;
193 * An instance of a UrlSource class
195 private $urlSourceInstance = NULL;
198 * An instance of a InputStream class
200 private $inputStreamInstance = NULL;
203 * An instance of a OutputStream class
205 private $outputStreamInstance = NULL;
208 * Networkable handler instance
210 private $handlerInstance = NULL;
213 * Visitor handler instance
215 private $visitorInstance = NULL;
220 private $dhtInstance = NULL;
223 * An instance of a database wrapper class
225 private $wrapperInstance = NULL;
228 * An instance of a file I/O pointer class (not handler)
230 private $pointerInstance = NULL;
233 * An instance of an Indexable class
235 private $indexInstance = NULL;
238 * An instance of a Block class
240 private $blockInstance = NULL;
245 private $minableInstance = NULL;
248 * A FrameworkDirectory instance
250 private $directoryInstance = NULL;
255 private $listenerInstance = NULL;
258 * An instance of a communicator
260 private $communicatorInstance = NULL;
263 * The concrete output instance
265 private $outputInstance = NULL;
270 private $stateInstance = NULL;
273 * Thousands separator
275 private $thousands = '.'; // German
280 private $decimals = ','; // German
285 private $socketResource = false;
288 * Regular expression to use for validation
290 private $regularExpression = '';
295 private $packageData = array();
300 private $genericArray = array();
305 private $commandName = '';
310 private $controllerName = '';
313 * Name of used protocol
315 private $protocolName = 'invalid';
318 * Array with bitmasks and such for pack/unpack methods to support both
319 * 32-bit and 64-bit systems
321 private $packingData = array(
324 'left' => 0xffff0000,
325 'right' => 0x0000ffff,
331 'left' => 0xffffffff00000000,
332 'right' => 0x00000000ffffffff,
339 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
341 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
343 private $archArrayElement = false;
345 /***********************
346 * Exception codes.... *
347 ***********************/
349 // @todo Try to clean these constants up
350 const EXCEPTION_IS_NULL_POINTER = 0x001;
351 const EXCEPTION_IS_NO_OBJECT = 0x002;
352 const EXCEPTION_IS_NO_ARRAY = 0x003;
353 const EXCEPTION_MISSING_METHOD = 0x004;
354 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
355 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
356 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
357 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
358 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
359 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
360 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
361 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
362 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
363 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
364 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
365 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
366 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
367 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
368 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
369 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
370 const EXCEPTION_PATH_NOT_FOUND = 0x015;
371 const EXCEPTION_INVALID_PATH_NAME = 0x016;
372 const EXCEPTION_READ_PROTECED_PATH = 0x017;
373 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
374 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
375 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
376 const EXCEPTION_INVALID_RESOURCE = 0x01b;
377 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
378 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
379 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
380 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
381 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
382 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
383 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
384 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
385 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
386 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
387 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
388 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
389 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
390 const EXCEPTION_INVALID_STRING = 0x029;
391 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
392 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
393 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
394 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
395 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
396 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
397 const EXCEPTION_MISSING_ELEMENT = 0x030;
398 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
399 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
400 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
401 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
402 const EXCEPTION_FATAL_ERROR = 0x035;
403 const EXCEPTION_FILE_NOT_FOUND = 0x036;
404 const EXCEPTION_ASSERTION_FAILED = 0x037;
405 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
406 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
407 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
408 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
409 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
410 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
413 * Hexadecimal->Decimal translation array
415 private static $hexdec = array(
435 * Decimal->hexadecimal translation array
437 private static $dechex = array(
457 * Startup time in miliseconds
459 private static $startupTime = 0;
462 * Protected super constructor
464 * @param $className Name of the class
467 protected function __construct ($className) {
469 $this->setRealClass($className);
471 // Set configuration instance if no registry ...
472 if (!$this instanceof Register) {
473 // ... because registries doesn't need to be configured
474 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
477 // Is the startup time set? (0 cannot be true anymore)
478 if (self::$startupTime == 0) {
480 self::$startupTime = microtime(true);
484 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
488 * Destructor for all classes. You should not call this method on your own.
492 public function __destruct () {
493 // Flush any updated entries to the database
494 $this->flushPendingUpdates();
496 // Is this object already destroyed?
497 if ($this->__toString() != 'DestructedObject') {
498 // Destroy all informations about this class but keep some text about it alive
499 $this->setRealClass('DestructedObject');
500 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
501 // Already destructed object
502 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
507 // Do not call this twice
508 trigger_error(__METHOD__ . ': Called twice.');
514 * The __call() method where all non-implemented methods end up
516 * @param $methodName Name of the missing method
517 * @args $args Arguments passed to the method
520 public final function __call ($methodName, $args) {
521 return self::__callStatic($methodName, $args);
525 * The __callStatic() method where all non-implemented static methods end up
527 * @param $methodName Name of the missing method
528 * @args $args Arguments passed to the method
531 public static final function __callStatic ($methodName, $args) {
533 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
535 // Init argument string
538 // Is it NULL, empty or an array?
539 if (is_null($args)) {
541 $argsString = 'NULL';
542 } elseif (is_array($args)) {
546 // Some arguments are there
547 foreach ($args as $arg) {
548 // Add data about the argument
549 $argsString .= gettype($arg) . ':';
552 // Found a NULL argument
553 $argsString .= 'NULL';
554 } elseif (is_string($arg)) {
555 // Add length for strings
556 $argsString .= strlen($arg);
557 } elseif ((is_int($arg)) || (is_float($arg))) {
560 } elseif (is_array($arg)) {
561 // .. or size if array
562 $argsString .= count($arg);
563 } elseif (is_object($arg)) {
565 $reflection = new ReflectionClass($arg);
567 // Is an other object, maybe no __toString() available
568 $argsString .= $reflection->getName();
569 } elseif ($arg === true) {
570 // ... is boolean 'true'
571 $argsString .= 'true';
572 } elseif ($arg === false) {
573 // ... is boolean 'false'
574 $argsString .= 'false';
577 // Comma for next one
582 if (substr($argsString, -2, 1) == ',') {
583 $argsString = substr($argsString, 0, -2);
589 // Invalid arguments!
590 $argsString = '!INVALID:' . gettype($args) . '!';
593 // Output stub message
594 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
595 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
605 * Getter for $realClass
607 * @return $realClass The name of the real class (not BaseFrameworkSystem)
609 public function __toString () {
610 return $this->realClass;
614 * Magic method to catch setting of missing but set class fields/attributes
616 * @param $name Name of the field/attribute
617 * @param $value Value to store
620 public final function __set ($name, $value) {
621 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
624 print_r($value, true)
629 * Magic method to catch getting of missing fields/attributes
631 * @param $name Name of the field/attribute
634 public final function __get ($name) {
635 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
641 * Magic method to catch unsetting of missing fields/attributes
643 * @param $name Name of the field/attribute
646 public final function __unset ($name) {
647 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
653 * Magic method to catch object serialization
655 * @return $unsupported Unsupported method
656 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
658 public final function __sleep () {
659 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
663 * Magic method to catch object deserialization
665 * @return $unsupported Unsupported method
666 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
668 public final function __wakeup () {
669 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
673 * Magic method to catch calls when an object instance is called
675 * @return $unsupported Unsupported method
676 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
678 public final function __invoke () {
679 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
683 * Setter for the real class name
685 * @param $realClass Class name (string)
688 public final function setRealClass ($realClass) {
690 $this->realClass = (string) $realClass;
694 * Setter for database result instance
696 * @param $resultInstance An instance of a database result class
698 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
700 protected final function setResultInstance (SearchableResult $resultInstance) {
701 $this->resultInstance = $resultInstance;
705 * Getter for database result instance
707 * @return $resultInstance An instance of a database result class
709 public final function getResultInstance () {
710 return $this->resultInstance;
714 * Setter for template engine instances
716 * @param $templateInstance An instance of a template engine class
719 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
720 $this->templateInstance = $templateInstance;
724 * Getter for template engine instances
726 * @return $templateInstance An instance of a template engine class
728 protected final function getTemplateInstance () {
729 return $this->templateInstance;
733 * Setter for search instance
735 * @param $searchInstance Searchable criteria instance
738 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
739 $this->searchInstance = $searchInstance;
743 * Getter for search instance
745 * @return $searchInstance Searchable criteria instance
747 public final function getSearchInstance () {
748 return $this->searchInstance;
752 * Setter for update instance
754 * @param $updateInstance An instance of a LocalUpdateCriteria clase
757 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
758 $this->updateInstance = $updateInstance;
762 * Getter for update instance
764 * @return $updateInstance Updateable criteria instance
766 public final function getUpdateInstance () {
767 return $this->updateInstance;
771 * Setter for resolver instance
773 * @param $resolverInstance Instance of a command resolver class
776 public final function setResolverInstance (Resolver $resolverInstance) {
777 $this->resolverInstance = $resolverInstance;
781 * Getter for resolver instance
783 * @return $resolverInstance Instance of a command resolver class
785 public final function getResolverInstance () {
786 return $this->resolverInstance;
790 * Setter for language instance
792 * @param $configInstance The configuration instance which shall
793 * be FrameworkConfiguration
796 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
797 Registry::getRegistry()->addInstance('config', $configInstance);
801 * Getter for configuration instance
803 * @return $configInstance Configuration instance
805 public final function getConfigInstance () {
806 $configInstance = Registry::getRegistry()->getInstance('config');
807 return $configInstance;
811 * Setter for debug instance
813 * @param $debugInstance The instance for debug output class
816 public final function setDebugInstance (DebugMiddleware $debugInstance) {
817 Registry::getRegistry()->addInstance('debug', $debugInstance);
821 * Getter for debug instance
823 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
825 public final function getDebugInstance () {
826 // Get debug instance
827 $debugInstance = Registry::getRegistry()->getInstance('debug');
830 return $debugInstance;
834 * Setter for web output instance
836 * @param $webInstance The instance for web output class
839 public final function setWebOutputInstance (OutputStreamer $webInstance) {
840 Registry::getRegistry()->addInstance('web_output', $webInstance);
844 * Getter for web output instance
846 * @return $webOutputInstance - Instance to class WebOutput
848 public final function getWebOutputInstance () {
849 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
850 return $webOutputInstance;
854 * Setter for database instance
856 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
859 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
860 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
864 * Getter for database layer
866 * @return $databaseInstance The database layer instance
868 public final function getDatabaseInstance () {
870 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
873 return $databaseInstance;
877 * Setter for compressor channel
879 * @param $compressorInstance An instance of CompressorChannel
882 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
883 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
887 * Getter for compressor channel
889 * @return $compressorInstance The compressor channel
891 public final function getCompressorChannel () {
892 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
893 return $compressorInstance;
897 * Protected getter for a manageable application helper class
899 * @return $applicationInstance An instance of a manageable application helper class
901 protected final function getApplicationInstance () {
902 $applicationInstance = Registry::getRegistry()->getInstance('app');
903 return $applicationInstance;
907 * Setter for a manageable application helper class
909 * @param $applicationInstance An instance of a manageable application helper class
912 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
913 Registry::getRegistry()->addInstance('application', $applicationInstance);
917 * Private getter for language instance
919 * @return $langInstance An instance to the language sub-system
921 protected final function getLanguageInstance () {
922 $langInstance = Registry::getRegistry()->getInstance('language');
923 return $langInstance;
927 * Setter for language instance
929 * @param $langInstance An instance to the language sub-system
931 * @see LanguageSystem
933 public final function setLanguageInstance (ManageableLanguage $langInstance) {
934 Registry::getRegistry()->addInstance('language', $langInstance);
938 * Private getter for file IO instance
940 * @return $fileIoInstance An instance to the file I/O sub-system
942 protected final function getFileIoInstance () {
943 return $this->fileIoInstance;
947 * Setter for file I/O instance
949 * @param $fileIoInstance An instance to the file I/O sub-system
952 public final function setFileIoInstance (IoHandler $fileIoInstance) {
953 $this->fileIoInstance = $fileIoInstance;
957 * Protected setter for user instance
959 * @param $userInstance An instance of a user class
962 protected final function setUserInstance (ManageableAccount $userInstance) {
963 $this->userInstance = $userInstance;
967 * Getter for user instance
969 * @return $userInstance An instance of a user class
971 public final function getUserInstance () {
972 return $this->userInstance;
976 * Setter for controller instance (this surely breaks a bit the MVC patterm)
978 * @param $controllerInstance An instance of the controller
981 public final function setControllerInstance (Controller $controllerInstance) {
982 $this->controllerInstance = $controllerInstance;
986 * Getter for controller instance (this surely breaks a bit the MVC patterm)
988 * @return $controllerInstance An instance of the controller
990 public final function getControllerInstance () {
991 return $this->controllerInstance;
995 * Setter for RNG instance
997 * @param $rngInstance An instance of a random number generator (RNG)
1000 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
1001 $this->rngInstance = $rngInstance;
1005 * Getter for RNG instance
1007 * @return $rngInstance An instance of a random number generator (RNG)
1009 public final function getRngInstance () {
1010 return $this->rngInstance;
1014 * Setter for Cryptable instance
1016 * @param $cryptoInstance An instance of a Cryptable class
1019 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1020 $this->cryptoInstance = $cryptoInstance;
1024 * Getter for Cryptable instance
1026 * @return $cryptoInstance An instance of a Cryptable class
1028 public final function getCryptoInstance () {
1029 return $this->cryptoInstance;
1033 * Setter for the list instance
1035 * @param $listInstance A list of Listable
1038 protected final function setListInstance (Listable $listInstance) {
1039 $this->listInstance = $listInstance;
1043 * Getter for the list instance
1045 * @return $listInstance A list of Listable
1047 protected final function getListInstance () {
1048 return $this->listInstance;
1052 * Setter for the menu instance
1054 * @param $menuInstance A RenderableMenu instance
1057 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1058 $this->menuInstance = $menuInstance;
1062 * Getter for the menu instance
1064 * @return $menuInstance A RenderableMenu instance
1066 protected final function getMenuInstance () {
1067 return $this->menuInstance;
1071 * Setter for image instance
1073 * @param $imageInstance An instance of an image
1076 public final function setImageInstance (BaseImage $imageInstance) {
1077 $this->imageInstance = $imageInstance;
1081 * Getter for image instance
1083 * @return $imageInstance An instance of an image
1085 public final function getImageInstance () {
1086 return $this->imageInstance;
1090 * Setter for stacker instance
1092 * @param $stackInstance An instance of an stacker
1095 public final function setStackInstance (Stackable $stackInstance) {
1096 $this->stackInstance = $stackInstance;
1100 * Getter for stacker instance
1102 * @return $stackInstance An instance of an stacker
1104 public final function getStackInstance () {
1105 return $this->stackInstance;
1109 * Setter for compressor instance
1111 * @param $compressorInstance An instance of an compressor
1114 public final function setCompressorInstance (Compressor $compressorInstance) {
1115 $this->compressorInstance = $compressorInstance;
1119 * Getter for compressor instance
1121 * @return $compressorInstance An instance of an compressor
1123 public final function getCompressorInstance () {
1124 return $this->compressorInstance;
1128 * Setter for Parseable instance
1130 * @param $parserInstance An instance of an Parseable
1133 public final function setParserInstance (Parseable $parserInstance) {
1134 $this->parserInstance = $parserInstance;
1138 * Getter for Parseable instance
1140 * @return $parserInstance An instance of an Parseable
1142 public final function getParserInstance () {
1143 return $this->parserInstance;
1147 * Setter for HandleableProtocol instance
1149 * @param $protocolInstance An instance of an HandleableProtocol
1152 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1153 $this->protocolInstance = $protocolInstance;
1157 * Getter for HandleableProtocol instance
1159 * @return $protocolInstance An instance of an HandleableProtocol
1161 public final function getProtocolInstance () {
1162 return $this->protocolInstance;
1166 * Setter for DatabaseWrapper instance
1168 * @param $wrapperInstance An instance of an DatabaseWrapper
1171 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1172 $this->wrapperInstance = $wrapperInstance;
1176 * Getter for DatabaseWrapper instance
1178 * @return $wrapperInstance An instance of an DatabaseWrapper
1180 public final function getWrapperInstance () {
1181 return $this->wrapperInstance;
1185 * Setter for socket resource
1187 * @param $socketResource A valid socket resource
1190 public final function setSocketResource ($socketResource) {
1191 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1192 $this->socketResource = $socketResource;
1196 * Getter for socket resource
1198 * @return $socketResource A valid socket resource
1200 public final function getSocketResource () {
1201 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1202 return $this->socketResource;
1206 * Setter for regular expression
1208 * @param $regularExpression A valid regular expression
1211 public final function setRegularExpression ($regularExpression) {
1212 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1213 $this->regularExpression = $regularExpression;
1217 * Getter for regular expression
1219 * @return $regularExpression A valid regular expression
1221 public final function getRegularExpression () {
1222 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1223 return $this->regularExpression;
1227 * Setter for helper instance
1229 * @param $helperInstance An instance of a helper class
1232 protected final function setHelperInstance (Helper $helperInstance) {
1233 $this->helperInstance = $helperInstance;
1237 * Getter for helper instance
1239 * @return $helperInstance An instance of a helper class
1241 public final function getHelperInstance () {
1242 return $this->helperInstance;
1246 * Setter for a Source instance
1248 * @param $sourceInstance An instance of a Source class
1251 protected final function setSourceInstance (Source $sourceInstance) {
1252 $this->sourceInstance = $sourceInstance;
1256 * Getter for a Source instance
1258 * @return $sourceInstance An instance of a Source class
1260 protected final function getSourceInstance () {
1261 return $this->sourceInstance;
1265 * Setter for a UrlSource instance
1267 * @param $sourceInstance An instance of a UrlSource class
1270 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1271 $this->urlSourceInstance = $urlSourceInstance;
1275 * Getter for a UrlSource instance
1277 * @return $urlSourceInstance An instance of a UrlSource class
1279 protected final function getUrlSourceInstance () {
1280 return $this->urlSourceInstance;
1284 * Getter for a InputStream instance
1286 * @param $inputStreamInstance The InputStream instance
1288 protected final function getInputStreamInstance () {
1289 return $this->inputStreamInstance;
1293 * Setter for a InputStream instance
1295 * @param $inputStreamInstance The InputStream instance
1298 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1299 $this->inputStreamInstance = $inputStreamInstance;
1303 * Getter for a OutputStream instance
1305 * @param $outputStreamInstance The OutputStream instance
1307 protected final function getOutputStreamInstance () {
1308 return $this->outputStreamInstance;
1312 * Setter for a OutputStream instance
1314 * @param $outputStreamInstance The OutputStream instance
1317 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1318 $this->outputStreamInstance = $outputStreamInstance;
1322 * Setter for handler instance
1324 * @param $handlerInstance An instance of a Handleable class
1327 protected final function setHandlerInstance (Handleable $handlerInstance) {
1328 $this->handlerInstance = $handlerInstance;
1332 * Getter for handler instance
1334 * @return $handlerInstance A Networkable instance
1336 protected final function getHandlerInstance () {
1337 return $this->handlerInstance;
1341 * Setter for visitor instance
1343 * @param $visitorInstance A Visitor instance
1346 protected final function setVisitorInstance (Visitor $visitorInstance) {
1347 $this->visitorInstance = $visitorInstance;
1351 * Getter for visitor instance
1353 * @return $visitorInstance A Visitor instance
1355 protected final function getVisitorInstance () {
1356 return $this->visitorInstance;
1360 * Setter for DHT instance
1362 * @param $dhtInstance A Distributable instance
1365 protected final function setDhtInstance (Distributable $dhtInstance) {
1366 $this->dhtInstance = $dhtInstance;
1370 * Getter for DHT instance
1372 * @return $dhtInstance A Distributable instance
1374 protected final function getDhtInstance () {
1375 return $this->dhtInstance;
1379 * Setter for raw package Data
1381 * @param $packageData Raw package Data
1384 public final function setPackageData (array $packageData) {
1385 $this->packageData = $packageData;
1389 * Getter for raw package Data
1391 * @return $packageData Raw package Data
1393 public function getPackageData () {
1394 return $this->packageData;
1399 * Setter for Iterator instance
1401 * @param $iteratorInstance An instance of an Iterator
1404 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1405 $this->iteratorInstance = $iteratorInstance;
1409 * Getter for Iterator instance
1411 * @return $iteratorInstance An instance of an Iterator
1413 public final function getIteratorInstance () {
1414 return $this->iteratorInstance;
1418 * Setter for FilePointer instance
1420 * @param $pointerInstance An instance of an FilePointer class
1423 protected final function setPointerInstance (FilePointer $pointerInstance) {
1424 $this->pointerInstance = $pointerInstance;
1428 * Getter for FilePointer instance
1430 * @return $pointerInstance An instance of an FilePointer class
1432 public final function getPointerInstance () {
1433 return $this->pointerInstance;
1437 * Unsets pointer instance which triggers a call of __destruct() if the
1438 * instance is still there. This is surely not fatal on already "closed"
1439 * file pointer instances.
1441 * I don't want to mess around with above setter by giving it a default
1442 * value NULL as setter should always explicitly only set (existing) object
1443 * instances and NULL is NULL.
1447 protected final function unsetPointerInstance () {
1448 // Simply it to NULL
1449 $this->pointerInstance = NULL;
1453 * Setter for Indexable instance
1455 * @param $indexInstance An instance of an Indexable class
1458 protected final function setIndexInstance (Indexable $indexInstance) {
1459 $this->indexInstance = $indexInstance;
1463 * Getter for Indexable instance
1465 * @return $indexInstance An instance of an Indexable class
1467 public final function getIndexInstance () {
1468 return $this->indexInstance;
1472 * Setter for Block instance
1474 * @param $blockInstance An instance of an Block class
1477 protected final function setBlockInstance (Block $blockInstance) {
1478 $this->blockInstance = $blockInstance;
1482 * Getter for Block instance
1484 * @return $blockInstance An instance of an Block class
1486 public final function getBlockInstance () {
1487 return $this->blockInstance;
1491 * Setter for Minable instance
1493 * @param $minableInstance A Minable instance
1496 protected final function setMinableInstance (Minable $minableInstance) {
1497 $this->minableInstance = $minableInstance;
1501 * Getter for minable instance
1503 * @return $minableInstance A Minable instance
1505 protected final function getMinableInstance () {
1506 return $this->minableInstance;
1510 * Setter for FrameworkDirectory instance
1512 * @param $directoryInstance A FrameworkDirectory instance
1515 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1516 $this->directoryInstance = $directoryInstance;
1520 * Getter for FrameworkDirectory instance
1522 * @return $directoryInstance A FrameworkDirectory instance
1524 protected final function getDirectoryInstance () {
1525 return $this->directoryInstance;
1529 * Setter for listener instance
1531 * @param $listenerInstance A Listenable instance
1534 protected final function setListenerInstance (Listenable $listenerInstance) {
1535 $this->listenerInstance = $listenerInstance;
1539 * Getter for listener instance
1541 * @return $listenerInstance A Listenable instance
1543 protected final function getListenerInstance () {
1544 return $this->listenerInstance;
1548 * Getter for communicator instance
1550 * @return $communicatorInstance An instance of a Communicator class
1552 public final function getCommunicatorInstance () {
1553 return $this->communicatorInstance;
1557 * Setter for communicator instance
1559 * @param $communicatorInstance An instance of a Communicator class
1562 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1563 $this->communicatorInstance = $communicatorInstance;
1567 * Setter for state instance
1569 * @param $stateInstance A Stateable instance
1572 public final function setStateInstance (Stateable $stateInstance) {
1573 $this->stateInstance = $stateInstance;
1577 * Getter for state instance
1579 * @return $stateInstance A Stateable instance
1581 public final function getStateInstance () {
1582 return $this->stateInstance;
1586 * Setter for output instance
1588 * @param $outputInstance The debug output instance
1591 public final function setOutputInstance (OutputStreamer $outputInstance) {
1592 $this->outputInstance = $outputInstance;
1596 * Getter for output instance
1598 * @return $outputInstance The debug output instance
1600 public final function getOutputInstance () {
1601 return $this->outputInstance;
1605 * Setter for command name
1607 * @param $commandName Last validated command name
1610 protected final function setCommandName ($commandName) {
1611 $this->commandName = $commandName;
1615 * Getter for command name
1617 * @return $commandName Last validated command name
1619 protected final function getCommandName () {
1620 return $this->commandName;
1624 * Setter for controller name
1626 * @param $controllerName Last validated controller name
1629 protected final function setControllerName ($controllerName) {
1630 $this->controllerName = $controllerName;
1634 * Getter for controller name
1636 * @return $controllerName Last validated controller name
1638 protected final function getControllerName () {
1639 return $this->controllerName;
1643 * Getter for protocol name
1645 * @return $protocolName Name of used protocol
1647 public final function getProtocolName () {
1648 return $this->protocolName;
1652 * Setter for protocol name
1654 * @param $protocolName Name of used protocol
1657 protected final function setProtocolName ($protocolName) {
1658 $this->protocolName = $protocolName;
1662 * Checks whether an object equals this object. You should overwrite this
1663 * method to implement own equality checks
1665 * @param $objectInstance An instance of a FrameworkInterface object
1666 * @return $equals Whether both objects equals
1668 public function equals (FrameworkInterface $objectInstance) {
1671 $this->__toString() == $objectInstance->__toString()
1673 $this->hashCode() == $objectInstance->hashCode()
1676 // Return the result
1681 * Generates a generic hash code of this class. You should really overwrite
1682 * this method with your own hash code generator code. But keep KISS in mind.
1684 * @return $hashCode A generic hash code respresenting this whole class
1686 public function hashCode () {
1688 return crc32($this->__toString());
1692 * Formats computer generated price values into human-understandable formats
1693 * with thousand and decimal separators.
1695 * @param $value The in computer format value for a price
1696 * @param $currency The currency symbol (use HTML-valid characters!)
1697 * @param $decNum Number of decimals after commata
1698 * @return $price The for the current language formated price string
1699 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1700 * thousands separator
1703 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1704 // Are all required attriutes set?
1705 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1706 // Throw an exception
1707 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1711 $value = (float) $value;
1713 // Reformat the US number
1714 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1716 // Return as string...
1721 * Appends a trailing slash to a string
1723 * @param $str A string (maybe) without trailing slash
1724 * @return $str A string with an auto-appended trailing slash
1726 public final function addMissingTrailingSlash ($str) {
1727 // Is there a trailing slash?
1728 if (substr($str, -1, 1) != '/') {
1732 // Return string with trailing slash
1737 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1738 * application helper instance (ApplicationHelper by default).
1740 * @param $applicationInstance An application helper instance or
1741 * null if we shall use the default
1742 * @return $templateInstance The template engine instance
1743 * @throws NullPointerException If the discovered application
1744 * instance is still null
1746 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1747 // Is the application instance set?
1748 if (is_null($applicationInstance)) {
1749 // Get the current instance
1750 $applicationInstance = Registry::getRegistry()->getInstance('app');
1753 if (is_null($applicationInstance)) {
1754 // Thrown an exception
1755 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1759 // Initialize the template engine
1760 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1762 // Return the prepared instance
1763 return $templateInstance;
1767 * Debugs this instance by putting out it's full content
1769 * @param $message Optional message to show in debug output
1772 public final function debugInstance ($message = '') {
1773 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1774 restore_error_handler();
1779 // Is a message set?
1780 if (!empty($message)) {
1781 // Construct message
1782 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1785 // Generate the output
1786 $content .= sprintf('<pre>%s</pre>',
1789 print_r($this, true)
1795 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>',
1796 $this->__toString(),
1798 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1803 * Replaces control characters with printable output
1805 * @param $str String with control characters
1806 * @return $str Replaced string
1808 protected function replaceControlCharacters ($str) {
1811 chr(13), '[r]', str_replace(
1812 chr(10), '[n]', str_replace(
1822 * Output a partial stub message for the caller method
1824 * @param $message An optional message to display
1827 protected function partialStub ($message = '') {
1828 // Get the backtrace
1829 $backtrace = debug_backtrace();
1831 // Generate the class::method string
1832 $methodName = 'UnknownClass->unknownMethod';
1833 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1834 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1837 // Construct the full message
1838 $stubMessage = sprintf('[%s:] Partial stub!',
1842 // Is the extra message given?
1843 if (!empty($message)) {
1844 // Then add it as well
1845 $stubMessage .= ' Message: ' . $message;
1848 // Debug instance is there?
1849 if (!is_null($this->getDebugInstance())) {
1850 // Output stub message
1851 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1854 trigger_error($stubMessage);
1860 * Outputs a debug backtrace and stops further script execution
1862 * @param $message An optional message to output
1863 * @param $doExit Whether exit the program (true is default)
1866 public function debugBackTrace ($message = '', $doExit = true) {
1867 // Sorry, there is no other way getting this nice backtrace
1868 if (!empty($message)) {
1870 printf('Message: %s<br />' . PHP_EOL, $message);
1874 debug_print_backtrace();
1878 if ($doExit === true) {
1884 * Creates an instance of a debugger instance
1886 * @param $className Name of the class (currently unsupported)
1887 * @param $lineNumber Line number where the call was made
1888 * @return $debugInstance An instance of a debugger class
1889 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1891 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1892 // Is the instance set?
1893 if (!Registry::getRegistry()->instanceExists('debug')) {
1894 // Init debug instance
1895 $debugInstance = NULL;
1899 // Get a debugger instance
1900 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1901 } catch (NullPointerException $e) {
1902 // Didn't work, no instance there
1903 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1906 // Empty string should be ignored and used for testing the middleware
1907 DebugMiddleware::getSelfInstance()->output('');
1909 // Set it in its own class. This will set it in the registry
1910 $debugInstance->setDebugInstance($debugInstance);
1912 // Get instance from registry
1913 $debugInstance = Registry::getRegistry()->getDebugInstance();
1917 return $debugInstance;
1921 * Simple output of a message with line-break
1923 * @param $message Message to output
1926 public function outputLine ($message) {
1928 print($message . PHP_EOL);
1932 * Outputs a debug message whether to debug instance (should be set!) or
1933 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1934 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1936 * @param $message Message we shall send out...
1937 * @param $doPrint Whether print or die here (default: print)
1938 * @paran $stripTags Whether to strip tags (default: false)
1941 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1942 // Set debug instance to NULL
1943 $debugInstance = NULL;
1947 // Get debug instance
1948 $debugInstance = $this->getDebugInstance();
1949 } catch (NullPointerException $e) {
1950 // The debug instance is not set (yet)
1953 // Is the debug instance there?
1954 if (is_object($debugInstance)) {
1955 // Use debug output handler
1956 $debugInstance->output($message, $stripTags);
1958 if ($doPrint === false) {
1959 // Die here if not printed
1963 // Are debug times enabled?
1964 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1966 $message = $this->getPrintableExecutionTime() . $message;
1970 if ($doPrint === true) {
1972 $this->outputLine($message);
1981 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1983 * @param $str The string, what ever it is needs to be converted
1984 * @return $className Generated class name
1986 public static final function convertToClassName ($str) {
1990 // Convert all dashes in underscores
1991 $str = self::convertDashesToUnderscores($str);
1993 // Now use that underscores to get classname parts for hungarian style
1994 foreach (explode('_', $str) as $strPart) {
1995 // Make the class name part lower case and first upper case
1996 $className .= ucfirst(strtolower($strPart));
1999 // Return class name
2004 * Converts dashes to underscores, e.g. useable for configuration entries
2006 * @param $str The string with maybe dashes inside
2007 * @return $str The converted string with no dashed, but underscores
2009 public static final function convertDashesToUnderscores ($str) {
2011 $str = str_replace('-', '_', $str);
2013 // Return converted string
2018 * Marks up the code by adding e.g. line numbers
2020 * @param $phpCode Unmarked PHP code
2021 * @return $markedCode Marked PHP code
2023 public function markupCode ($phpCode) {
2028 $errorArray = error_get_last();
2030 // Init the code with error message
2031 if (is_array($errorArray)) {
2033 $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>',
2034 basename($errorArray['file']),
2035 $errorArray['line'],
2036 $errorArray['message'],
2041 // Add line number to the code
2042 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2044 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2046 htmlentities($code, ENT_QUOTES)
2055 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2056 * beatiful for web-based front-ends. If null is given a message id
2057 * null_timestamp will be resolved and returned.
2059 * @param $timestamp Timestamp to prepare (filter) for display
2060 * @return $readable A readable timestamp
2062 public function doFilterFormatTimestamp ($timestamp) {
2063 // Default value to return
2066 // Is the timestamp null?
2067 if (is_null($timestamp)) {
2068 // Get a message string
2069 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2071 switch ($this->getLanguageInstance()->getLanguageCode()) {
2072 case 'de': // German format is a bit different to default
2073 // Split the GMT stamp up
2074 $dateTime = explode(' ', $timestamp );
2075 $dateArray = explode('-', $dateTime[0]);
2076 $timeArray = explode(':', $dateTime[1]);
2078 // Construct the timestamp
2079 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2089 default: // Default is pass-through
2090 $readable = $timestamp;
2100 * Filter a given number into a localized number
2102 * @param $value The raw value from e.g. database
2103 * @return $localized Localized value
2105 public function doFilterFormatNumber ($value) {
2106 // Generate it from config and localize dependencies
2107 switch ($this->getLanguageInstance()->getLanguageCode()) {
2108 case 'de': // German format is a bit different to default
2109 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2112 default: // US, etc.
2113 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2122 * "Getter" for databse entry
2124 * @return $entry An array with database entries
2125 * @throws NullPointerException If the database result is not found
2126 * @throws InvalidDatabaseResultException If the database result is invalid
2128 protected final function getDatabaseEntry () {
2129 // Is there an instance?
2130 if (!$this->getResultInstance() instanceof SearchableResult) {
2131 // Throw an exception here
2132 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2136 $this->getResultInstance()->rewind();
2138 // Do we have an entry?
2139 if ($this->getResultInstance()->valid() === false) {
2140 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2141 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2145 $this->getResultInstance()->next();
2148 $entry = $this->getResultInstance()->current();
2155 * Getter for field name
2157 * @param $fieldName Field name which we shall get
2158 * @return $fieldValue Field value from the user
2159 * @throws NullPointerException If the result instance is null
2161 public final function getField ($fieldName) {
2162 // Default field value
2165 // Get result instance
2166 $resultInstance = $this->getResultInstance();
2168 // Is this instance null?
2169 if (is_null($resultInstance)) {
2170 // Then the user instance is no longer valid (expired cookies?)
2171 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2174 // Get current array
2175 $fieldArray = $resultInstance->current();
2176 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2178 // Convert dashes to underscore
2179 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2181 // Does the field exist?
2182 if ($this->isFieldSet($fieldName)) {
2184 $fieldValue = $fieldArray[$fieldName2];
2185 } elseif (defined('DEVELOPER')) {
2186 // Missing field entry, may require debugging
2187 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2189 // Missing field entry, may require debugging
2190 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2198 * Checks if given field is set
2200 * @param $fieldName Field name to check
2201 * @return $isSet Whether the given field name is set
2202 * @throws NullPointerException If the result instance is null
2204 public function isFieldSet ($fieldName) {
2205 // Get result instance
2206 $resultInstance = $this->getResultInstance();
2208 // Is this instance null?
2209 if (is_null($resultInstance)) {
2210 // Then the user instance is no longer valid (expired cookies?)
2211 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2214 // Get current array
2215 $fieldArray = $resultInstance->current();
2216 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2218 // Convert dashes to underscore
2219 $fieldName = self::convertDashesToUnderscores($fieldName);
2222 $isSet = isset($fieldArray[$fieldName]);
2229 * Flushs all pending updates to the database layer
2233 public function flushPendingUpdates () {
2234 // Get result instance
2235 $resultInstance = $this->getResultInstance();
2237 // Do we have data to update?
2238 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2239 // Get wrapper class name config entry
2240 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2242 // Create object instance
2243 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2245 // Yes, then send the whole result to the database layer
2246 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2251 * Outputs a deprecation warning to the developer.
2253 * @param $message The message we shall output to the developer
2255 * @todo Write a logging mechanism for productive mode
2257 public function deprecationWarning ($message) {
2258 // Is developer mode active?
2259 if (defined('DEVELOPER')) {
2260 // Debug instance is there?
2261 if (!is_null($this->getDebugInstance())) {
2262 // Output stub message
2263 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2266 trigger_error($message . "<br />\n");
2270 // @TODO Finish this part!
2271 $this->partialStub('Developer mode inactive. Message:' . $message);
2276 * Checks whether the given PHP extension is loaded
2278 * @param $phpExtension The PHP extension we shall check
2279 * @return $isLoaded Whether the PHP extension is loaded
2281 public final function isPhpExtensionLoaded ($phpExtension) {
2283 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2290 * "Getter" as a time() replacement but with milliseconds. You should use this
2291 * method instead of the encapsulated getimeofday() function.
2293 * @return $milliTime Timestamp with milliseconds
2295 public function getMilliTime () {
2296 // Get the time of day as float
2297 $milliTime = gettimeofday(true);
2304 * Idles (sleeps) for given milliseconds
2306 * @return $hasSlept Whether it goes fine
2308 public function idle ($milliSeconds) {
2309 // Sleep is fine by default
2312 // Idle so long with found function
2313 if (function_exists('time_sleep_until')) {
2314 // Get current time and add idle time
2315 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2317 // New PHP 5.1.0 function found, ignore errors
2318 $hasSlept = @time_sleep_until($sleepUntil);
2321 * My Sun station doesn't have that function even with latest PHP
2324 usleep($milliSeconds * 1000);
2331 * Converts a hexadecimal string, even with negative sign as first string to
2332 * a decimal number using BC functions.
2334 * This work is based on comment #86673 on php.net documentation page at:
2335 * <http://de.php.net/manual/en/function.dechex.php#86673>
2337 * @param $hex Hexadecimal string
2338 * @return $dec Decimal number
2340 protected function hex2dec ($hex) {
2341 // Convert to all lower-case
2342 $hex = strtolower($hex);
2344 // Detect sign (negative/positive numbers)
2346 if (substr($hex, 0, 1) == '-') {
2348 $hex = substr($hex, 1);
2351 // Decode the hexadecimal string into a decimal number
2353 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2354 $factor = self::$hexdec[substr($hex, $i, 1)];
2355 $dec = bcadd($dec, bcmul($factor, $e));
2358 // Return the decimal number
2359 return $sign . $dec;
2363 * Converts even very large decimal numbers, also signed, to a hexadecimal
2366 * This work is based on comment #97756 on php.net documentation page at:
2367 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2369 * @param $dec Decimal number, even with negative sign
2370 * @param $maxLength Optional maximum length of the string
2371 * @return $hex Hexadecimal string
2373 protected function dec2hex ($dec, $maxLength = 0) {
2374 // maxLength can be zero or devideable by 2
2375 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2377 // Detect sign (negative/positive numbers)
2384 // Encode the decimal number into a hexadecimal string
2387 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2389 } while ($dec >= 1);
2392 * Leading zeros are required for hex-decimal "numbers". In some
2393 * situations more leading zeros are wanted, so check for both
2396 if ($maxLength > 0) {
2397 // Prepend more zeros
2398 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2399 } elseif ((strlen($hex) % 2) != 0) {
2400 // Only make string's length dividable by 2
2404 // Return the hexadecimal string
2405 return $sign . $hex;
2409 * Converts a ASCII string (0 to 255) into a decimal number.
2411 * @param $asc The ASCII string to be converted
2412 * @return $dec Decimal number
2414 protected function asc2dec ($asc) {
2415 // Convert it into a hexadecimal number
2416 $hex = bin2hex($asc);
2418 // And back into a decimal number
2419 $dec = $this->hex2dec($hex);
2426 * Converts a decimal number into an ASCII string.
2428 * @param $dec Decimal number
2429 * @return $asc An ASCII string
2431 protected function dec2asc ($dec) {
2432 // First convert the number into a hexadecimal string
2433 $hex = $this->dec2hex($dec);
2435 // Then convert it into the ASCII string
2436 $asc = $this->hex2asc($hex);
2443 * Converts a hexadecimal number into an ASCII string. Negative numbers
2446 * @param $hex Hexadecimal string
2447 * @return $asc An ASCII string
2449 protected function hex2asc ($hex) {
2450 // Check for length, it must be devideable by 2
2451 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2452 assert((strlen($hex) % 2) == 0);
2456 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2457 // Get the decimal number of the chunk
2458 $part = hexdec(substr($hex, $idx, 2));
2460 // Add it to the final string
2464 // Return the final string
2469 * Checks whether the given encoded data was encoded with Base64
2471 * @param $encodedData Encoded data we shall check
2472 * @return $isBase64 Whether the encoded data is Base64
2474 protected function isBase64Encoded ($encodedData) {
2476 $isBase64 = (@base64_decode($encodedData, true) !== false);
2483 * Gets a cache key from Criteria instance
2485 * @param $criteriaInstance An instance of a Criteria class
2486 * @param $onlyKeys Only use these keys for a cache key
2487 * @return $cacheKey A cache key suitable for lookup/storage purposes
2489 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2491 $cacheKey = sprintf('%s@%s',
2492 $this->__toString(),
2493 $criteriaInstance->getCacheKey($onlyKeys)
2497 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2502 * Getter for startup time in miliseconds
2504 * @return $startupTime Startup time in miliseconds
2506 protected function getStartupTime () {
2507 return self::$startupTime;
2511 * "Getter" for a printable currently execution time in nice braces
2513 * @return $executionTime Current execution time in nice braces
2515 protected function getPrintableExecutionTime () {
2516 // Caculate the execution time
2517 $executionTime = microtime(true) - $this->getStartupTime();
2519 // Pack it in nice braces
2520 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2523 return $executionTime;
2527 * Hashes a given string with a simple but stronger hash function (no salt)
2528 * and hex-encode it.
2530 * @param $str The string to be hashed
2531 * @return $hash The hash from string $str
2533 public static final function hash ($str) {
2534 // Hash given string with (better secure) hasher
2535 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2542 * "Getter" for length of hash() output. This will be "cached" to speed up
2545 * @return $length Length of hash() output
2547 public static final function getHashLength () {
2549 if (is_null(self::$hashLength)) {
2550 // No, then hash a string and save its length.
2551 self::$hashLength = strlen(self::hash('abc123'));
2555 return self::$hashLength;
2559 * Checks whether the given number is really a number (only chars 0-9).
2561 * @param $num A string consisting only chars between 0 and 9
2562 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2563 * @param $assertMismatch Whether to assert mismatches
2564 * @return $ret The (hopefully) secured numbered value
2566 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2567 // Filter all numbers out
2568 $ret = preg_replace('/[^0123456789]/', '', $num);
2571 if ($castValue === true) {
2572 // Cast to biggest numeric type
2573 $ret = (double) $ret;
2576 // Assert only if requested
2577 if ($assertMismatch === true) {
2578 // Has the whole value changed?
2579 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2587 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2589 * @param $num A string consisting only chars between 0 and 9
2590 * @param $assertMismatch Whether to assert mismatches
2591 * @return $ret The (hopefully) secured hext-numbered value
2593 public function hexval ($num, $assertMismatch = false) {
2594 // Filter all numbers out
2595 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2597 // Assert only if requested
2598 if ($assertMismatch === true) {
2599 // Has the whole value changed?
2600 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2608 * Checks whether start/end marker are set
2610 * @param $data Data to be checked
2611 * @return $isset Whether start/end marker are set
2613 public final function ifStartEndMarkersSet ($data) {
2615 $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));
2617 // ... and return it
2622 * Determines if an element is set in the generic array
2624 * @param $keyGroup Main group for the key
2625 * @param $subGroup Sub group for the key
2626 * @param $key Key to check
2627 * @param $element Element to check
2628 * @return $isset Whether the given key is set
2630 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2632 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2635 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2641 * Determines if a key is set in the generic array
2643 * @param $keyGroup Main group for the key
2644 * @param $subGroup Sub group for the key
2645 * @param $key Key to check
2646 * @return $isset Whether the given key is set
2648 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2650 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2653 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2661 * Determines if a group is set in the generic array
2663 * @param $keyGroup Main group
2664 * @param $subGroup Sub group
2665 * @return $isset Whether the given group is set
2667 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2669 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2672 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2679 * Getter for sub key group
2681 * @param $keyGroup Main key group
2682 * @param $subGroup Sub key group
2683 * @return $array An array with all array elements
2685 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2687 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2688 // No, then abort here
2689 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2694 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2697 return $this->genericArray[$keyGroup][$subGroup];
2701 * Unsets a given key in generic array
2703 * @param $keyGroup Main group for the key
2704 * @param $subGroup Sub group for the key
2705 * @param $key Key to unset
2708 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2710 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2713 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2717 * Unsets a given element in generic array
2719 * @param $keyGroup Main group for the key
2720 * @param $subGroup Sub group for the key
2721 * @param $key Key to unset
2722 * @param $element Element to unset
2725 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2727 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2730 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2734 * Append a string to a given generic array key
2736 * @param $keyGroup Main group for the key
2737 * @param $subGroup Sub group for the key
2738 * @param $key Key to unset
2739 * @param $value Value to add/append
2742 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2744 //* 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);
2746 // Is it already there?
2747 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2749 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2752 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2757 * Append a string to a given generic array element
2759 * @param $keyGroup Main group for the key
2760 * @param $subGroup Sub group for the key
2761 * @param $key Key to unset
2762 * @param $element Element to check
2763 * @param $value Value to add/append
2766 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2768 //* 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);
2770 // Is it already there?
2771 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2773 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2776 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2781 * Sets a string in a given generic array element
2783 * @param $keyGroup Main group for the key
2784 * @param $subGroup Sub group for the key
2785 * @param $key Key to unset
2786 * @param $element Element to check
2787 * @param $value Value to add/append
2790 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2792 //* 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);
2795 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2799 * Initializes given generic array group
2801 * @param $keyGroup Main group for the key
2802 * @param $subGroup Sub group for the key
2803 * @param $key Key to use
2804 * @param $forceInit Optionally force initialization
2807 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2809 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2811 // Is it already set?
2812 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2813 // Already initialized
2814 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2819 $this->genericArray[$keyGroup][$subGroup] = array();
2823 * Initializes given generic array key
2825 * @param $keyGroup Main group for the key
2826 * @param $subGroup Sub group for the key
2827 * @param $key Key to use
2828 * @param $forceInit Optionally force initialization
2831 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2833 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2835 // Is it already set?
2836 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2837 // Already initialized
2838 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2843 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2847 * Initializes given generic array element
2849 * @param $keyGroup Main group for the key
2850 * @param $subGroup Sub group for the key
2851 * @param $key Key to use
2852 * @param $element Element to use
2853 * @param $forceInit Optionally force initialization
2856 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2858 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2860 // Is it already set?
2861 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2862 // Already initialized
2863 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2868 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2872 * Pushes an element to a generic key
2874 * @param $keyGroup Main group for the key
2875 * @param $subGroup Sub group for the key
2876 * @param $key Key to use
2877 * @param $value Value to add/append
2878 * @return $count Number of array elements
2880 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2882 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2885 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2887 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2891 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2894 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2895 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2900 * Pushes an element to a generic array element
2902 * @param $keyGroup Main group for the key
2903 * @param $subGroup Sub group for the key
2904 * @param $key Key to use
2905 * @param $element Element to check
2906 * @param $value Value to add/append
2907 * @return $count Number of array elements
2909 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2911 //* 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));
2914 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2916 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2920 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2923 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2924 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2929 * Pops an element from a generic group
2931 * @param $keyGroup Main group for the key
2932 * @param $subGroup Sub group for the key
2933 * @param $key Key to unset
2934 * @return $value Last "popped" value
2936 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2938 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2941 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2943 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2948 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2951 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2952 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2957 * Shifts an element from a generic group
2959 * @param $keyGroup Main group for the key
2960 * @param $subGroup Sub group for the key
2961 * @param $key Key to unset
2962 * @return $value Last "popped" value
2964 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2966 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2969 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2971 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2976 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2979 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2980 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2985 * Count generic array group
2987 * @param $keyGroup Main group for the key
2988 * @return $count Count of given group
2990 protected final function countGenericArray ($keyGroup) {
2992 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2995 if (!isset($this->genericArray[$keyGroup])) {
2997 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3002 $count = count($this->genericArray[$keyGroup]);
3005 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3012 * Count generic array sub group
3014 * @param $keyGroup Main group for the key
3015 * @param $subGroup Sub group for the key
3016 * @return $count Count of given group
3018 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3020 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3023 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3025 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3030 $count = count($this->genericArray[$keyGroup][$subGroup]);
3033 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3040 * Count generic array elements
3042 * @param $keyGroup Main group for the key
3043 * @param $subGroup Sub group for the key
3044 * @para $key Key to count
3045 * @return $count Count of given key
3047 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3049 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3052 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3054 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3056 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3058 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3063 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3066 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3073 * Getter for whole generic group array
3075 * @param $keyGroup Key group to get
3076 * @return $array Whole generic array group
3078 protected final function getGenericArray ($keyGroup) {
3080 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3083 if (!isset($this->genericArray[$keyGroup])) {
3085 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3090 return $this->genericArray[$keyGroup];
3094 * Setter for generic array key
3096 * @param $keyGroup Key group to get
3097 * @param $subGroup Sub group for the key
3098 * @param $key Key to unset
3099 * @param $value Mixed value from generic array element
3102 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3104 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3107 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3111 * Getter for generic array key
3113 * @param $keyGroup Key group to get
3114 * @param $subGroup Sub group for the key
3115 * @param $key Key to unset
3116 * @return $value Mixed value from generic array element
3118 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3120 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3123 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3125 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3130 return $this->genericArray[$keyGroup][$subGroup][$key];
3134 * Sets a value in given generic array key/element
3136 * @param $keyGroup Main group for the key
3137 * @param $subGroup Sub group for the key
3138 * @param $key Key to set
3139 * @param $element Element to set
3140 * @param $value Value to set
3143 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3145 //* 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));
3148 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3152 * Getter for generic array element
3154 * @param $keyGroup Key group to get
3155 * @param $subGroup Sub group for the key
3156 * @param $key Key to look for
3157 * @param $element Element to look for
3158 * @return $value Mixed value from generic array element
3160 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3162 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3165 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3167 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3172 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3176 * Checks if a given sub group is valid (array)
3178 * @param $keyGroup Key group to get
3179 * @param $subGroup Sub group for the key
3180 * @return $isValid Whether given sub group is valid
3182 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3184 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3187 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3194 * Checks if a given key is valid (array)
3196 * @param $keyGroup Key group to get
3197 * @param $subGroup Sub group for the key
3198 * @param $key Key to check
3199 * @return $isValid Whether given sub group is valid
3201 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3203 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3206 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3213 * Initializes the web output instance
3217 protected function initWebOutputInstance () {
3218 // Get application instance
3219 $applicationInstance = Registry::getRegistry()->getInstance('app');
3221 // Init web output instance
3222 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3225 $this->setWebOutputInstance($outputInstance);
3229 * Translates boolean true to 'Y' and false to 'N'
3231 * @param $boolean Boolean value
3232 * @return $translated Translated boolean value
3234 public static final function translateBooleanToYesNo ($boolean) {
3235 // Make sure it is really boolean
3236 assert(is_bool($boolean));
3239 $translated = ($boolean === true) ? 'Y' : 'N';
3241 // ... and return it
3246 * Encodes raw data (almost any type) by "serializing" it and then pack it
3247 * into a "binary format".
3249 * @param $rawData Raw data (almost any type)
3250 * @return $encoded Encoded data
3252 protected function encodeData ($rawData) {
3253 // Make sure no objects or resources pass through
3254 assert(!is_object($rawData));
3255 assert(!is_resource($rawData));
3257 // First "serialize" it (json_encode() is faster than serialize())
3258 $encoded = $this->packString(json_encode($rawData));
3265 * Pack a string into a "binary format". Please execuse me that this is
3266 * widely undocumented. :-(
3268 * @param $str Unpacked string
3269 * @return $packed Packed string
3270 * @todo Improve documentation
3272 protected function packString ($str) {
3274 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3276 // First compress the string (gzcompress is okay)
3277 $str = gzcompress($str);
3282 // And start the "encoding" loop
3283 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3285 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3286 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3288 if (($idx + $i) <= strlen($str)) {
3289 $ord = ord(substr($str, ($idx + $i), 1));
3291 $add = $ord * pow(256, $factor);
3295 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3299 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3300 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3302 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3303 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3309 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3314 * Creates a full-qualified file name (FQFN) for given file name by adding
3315 * a configured temporary file path to it.
3317 * @param $fileName Name for temporary file
3318 * @return $fqfn Full-qualified file name
3319 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3320 * @throws FileIoException If the file cannot be written
3322 protected static function createTempPathForFile ($fileName) {
3324 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3326 // Is the path writeable?
3327 if (!is_writable($basePath)) {
3328 // Path is write-protected
3329 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3333 $fqfn = $basePath . '/' . $fileName;
3336 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3338 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3346 * "Getter" for a printable state name
3348 * @return $stateName Name of the node's state in a printable format
3350 public final function getPrintableState () {
3351 // Default is 'null'
3352 $stateName = 'null';
3354 // Get the state instance
3355 $stateInstance = $this->getStateInstance();
3357 // Is it an instance of Stateable?
3358 if ($stateInstance instanceof Stateable) {
3359 // Then use that state name
3360 $stateName = $stateInstance->getStateName();
3368 * Handles socket error for given socket resource and peer data. This method
3369 * validates $socketResource if it is a valid resource (see is_resource())
3370 * but assumes valid data in array $recipientData, except that
3371 * count($recipientData) is always 2.
3373 * @param $method Value of __METHOD__ from calling method
3374 * @param $line Value of __LINE__ from calling method
3375 * @param $socketResource A valid socket resource
3376 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3378 * @throws InvalidSocketException If $socketResource is no socket resource
3379 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3380 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3382 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3383 // This method handles only socket resources
3384 if (!is_resource($socketResource)) {
3385 // No resource, abort here
3386 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3389 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3390 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, true));
3391 assert(isset($socketData[0]));
3392 assert(isset($socketData[1]));
3394 // Get error code for first validation (0 is not an error)
3395 $errorCode = socket_last_error($socketResource);
3397 // If the error code is zero, someone called this method without an error
3398 if ($errorCode == 0) {
3399 // No error detected (or previously cleared outside this method)
3400 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3403 // Get handler (method) name
3404 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3406 // Call-back the error handler method
3407 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3409 // Finally clear the error because it has been handled
3410 socket_clear_error($socketResource);