3 namespace Org\Mxchange\CoreFramework\Object;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Compressor\Compressor;
8 use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
9 use Org\Mxchange\CoreFramework\Connection\Database\DatabaseConnection;
10 use Org\Mxchange\CoreFramework\Criteria\Criteria;
11 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
12 use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
13 use Org\Mxchange\CoreFramework\Crypto\Cryptable;
14 use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
15 use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
16 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
17 use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
18 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
19 use Org\Mxchange\CoreFramework\Filesystem\Block;
20 use Org\Mxchange\CoreFramework\Filesystem\FilePointer;
21 use Org\Mxchange\CoreFramework\Filesystem\FrameworkDirectory;
22 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
23 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
24 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
25 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
26 use Org\Mxchange\CoreFramework\Handler\Handleable;
27 use Org\Mxchange\CoreFramework\Helper\Helper;
28 use Org\Mxchange\CoreFramework\Index\Indexable;
29 use Org\Mxchange\CoreFramework\Lists\Listable;
30 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
31 use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
32 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
33 use Org\Mxchange\CoreFramework\Menu\RenderableMenu;
34 use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
35 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
36 use Org\Mxchange\CoreFramework\Parser\Parseable;
37 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
38 use Org\Mxchange\CoreFramework\Registry\Register;
39 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
40 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
41 use Org\Mxchange\CoreFramework\Stacker\Stackable;
42 use Org\Mxchange\CoreFramework\State\Stateable;
43 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
44 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
45 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
46 use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
47 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
48 use Org\Mxchange\CoreFramework\User\ManageableAccount;
49 use Org\Mxchange\CoreFramework\Visitor\Visitor;
53 use \InvalidArgumentException;
59 * The simulator system class is the super class of all other classes. This
60 * class handles saving of games etc.
62 * @author Roland Haeder <webmaster@shipsimu.org>
64 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
65 * @license GNU GPL 3.0 or any newer version
66 * @link http://www.shipsimu.org
68 * This program is free software: you can redistribute it and/or modify
69 * it under the terms of the GNU General Public License as published by
70 * the Free Software Foundation, either version 3 of the License, or
71 * (at your option) any later version.
73 * This program is distributed in the hope that it will be useful,
74 * but WITHOUT ANY WARRANTY; without even the implied warranty of
75 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
76 * GNU General Public License for more details.
78 * You should have received a copy of the GNU General Public License
79 * along with this program. If not, see <http://www.gnu.org/licenses/>.
81 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
83 * Length of output from hash()
85 private static $hashLength = NULL;
88 * Self-referencing instance
90 private static $instance = NULL;
95 private $realClass = __CLASS__;
98 * Search criteria instance
100 private $searchInstance = NULL;
103 * Update criteria instance
105 private $updateInstance = 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;
125 private $rngInstance = NULL;
128 * Instance of a crypto helper
130 private $cryptoInstance = NULL;
133 * Instance of an Iterator class
135 private $iteratorInstance = NULL;
138 * Instance of the list
140 private $listInstance = NULL;
145 private $menuInstance = NULL;
148 * Instance of the image
150 private $imageInstance = NULL;
153 * Instance of the stacker
155 private $stackInstance = NULL;
158 * A Compressor instance
160 private $compressorInstance = NULL;
163 * A Parseable instance
165 private $parserInstance = NULL;
168 * A database wrapper instance
170 private $databaseInstance = NULL;
173 * A helper instance for the form
175 private $helperInstance = NULL;
178 * An instance of a InputStream class
180 private $inputStreamInstance = NULL;
183 * An instance of a OutputStream class
185 private $outputStreamInstance = NULL;
190 private $handlerInstance = NULL;
193 * Visitor handler instance
195 private $visitorInstance = NULL;
198 * An instance of a database wrapper class
200 private $wrapperInstance = NULL;
203 * An instance of a file I/O pointer class (not handler)
205 private $pointerInstance = NULL;
208 * An instance of an Indexable class
210 private $indexInstance = NULL;
213 * An instance of a Block class
215 private $blockInstance = NULL;
218 * A FrameworkDirectory instance
220 private $directoryInstance = NULL;
223 * The concrete output instance
225 private $outputInstance = NULL;
230 private $stateInstance = NULL;
233 * Registry instance (implementing Register)
235 private $registryInstance = NULL;
240 private $callbackInstance = NULL;
243 * Thousands separator
245 private $thousands = '.'; // German
250 private $decimals = ','; // German
255 private $genericArray = array();
260 private $commandName = '';
265 private $controllerName = '';
268 * Array with bitmasks and such for pack/unpack methods to support both
269 * 32-bit and 64-bit systems
271 private $packingData = array(
274 'left' => 0xffff0000,
275 'right' => 0x0000ffff,
281 'left' => 0xffffffff00000000,
282 'right' => 0x00000000ffffffff,
289 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
291 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
293 private $archArrayElement = false;
295 /***********************
296 * Exception codes.... *
297 ***********************/
299 // @todo Try to clean these constants up
300 const EXCEPTION_IS_NULL_POINTER = 0x001;
301 const EXCEPTION_IS_NO_OBJECT = 0x002;
302 const EXCEPTION_IS_NO_ARRAY = 0x003;
303 const EXCEPTION_MISSING_METHOD = 0x004;
304 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
305 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
306 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
307 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
308 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
309 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
310 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
311 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
312 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
313 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
314 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
315 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
316 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
317 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
318 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
319 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
320 const EXCEPTION_PATH_NOT_FOUND = 0x015;
321 const EXCEPTION_INVALID_PATH_NAME = 0x016;
322 const EXCEPTION_READ_PROTECED_PATH = 0x017;
323 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
324 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
325 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
326 const EXCEPTION_INVALID_RESOURCE = 0x01b;
327 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
328 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
329 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
330 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
331 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
332 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
333 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
334 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
335 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
336 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
337 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
338 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
339 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
340 const EXCEPTION_INVALID_STRING = 0x029;
341 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
342 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
343 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
344 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
345 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
346 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
347 const EXCEPTION_MISSING_ELEMENT = 0x030;
348 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
349 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
350 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
351 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
352 const EXCEPTION_FATAL_ERROR = 0x035;
353 const EXCEPTION_FILE_NOT_FOUND = 0x036;
354 const EXCEPTION_ASSERTION_FAILED = 0x037;
355 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
356 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
357 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
358 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
359 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
360 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
361 const EXCEPTION_INVALID_SOCKET = 0x03e;
362 const EXCEPTION_SELF_INSTANCE = 0x03f;
365 * Hexadecimal->Decimal translation array
367 private static $hexdec = array(
387 * Decimal->hexadecimal translation array
389 private static $dechex = array(
409 * Startup time in miliseconds
411 private static $startupTime = 0;
414 * Protected super constructor
416 * @param $className Name of the class
419 protected function __construct ($className) {
421 $this->setRealClass($className);
423 // Set configuration instance if no registry ...
424 if (!$this instanceof Register) {
425 // ... because registries doesn't need to be configured
426 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
429 // Is the startup time set? (0 cannot be true anymore)
430 if (self::$startupTime == 0) {
432 self::$startupTime = microtime(true);
436 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
440 * Destructor for all classes. You should not call this method on your own.
444 public function __destruct () {
445 // Flush any updated entries to the database
446 $this->flushPendingUpdates();
448 // Is this object already destroyed?
449 if ($this->__toString() != 'DestructedObject') {
450 // Destroy all informations about this class but keep some text about it alive
451 $this->setRealClass('DestructedObject');
452 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
453 // Already destructed object
454 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
458 // Do not call this twice
459 trigger_error(__METHOD__ . ': Called twice.');
465 * The __call() method where all non-implemented methods end up
467 * @param $methodName Name of the missing method
468 * @args $args Arguments passed to the method
471 public final function __call ($methodName, $args) {
473 self::$instance = $this;
475 // Call static method
476 self::__callStatic($methodName, $args);
478 // Clear self-instance
479 self::$instance = NULL;
483 * The __callStatic() method where all non-implemented static methods end up
485 * @param $methodName Name of the missing method
486 * @param $args Arguments passed to the method
488 * @throws InvalidArgumentException If self::$instance is not a framework's own object
490 public static final function __callStatic ($methodName, $args) {
492 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
494 // Init argument string and class name
496 $className = 'unknown';
498 // Is self-instance set?
499 if (self::$instance instanceof FrameworkInterface) {
500 // Framework's own instance
501 $className = self::$instance->__toString();
502 } elseif (!is_null(self::$instance)) {
504 throw new InvalidArgumentException(sprintf('self::instance[%s] is not expected.', gettype(self::$instance)), self::EXCEPTION_SELF_INSTANCE);
507 // Is it NULL, empty or an array?
508 if (is_null($args)) {
510 $argsString = 'NULL';
511 } elseif (is_array($args)) {
515 // Some arguments are there
516 foreach ($args as $arg) {
517 // Add data about the argument
518 $argsString .= gettype($arg) . ':';
521 // Found a NULL argument
522 $argsString .= 'NULL';
523 } elseif (is_string($arg)) {
524 // Add length for strings
525 $argsString .= strlen($arg);
526 } elseif ((is_int($arg)) || (is_float($arg))) {
529 } elseif (is_array($arg)) {
530 // .. or size if array
531 $argsString .= count($arg);
532 } elseif (is_object($arg)) {
534 $reflection = new ReflectionClass($arg);
536 // Is an other object, maybe no __toString() available
537 $argsString .= $reflection->getName();
538 } elseif ($arg === true) {
539 // ... is boolean 'true'
540 $argsString .= 'true';
541 } elseif ($arg === false) {
542 // ... is boolean 'false'
543 $argsString .= 'false';
546 // Comma for next one
551 if (substr($argsString, -2, 1) == ',') {
553 $argsString = substr($argsString, 0, -2);
559 // Invalid arguments!
560 $argsString = sprintf('!INVALID:%s!', gettype($args));
563 // Output stub message
564 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
565 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s::%s]: Stub! Args: %s',
576 * Getter for $realClass
578 * @return $realClass The name of the real class (not BaseFrameworkSystem)
580 public function __toString () {
581 return $this->realClass;
585 * Magic method to catch setting of missing but set class fields/attributes
587 * @param $name Name of the field/attribute
588 * @param $value Value to store
591 public final function __set ($name, $value) {
592 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
595 print_r($value, true)
600 * Magic method to catch getting of missing fields/attributes
602 * @param $name Name of the field/attribute
605 public final function __get ($name) {
606 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
612 * Magic method to catch unsetting of missing fields/attributes
614 * @param $name Name of the field/attribute
617 public final function __unset ($name) {
618 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
624 * Magic method to catch object serialization
626 * @return $unsupported Unsupported method
627 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
629 public final function __sleep () {
630 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
634 * Magic method to catch object deserialization
636 * @return $unsupported Unsupported method
637 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
639 public final function __wakeup () {
640 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
644 * Magic method to catch calls when an object instance is called
646 * @return $unsupported Unsupported method
647 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
649 public final function __invoke () {
650 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
654 * Setter for the real class name
656 * @param $realClass Class name (string)
659 public final function setRealClass ($realClass) {
661 $this->realClass = (string) $realClass;
665 * Setter for database result instance
667 * @param $resultInstance An instance of a database result class
669 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
671 protected final function setResultInstance (SearchableResult $resultInstance) {
672 $this->resultInstance = $resultInstance;
676 * Getter for database result instance
678 * @return $resultInstance An instance of a database result class
680 public final function getResultInstance () {
681 return $this->resultInstance;
685 * Setter for template engine instances
687 * @param $templateInstance An instance of a template engine class
690 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
691 $this->templateInstance = $templateInstance;
695 * Getter for template engine instances
697 * @return $templateInstance An instance of a template engine class
699 protected final function getTemplateInstance () {
700 return $this->templateInstance;
704 * Setter for search instance
706 * @param $searchInstance Searchable criteria instance
709 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
710 $this->searchInstance = $searchInstance;
714 * Getter for search instance
716 * @return $searchInstance Searchable criteria instance
718 public final function getSearchInstance () {
719 return $this->searchInstance;
723 * Setter for update instance
725 * @param $updateInstance An instance of a LocalUpdateCriteria clase
728 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
729 $this->updateInstance = $updateInstance;
733 * Getter for update instance
735 * @return $updateInstance Updateable criteria instance
737 public final function getUpdateInstance () {
738 return $this->updateInstance;
742 * Setter for language instance
744 * @param $configInstance The configuration instance which shall
745 * be FrameworkConfiguration
748 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
749 GenericRegistry::getRegistry()->addInstance('config', $configInstance);
753 * Getter for configuration instance
755 * @return $configInstance Configuration instance
757 public final function getConfigInstance () {
758 $configInstance = GenericRegistry::getRegistry()->getInstance('config');
759 return $configInstance;
763 * Setter for debug instance
765 * @param $debugInstance The instance for debug output class
768 public final function setDebugInstance (DebugMiddleware $debugInstance) {
769 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
773 * Getter for debug instance
775 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
777 public final function getDebugInstance () {
778 // Get debug instance
779 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
782 return $debugInstance;
786 * Setter for web output instance
788 * @param $webInstance The instance for web output class
791 public final function setWebOutputInstance (OutputStreamer $webInstance) {
792 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
796 * Getter for web output instance
798 * @return $webOutputInstance - Instance to class WebOutput
800 public final function getWebOutputInstance () {
801 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
802 return $webOutputInstance;
806 * Setter for database instance
808 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
811 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
812 GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
816 * Getter for database layer
818 * @return $databaseInstance The database layer instance
820 public final function getDatabaseInstance () {
822 $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
825 return $databaseInstance;
829 * Setter for compressor channel
831 * @param $compressorInstance An instance of CompressorChannel
834 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
835 GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
839 * Getter for compressor channel
841 * @return $compressorInstance The compressor channel
843 public final function getCompressorChannel () {
844 $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
845 return $compressorInstance;
849 * Private getter for language instance
851 * @return $langInstance An instance to the language sub-system
853 protected final function getLanguageInstance () {
854 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
855 return $langInstance;
859 * Setter for language instance
861 * @param $langInstance An instance to the language sub-system
863 * @see LanguageSystem
865 public final function setLanguageInstance (ManageableLanguage $langInstance) {
866 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
870 * Protected setter for user instance
872 * @param $userInstance An instance of a user class
875 protected final function setUserInstance (ManageableAccount $userInstance) {
876 $this->userInstance = $userInstance;
880 * Getter for user instance
882 * @return $userInstance An instance of a user class
884 public final function getUserInstance () {
885 return $this->userInstance;
889 * Setter for RNG instance
891 * @param $rngInstance An instance of a random number generator (RNG)
894 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
895 $this->rngInstance = $rngInstance;
899 * Getter for RNG instance
901 * @return $rngInstance An instance of a random number generator (RNG)
903 public final function getRngInstance () {
904 return $this->rngInstance;
908 * Setter for Cryptable instance
910 * @param $cryptoInstance An instance of a Cryptable class
913 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
914 $this->cryptoInstance = $cryptoInstance;
918 * Getter for Cryptable instance
920 * @return $cryptoInstance An instance of a Cryptable class
922 public final function getCryptoInstance () {
923 return $this->cryptoInstance;
927 * Setter for the list instance
929 * @param $listInstance A list of Listable
932 protected final function setListInstance (Listable $listInstance) {
933 $this->listInstance = $listInstance;
937 * Getter for the list instance
939 * @return $listInstance A list of Listable
941 protected final function getListInstance () {
942 return $this->listInstance;
946 * Setter for the menu instance
948 * @param $menuInstance A RenderableMenu instance
951 protected final function setMenuInstance (RenderableMenu $menuInstance) {
952 $this->menuInstance = $menuInstance;
956 * Getter for the menu instance
958 * @return $menuInstance A RenderableMenu instance
960 protected final function getMenuInstance () {
961 return $this->menuInstance;
965 * Setter for image instance
967 * @param $imageInstance An instance of an image
970 public final function setImageInstance (BaseImage $imageInstance) {
971 $this->imageInstance = $imageInstance;
975 * Getter for image instance
977 * @return $imageInstance An instance of an image
979 public final function getImageInstance () {
980 return $this->imageInstance;
984 * Setter for stacker instance
986 * @param $stackInstance An instance of an stacker
989 public final function setStackInstance (Stackable $stackInstance) {
990 $this->stackInstance = $stackInstance;
994 * Getter for stacker instance
996 * @return $stackInstance An instance of an stacker
998 public final function getStackInstance () {
999 return $this->stackInstance;
1003 * Setter for compressor instance
1005 * @param $compressorInstance An instance of an compressor
1008 public final function setCompressorInstance (Compressor $compressorInstance) {
1009 $this->compressorInstance = $compressorInstance;
1013 * Getter for compressor instance
1015 * @return $compressorInstance An instance of an compressor
1017 public final function getCompressorInstance () {
1018 return $this->compressorInstance;
1022 * Setter for Parseable instance
1024 * @param $parserInstance An instance of an Parseable
1027 public final function setParserInstance (Parseable $parserInstance) {
1028 $this->parserInstance = $parserInstance;
1032 * Getter for Parseable instance
1034 * @return $parserInstance An instance of an Parseable
1036 public final function getParserInstance () {
1037 return $this->parserInstance;
1041 * Setter for DatabaseWrapper instance
1043 * @param $wrapperInstance An instance of an DatabaseWrapper
1046 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1047 $this->wrapperInstance = $wrapperInstance;
1051 * Getter for DatabaseWrapper instance
1053 * @return $wrapperInstance An instance of an DatabaseWrapper
1055 public final function getWrapperInstance () {
1056 return $this->wrapperInstance;
1060 * Setter for helper instance
1062 * @param $helperInstance An instance of a helper class
1065 protected final function setHelperInstance (Helper $helperInstance) {
1066 $this->helperInstance = $helperInstance;
1070 * Getter for helper instance
1072 * @return $helperInstance An instance of a helper class
1074 public final function getHelperInstance () {
1075 return $this->helperInstance;
1079 * Getter for a InputStream instance
1081 * @param $inputStreamInstance The InputStream instance
1083 protected final function getInputStreamInstance () {
1084 return $this->inputStreamInstance;
1088 * Setter for a InputStream instance
1090 * @param $inputStreamInstance The InputStream instance
1093 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1094 $this->inputStreamInstance = $inputStreamInstance;
1098 * Getter for a OutputStream instance
1100 * @param $outputStreamInstance The OutputStream instance
1102 protected final function getOutputStreamInstance () {
1103 return $this->outputStreamInstance;
1107 * Setter for a OutputStream instance
1109 * @param $outputStreamInstance The OutputStream instance
1112 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1113 $this->outputStreamInstance = $outputStreamInstance;
1117 * Setter for handler instance
1119 * @param $handlerInstance An instance of a Handleable class
1122 protected final function setHandlerInstance (Handleable $handlerInstance) {
1123 $this->handlerInstance = $handlerInstance;
1127 * Getter for handler instance
1129 * @return $handlerInstance A Handleable instance
1131 protected final function getHandlerInstance () {
1132 return $this->handlerInstance;
1136 * Setter for visitor instance
1138 * @param $visitorInstance A Visitor instance
1141 protected final function setVisitorInstance (Visitor $visitorInstance) {
1142 $this->visitorInstance = $visitorInstance;
1146 * Getter for visitor instance
1148 * @return $visitorInstance A Visitor instance
1150 protected final function getVisitorInstance () {
1151 return $this->visitorInstance;
1155 * Setter for Iterator instance
1157 * @param $iteratorInstance An instance of an Iterator
1160 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1161 $this->iteratorInstance = $iteratorInstance;
1165 * Getter for Iterator instance
1167 * @return $iteratorInstance An instance of an Iterator
1169 public final function getIteratorInstance () {
1170 return $this->iteratorInstance;
1174 * Setter for FilePointer instance
1176 * @param $pointerInstance An instance of an FilePointer class
1179 protected final function setPointerInstance (FilePointer $pointerInstance) {
1180 $this->pointerInstance = $pointerInstance;
1184 * Getter for FilePointer instance
1186 * @return $pointerInstance An instance of an FilePointer class
1188 public final function getPointerInstance () {
1189 return $this->pointerInstance;
1193 * Unsets pointer instance which triggers a call of __destruct() if the
1194 * instance is still there. This is surely not fatal on already "closed"
1195 * file pointer instances.
1197 * I don't want to mess around with above setter by giving it a default
1198 * value NULL as setter should always explicitly only set (existing) object
1199 * instances and NULL is NULL.
1203 protected final function unsetPointerInstance () {
1204 // Simply it to NULL
1205 $this->pointerInstance = NULL;
1209 * Setter for Indexable instance
1211 * @param $indexInstance An instance of an Indexable class
1214 protected final function setIndexInstance (Indexable $indexInstance) {
1215 $this->indexInstance = $indexInstance;
1219 * Getter for Indexable instance
1221 * @return $indexInstance An instance of an Indexable class
1223 public final function getIndexInstance () {
1224 return $this->indexInstance;
1228 * Setter for Block instance
1230 * @param $blockInstance An instance of an Block class
1233 protected final function setBlockInstance (Block $blockInstance) {
1234 $this->blockInstance = $blockInstance;
1238 * Getter for Block instance
1240 * @return $blockInstance An instance of an Block class
1242 public final function getBlockInstance () {
1243 return $this->blockInstance;
1247 * Setter for FrameworkDirectory instance
1249 * @param $directoryInstance A FrameworkDirectory instance
1252 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1253 $this->directoryInstance = $directoryInstance;
1257 * Getter for FrameworkDirectory instance
1259 * @return $directoryInstance A FrameworkDirectory instance
1261 protected final function getDirectoryInstance () {
1262 return $this->directoryInstance;
1266 * Setter for state instance
1268 * @param $stateInstance A Stateable instance
1271 public final function setStateInstance (Stateable $stateInstance) {
1272 $this->stateInstance = $stateInstance;
1276 * Getter for state instance
1278 * @return $stateInstance A Stateable instance
1280 public final function getStateInstance () {
1281 return $this->stateInstance;
1285 * Setter for output instance
1287 * @param $outputInstance The debug output instance
1290 public final function setOutputInstance (OutputStreamer $outputInstance) {
1291 $this->outputInstance = $outputInstance;
1295 * Getter for output instance
1297 * @return $outputInstance The debug output instance
1299 public final function getOutputInstance () {
1300 return $this->outputInstance;
1304 * Setter for registry instance
1306 * @param $registryInstance An instance of a Register class
1309 protected final function setRegistryInstance (Register $registryInstance) {
1310 $this->registryInstance = $registryInstance;
1314 * Getter for registry instance
1316 * @return $registryInstance The debug registry instance
1318 public final function getRegistryInstance () {
1319 return $this->registryInstance;
1323 * Setter for call-back instance
1325 * @param $callbackInstance An instance of a FrameworkInterface class
1328 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1329 $this->callbackInstance = $callbackInstance;
1333 * Getter for call-back instance
1335 * @return $callbackInstance An instance of a FrameworkInterface class
1337 protected final function getCallbackInstance () {
1338 return $this->callbackInstance;
1342 * Setter for command name
1344 * @param $commandName Last validated command name
1347 protected final function setCommandName ($commandName) {
1348 $this->commandName = $commandName;
1352 * Getter for command name
1354 * @return $commandName Last validated command name
1356 protected final function getCommandName () {
1357 return $this->commandName;
1361 * Setter for controller name
1363 * @param $controllerName Last validated controller name
1366 protected final function setControllerName ($controllerName) {
1367 $this->controllerName = $controllerName;
1371 * Getter for controller name
1373 * @return $controllerName Last validated controller name
1375 protected final function getControllerName () {
1376 return $this->controllerName;
1380 * Checks whether an object equals this object. You should overwrite this
1381 * method to implement own equality checks
1383 * @param $objectInstance An instance of a FrameworkInterface object
1384 * @return $equals Whether both objects equals
1386 public function equals (FrameworkInterface $objectInstance) {
1389 $this->__toString() == $objectInstance->__toString()
1391 $this->hashCode() == $objectInstance->hashCode()
1394 // Return the result
1399 * Generates a generic hash code of this class. You should really overwrite
1400 * this method with your own hash code generator code. But keep KISS in mind.
1402 * @return $hashCode A generic hash code respresenting this whole class
1404 public function hashCode () {
1406 return crc32($this->__toString());
1410 * Formats computer generated price values into human-understandable formats
1411 * with thousand and decimal separators.
1413 * @param $value The in computer format value for a price
1414 * @param $currency The currency symbol (use HTML-valid characters!)
1415 * @param $decNum Number of decimals after commata
1416 * @return $price The for the current language formated price string
1417 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1418 * thousands separator
1421 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1422 // Are all required attriutes set?
1423 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1424 // Throw an exception
1425 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1429 $value = (float) $value;
1431 // Reformat the US number
1432 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1434 // Return as string...
1439 * Appends a trailing slash to a string
1441 * @param $str A string (maybe) without trailing slash
1442 * @return $str A string with an auto-appended trailing slash
1444 public final function addMissingTrailingSlash ($str) {
1445 // Is there a trailing slash?
1446 if (substr($str, -1, 1) != '/') {
1450 // Return string with trailing slash
1455 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1456 * application helper instance (ApplicationHelper by default).
1458 * @param $applicationInstance An application helper instance or
1459 * null if we shall use the default
1460 * @return $templateInstance The template engine instance
1461 * @throws NullPointerException If the discovered application
1462 * instance is still null
1464 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1465 // Is the application instance set?
1466 if (is_null($applicationInstance)) {
1467 // Get the current instance
1468 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1471 if (is_null($applicationInstance)) {
1472 // Thrown an exception
1473 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1477 // Initialize the template engine
1478 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1480 // Return the prepared instance
1481 return $templateInstance;
1485 * Debugs this instance by putting out it's full content
1487 * @param $message Optional message to show in debug output
1490 public final function debugInstance ($message = '') {
1491 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1492 restore_error_handler();
1497 // Is a message set?
1498 if (!empty($message)) {
1499 // Construct message
1500 $content = sprintf('<div class="debug_message">
1502 </div>' . PHP_EOL, $message);
1505 // Generate the output
1506 $content .= sprintf('<pre>%s</pre>',
1509 print_r($this, true)
1515 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1518 <div class="debug_content">
1522 <div class="debug_include_list">
1525 $this->__toString(),
1527 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1532 * Replaces control characters with printable output
1534 * @param $str String with control characters
1535 * @return $str Replaced string
1537 protected function replaceControlCharacters ($str) {
1540 chr(13), '[r]', str_replace(
1541 chr(10), '[n]', str_replace(
1551 * Output a partial stub message for the caller method
1553 * @param $message An optional message to display
1556 protected function partialStub ($message = '') {
1558 $stubMessage = 'Partial stub!';
1560 // Is an extra message given?
1561 if (!empty($message)) {
1562 // Then add it as well
1563 $stubMessage .= ' Message: ' . $message;
1566 // Debug instance is there?
1567 if (!is_null($this->getDebugInstance())) {
1568 // Output stub message
1569 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1572 trigger_error($stubMessage);
1578 * Outputs a debug backtrace and stops further script execution
1580 * @param $message An optional message to output
1581 * @param $doExit Whether exit the program (true is default)
1584 public function debugBackTrace ($message = '', $doExit = true) {
1585 // Sorry, there is no other way getting this nice backtrace
1586 if (!empty($message)) {
1588 printf('Message: %s<br />' . PHP_EOL, $message);
1592 debug_print_backtrace();
1596 if ($doExit === true) {
1602 * Creates an instance of a debugger instance
1604 * @param $className Name of the class (currently unsupported)
1605 * @param $lineNumber Line number where the call was made
1606 * @return $debugInstance An instance of a debugger class
1607 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1609 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1610 // Is the instance set?
1611 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1612 // Init debug instance
1613 $debugInstance = NULL;
1617 // Get a debugger instance
1618 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1619 } catch (NullPointerException $e) {
1620 // Didn't work, no instance there
1621 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1624 // Empty string should be ignored and used for testing the middleware
1625 DebugMiddleware::getSelfInstance()->output('');
1627 // Set it in registry
1628 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1630 // Get instance from registry
1631 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1635 return $debugInstance;
1639 * Simple output of a message with line-break
1641 * @param $message Message to output
1644 public function outputLine ($message) {
1646 print($message . PHP_EOL);
1650 * Outputs a debug message whether to debug instance (should be set!) or
1651 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1652 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1654 * @param $message Message we shall send out...
1655 * @param $doPrint Whether print or die here (default: print)
1656 * @paran $stripTags Whether to strip tags (default: false)
1659 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1660 // Set debug instance to NULL
1661 $debugInstance = NULL;
1664 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1666 // Is function partialStub/__callStatic ?
1667 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1668 // Prepend class::function:line from 3rd element
1669 $message = sprintf('[%s::%s:%d]: %s',
1670 $backtrace[2]['class'],
1671 $backtrace[2]['function'],
1672 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1676 // Prepend class::function:line from 2nd element
1677 $message = sprintf('[%s::%s:%d]: %s',
1678 $backtrace[1]['class'],
1679 $backtrace[1]['function'],
1680 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1687 // Get debug instance
1688 $debugInstance = $this->getDebugInstance();
1689 } catch (NullPointerException $e) {
1690 // The debug instance is not set (yet)
1693 // Is the debug instance there?
1694 if (is_object($debugInstance)) {
1695 // Use debug output handler
1696 $debugInstance->output($message, $stripTags);
1698 if ($doPrint === false) {
1699 // Die here if not printed
1703 // Are debug times enabled?
1704 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1706 $message = $this->getPrintableExecutionTime() . $message;
1710 if ($doPrint === true) {
1712 $this->outputLine($message);
1721 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1723 * @param $str The string, what ever it is needs to be converted
1724 * @return $className Generated class name
1726 public static final function convertToClassName ($str) {
1730 // Convert all dashes in underscores
1731 $str = StringUtils::convertDashesToUnderscores($str);
1733 // Now use that underscores to get classname parts for hungarian style
1734 foreach (explode('_', $str) as $strPart) {
1735 // Make the class name part lower case and first upper case
1736 $className .= ucfirst(strtolower($strPart));
1739 // Return class name
1744 * Marks up the code by adding e.g. line numbers
1746 * @param $phpCode Unmarked PHP code
1747 * @return $markedCode Marked PHP code
1749 public function markupCode ($phpCode) {
1754 $errorArray = error_get_last();
1756 // Init the code with error message
1757 if (is_array($errorArray)) {
1759 $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>',
1760 basename($errorArray['file']),
1761 $errorArray['line'],
1762 $errorArray['message'],
1767 // Add line number to the code
1768 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1770 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1772 htmlentities($code, ENT_QUOTES)
1781 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1782 * beatiful for web-based front-ends. If null is given a message id
1783 * null_timestamp will be resolved and returned.
1785 * @param $timestamp Timestamp to prepare (filter) for display
1786 * @return $readable A readable timestamp
1788 public function doFilterFormatTimestamp ($timestamp) {
1789 // Default value to return
1792 // Is the timestamp null?
1793 if (is_null($timestamp)) {
1794 // Get a message string
1795 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1797 switch ($this->getLanguageInstance()->getLanguageCode()) {
1798 case 'de': // German format is a bit different to default
1799 // Split the GMT stamp up
1800 $dateTime = explode(' ', $timestamp );
1801 $dateArray = explode('-', $dateTime[0]);
1802 $timeArray = explode(':', $dateTime[1]);
1804 // Construct the timestamp
1805 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1815 default: // Default is pass-through
1816 $readable = $timestamp;
1826 * Filter a given number into a localized number
1828 * @param $value The raw value from e.g. database
1829 * @return $localized Localized value
1831 public function doFilterFormatNumber ($value) {
1832 // Generate it from config and localize dependencies
1833 switch ($this->getLanguageInstance()->getLanguageCode()) {
1834 case 'de': // German format is a bit different to default
1835 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1838 default: // US, etc.
1839 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1848 * "Getter" for databse entry
1850 * @return $entry An array with database entries
1851 * @throws NullPointerException If the database result is not found
1852 * @throws InvalidDatabaseResultException If the database result is invalid
1854 protected final function getDatabaseEntry () {
1855 // Is there an instance?
1856 if (!$this->getResultInstance() instanceof SearchableResult) {
1857 // Throw an exception here
1858 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1862 $this->getResultInstance()->rewind();
1864 // Do we have an entry?
1865 if ($this->getResultInstance()->valid() === false) {
1866 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
1867 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1871 $this->getResultInstance()->next();
1874 $entry = $this->getResultInstance()->current();
1881 * Getter for field name
1883 * @param $fieldName Field name which we shall get
1884 * @return $fieldValue Field value from the user
1885 * @throws NullPointerException If the result instance is null
1887 public final function getField ($fieldName) {
1888 // Default field value
1891 // Get result instance
1892 $resultInstance = $this->getResultInstance();
1894 // Is this instance null?
1895 if (is_null($resultInstance)) {
1896 // Then the user instance is no longer valid (expired cookies?)
1897 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1900 // Get current array
1901 $fieldArray = $resultInstance->current();
1902 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1904 // Convert dashes to underscore
1905 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
1907 // Does the field exist?
1908 if ($this->isFieldSet($fieldName)) {
1910 $fieldValue = $fieldArray[$fieldName2];
1911 } elseif (defined('DEVELOPER')) {
1912 // Missing field entry, may require debugging
1913 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
1915 // Missing field entry, may require debugging
1916 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
1924 * Checks if given field is set
1926 * @param $fieldName Field name to check
1927 * @return $isSet Whether the given field name is set
1928 * @throws NullPointerException If the result instance is null
1930 public function isFieldSet ($fieldName) {
1931 // Get result instance
1932 $resultInstance = $this->getResultInstance();
1934 // Is this instance null?
1935 if (is_null($resultInstance)) {
1936 // Then the user instance is no longer valid (expired cookies?)
1937 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1940 // Get current array
1941 $fieldArray = $resultInstance->current();
1942 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
1944 // Convert dashes to underscore
1945 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
1948 $isSet = isset($fieldArray[$fieldName]);
1955 * Flushs all pending updates to the database layer
1959 public function flushPendingUpdates () {
1960 // Get result instance
1961 $resultInstance = $this->getResultInstance();
1963 // Do we have data to update?
1964 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1965 // Get wrapper class name config entry
1966 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1968 // Create object instance
1969 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
1971 // Yes, then send the whole result to the database layer
1972 $wrapperInstance->doUpdateByResult($this->getResultInstance());
1977 * Outputs a deprecation warning to the developer.
1979 * @param $message The message we shall output to the developer
1981 * @todo Write a logging mechanism for productive mode
1983 public function deprecationWarning ($message) {
1984 // Is developer mode active?
1985 if (defined('DEVELOPER')) {
1986 // Debug instance is there?
1987 if (!is_null($this->getDebugInstance())) {
1988 // Output stub message
1989 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
1992 trigger_error($message . "<br />\n");
1996 // @TODO Finish this part!
1997 $this->partialStub('Developer mode inactive. Message:' . $message);
2002 * Checks whether the given PHP extension is loaded
2004 * @param $phpExtension The PHP extension we shall check
2005 * @return $isLoaded Whether the PHP extension is loaded
2007 public final function isPhpExtensionLoaded ($phpExtension) {
2009 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2016 * "Getter" as a time() replacement but with milliseconds. You should use this
2017 * method instead of the encapsulated getimeofday() function.
2019 * @return $milliTime Timestamp with milliseconds
2021 public function getMilliTime () {
2022 // Get the time of day as float
2023 $milliTime = gettimeofday(true);
2030 * Idles (sleeps) for given milliseconds
2032 * @return $hasSlept Whether it goes fine
2034 public function idle ($milliSeconds) {
2035 // Sleep is fine by default
2038 // Idle so long with found function
2039 if (function_exists('time_sleep_until')) {
2040 // Get current time and add idle time
2041 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2043 // New PHP 5.1.0 function found, ignore errors
2044 $hasSlept = @time_sleep_until($sleepUntil);
2047 * My Sun station doesn't have that function even with latest PHP
2050 usleep($milliSeconds * 1000);
2057 * Converts a hexadecimal string, even with negative sign as first string to
2058 * a decimal number using BC functions.
2060 * This work is based on comment #86673 on php.net documentation page at:
2061 * <http://de.php.net/manual/en/function.dechex.php#86673>
2063 * @param $hex Hexadecimal string
2064 * @return $dec Decimal number
2066 protected function hex2dec ($hex) {
2067 // Convert to all lower-case
2068 $hex = strtolower($hex);
2070 // Detect sign (negative/positive numbers)
2072 if (substr($hex, 0, 1) == '-') {
2074 $hex = substr($hex, 1);
2077 // Decode the hexadecimal string into a decimal number
2079 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2080 $factor = self::$hexdec[substr($hex, $i, 1)];
2081 $dec = bcadd($dec, bcmul($factor, $e));
2084 // Return the decimal number
2085 return $sign . $dec;
2089 * Converts even very large decimal numbers, also signed, to a hexadecimal
2092 * This work is based on comment #97756 on php.net documentation page at:
2093 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2095 * @param $dec Decimal number, even with negative sign
2096 * @param $maxLength Optional maximum length of the string
2097 * @return $hex Hexadecimal string
2099 protected function dec2hex ($dec, $maxLength = 0) {
2100 // maxLength can be zero or devideable by 2
2101 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2103 // Detect sign (negative/positive numbers)
2110 // Encode the decimal number into a hexadecimal string
2113 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2115 } while ($dec >= 1);
2118 * Leading zeros are required for hex-decimal "numbers". In some
2119 * situations more leading zeros are wanted, so check for both
2122 if ($maxLength > 0) {
2123 // Prepend more zeros
2124 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2125 } elseif ((strlen($hex) % 2) != 0) {
2126 // Only make string's length dividable by 2
2130 // Return the hexadecimal string
2131 return $sign . $hex;
2135 * Converts a ASCII string (0 to 255) into a decimal number.
2137 * @param $asc The ASCII string to be converted
2138 * @return $dec Decimal number
2140 protected function asc2dec ($asc) {
2141 // Convert it into a hexadecimal number
2142 $hex = bin2hex($asc);
2144 // And back into a decimal number
2145 $dec = $this->hex2dec($hex);
2152 * Converts a decimal number into an ASCII string.
2154 * @param $dec Decimal number
2155 * @return $asc An ASCII string
2157 protected function dec2asc ($dec) {
2158 // First convert the number into a hexadecimal string
2159 $hex = $this->dec2hex($dec);
2161 // Then convert it into the ASCII string
2162 $asc = $this->hex2asc($hex);
2169 * Converts a hexadecimal number into an ASCII string. Negative numbers
2172 * @param $hex Hexadecimal string
2173 * @return $asc An ASCII string
2175 protected function hex2asc ($hex) {
2176 // Check for length, it must be devideable by 2
2177 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2178 assert((strlen($hex) % 2) == 0);
2182 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2183 // Get the decimal number of the chunk
2184 $part = hexdec(substr($hex, $idx, 2));
2186 // Add it to the final string
2190 // Return the final string
2195 * Checks whether the given encoded data was encoded with Base64
2197 * @param $encodedData Encoded data we shall check
2198 * @return $isBase64 Whether the encoded data is Base64
2200 protected function isBase64Encoded ($encodedData) {
2202 $isBase64 = (@base64_decode($encodedData, true) !== false);
2209 * Gets a cache key from Criteria instance
2211 * @param $criteriaInstance An instance of a Criteria class
2212 * @param $onlyKeys Only use these keys for a cache key
2213 * @return $cacheKey A cache key suitable for lookup/storage purposes
2215 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2217 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: criteriaInstance=' . $criteriaInstance->__toString() . ',onlyKeys()=' . count($onlyKeys) . ' - CALLED!');
2218 $cacheKey = sprintf('%s@%s',
2219 $this->__toString(),
2220 $criteriaInstance->getCacheKey($onlyKeys)
2224 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: cacheKey=' . $cacheKey . ' - EXIT!');
2229 * Getter for startup time in miliseconds
2231 * @return $startupTime Startup time in miliseconds
2233 protected function getStartupTime () {
2234 return self::$startupTime;
2238 * "Getter" for a printable currently execution time in nice braces
2240 * @return $executionTime Current execution time in nice braces
2242 protected function getPrintableExecutionTime () {
2243 // Caculate the execution time
2244 $executionTime = microtime(true) - $this->getStartupTime();
2246 // Pack it in nice braces
2247 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2250 return $executionTime;
2254 * Hashes a given string with a simple but stronger hash function (no salt)
2255 * and hex-encode it.
2257 * @param $str The string to be hashed
2258 * @return $hash The hash from string $str
2260 public static final function hash ($str) {
2261 // Hash given string with (better secure) hasher
2262 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2269 * "Getter" for length of hash() output. This will be "cached" to speed up
2272 * @return $length Length of hash() output
2274 public static final function getHashLength () {
2276 if (is_null(self::$hashLength)) {
2277 // No, then hash a string and save its length.
2278 self::$hashLength = strlen(self::hash('abc123'));
2282 return self::$hashLength;
2286 * Checks whether the given number is really a number (only chars 0-9).
2288 * @param $num A string consisting only chars between 0 and 9
2289 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2290 * @param $assertMismatch Whether to assert mismatches
2291 * @return $ret The (hopefully) secured numbered value
2293 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2294 // Filter all numbers out
2295 $ret = preg_replace('/[^0123456789]/', '', $num);
2298 if ($castValue === true) {
2299 // Cast to biggest numeric type
2300 $ret = (double) $ret;
2303 // Assert only if requested
2304 if ($assertMismatch === true) {
2305 // Has the whole value changed?
2306 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2314 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2316 * @param $num A string consisting only chars between 0 and 9
2317 * @param $assertMismatch Whether to assert mismatches
2318 * @return $ret The (hopefully) secured hext-numbered value
2320 public function hexval ($num, $assertMismatch = false) {
2321 // Filter all numbers out
2322 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2324 // Assert only if requested
2325 if ($assertMismatch === true) {
2326 // Has the whole value changed?
2327 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2335 * Determines if an element is set in the generic array
2337 * @param $keyGroup Main group for the key
2338 * @param $subGroup Sub group for the key
2339 * @param $key Key to check
2340 * @param $element Element to check
2341 * @return $isset Whether the given key is set
2343 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2345 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2348 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2354 * Determines if a key is set in the generic array
2356 * @param $keyGroup Main group for the key
2357 * @param $subGroup Sub group for the key
2358 * @param $key Key to check
2359 * @return $isset Whether the given key is set
2361 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2363 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2366 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2374 * Determines if a group is set in the generic array
2376 * @param $keyGroup Main group
2377 * @param $subGroup Sub group
2378 * @return $isset Whether the given group is set
2380 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2382 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2385 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2392 * Getter for sub key group
2394 * @param $keyGroup Main key group
2395 * @param $subGroup Sub key group
2396 * @return $array An array with all array elements
2398 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2400 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2401 // No, then abort here
2402 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2407 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2410 return $this->genericArray[$keyGroup][$subGroup];
2414 * Unsets a given key in generic array
2416 * @param $keyGroup Main group for the key
2417 * @param $subGroup Sub group for the key
2418 * @param $key Key to unset
2421 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2423 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2426 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2430 * Unsets a given element in generic array
2432 * @param $keyGroup Main group for the key
2433 * @param $subGroup Sub group for the key
2434 * @param $key Key to unset
2435 * @param $element Element to unset
2438 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2440 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2443 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2447 * Append a string to a given generic array key
2449 * @param $keyGroup Main group for the key
2450 * @param $subGroup Sub group for the key
2451 * @param $key Key to unset
2452 * @param $value Value to add/append
2455 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2457 //* 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);
2459 // Is it already there?
2460 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2462 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2465 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2470 * Append a string to a given generic array element
2472 * @param $keyGroup Main group for the key
2473 * @param $subGroup Sub group for the key
2474 * @param $key Key to unset
2475 * @param $element Element to check
2476 * @param $value Value to add/append
2479 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2481 //* 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);
2483 // Is it already there?
2484 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2486 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2489 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2494 * Sets a string in a given generic array element
2496 * @param $keyGroup Main group for the key
2497 * @param $subGroup Sub group for the key
2498 * @param $key Key to unset
2499 * @param $element Element to check
2500 * @param $value Value to add/append
2503 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2505 //* 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);
2508 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2512 * Initializes given generic array group
2514 * @param $keyGroup Main group for the key
2515 * @param $subGroup Sub group for the key
2516 * @param $key Key to use
2517 * @param $forceInit Optionally force initialization
2520 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2522 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2524 // Is it already set?
2525 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2526 // Already initialized
2527 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2532 $this->genericArray[$keyGroup][$subGroup] = array();
2536 * Initializes given generic array key
2538 * @param $keyGroup Main group for the key
2539 * @param $subGroup Sub group for the key
2540 * @param $key Key to use
2541 * @param $forceInit Optionally force initialization
2544 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2546 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2548 // Is it already set?
2549 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2550 // Already initialized
2551 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2556 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2560 * Initializes given generic array element
2562 * @param $keyGroup Main group for the key
2563 * @param $subGroup Sub group for the key
2564 * @param $key Key to use
2565 * @param $element Element to use
2566 * @param $forceInit Optionally force initialization
2569 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2571 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2573 // Is it already set?
2574 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2575 // Already initialized
2576 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2581 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2585 * Pushes an element to a generic key
2587 * @param $keyGroup Main group for the key
2588 * @param $subGroup Sub group for the key
2589 * @param $key Key to use
2590 * @param $value Value to add/append
2591 * @return $count Number of array elements
2593 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2595 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2598 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2600 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2604 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2607 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2608 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2613 * Pushes an element to a generic array element
2615 * @param $keyGroup Main group for the key
2616 * @param $subGroup Sub group for the key
2617 * @param $key Key to use
2618 * @param $element Element to check
2619 * @param $value Value to add/append
2620 * @return $count Number of array elements
2622 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2624 //* 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));
2627 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2629 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2633 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2636 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2637 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2642 * Pops an element from a generic group
2644 * @param $keyGroup Main group for the key
2645 * @param $subGroup Sub group for the key
2646 * @param $key Key to unset
2647 * @return $value Last "popped" value
2649 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2651 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2654 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2656 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2661 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2664 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2665 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2670 * Shifts an element from a generic group
2672 * @param $keyGroup Main group for the key
2673 * @param $subGroup Sub group for the key
2674 * @param $key Key to unset
2675 * @return $value Last "popped" value
2677 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2679 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2682 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2684 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2689 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2692 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2693 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2698 * Count generic array group
2700 * @param $keyGroup Main group for the key
2701 * @return $count Count of given group
2703 protected final function countGenericArray ($keyGroup) {
2705 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2708 if (!isset($this->genericArray[$keyGroup])) {
2710 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2715 $count = count($this->genericArray[$keyGroup]);
2718 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2725 * Count generic array sub group
2727 * @param $keyGroup Main group for the key
2728 * @param $subGroup Sub group for the key
2729 * @return $count Count of given group
2731 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2733 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2736 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2738 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2743 $count = count($this->genericArray[$keyGroup][$subGroup]);
2746 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2753 * Count generic array elements
2755 * @param $keyGroup Main group for the key
2756 * @param $subGroup Sub group for the key
2757 * @para $key Key to count
2758 * @return $count Count of given key
2760 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2762 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2765 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2767 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2769 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2771 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2776 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2779 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2786 * Getter for whole generic group array
2788 * @param $keyGroup Key group to get
2789 * @return $array Whole generic array group
2791 protected final function getGenericArray ($keyGroup) {
2793 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2796 if (!isset($this->genericArray[$keyGroup])) {
2798 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2803 return $this->genericArray[$keyGroup];
2807 * Setter for generic array key
2809 * @param $keyGroup Key group to get
2810 * @param $subGroup Sub group for the key
2811 * @param $key Key to unset
2812 * @param $value Mixed value from generic array element
2815 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2817 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2820 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2824 * Getter for generic array key
2826 * @param $keyGroup Key group to get
2827 * @param $subGroup Sub group for the key
2828 * @param $key Key to unset
2829 * @return $value Mixed value from generic array element
2831 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2833 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2836 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2838 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2843 return $this->genericArray[$keyGroup][$subGroup][$key];
2847 * Sets a value in given generic array key/element
2849 * @param $keyGroup Main group for the key
2850 * @param $subGroup Sub group for the key
2851 * @param $key Key to set
2852 * @param $element Element to set
2853 * @param $value Value to set
2856 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2858 //* 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));
2861 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2865 * Getter for generic array element
2867 * @param $keyGroup Key group to get
2868 * @param $subGroup Sub group for the key
2869 * @param $key Key to look for
2870 * @param $element Element to look for
2871 * @return $value Mixed value from generic array element
2873 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2875 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2878 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2880 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2885 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2889 * Checks if a given sub group is valid (array)
2891 * @param $keyGroup Key group to get
2892 * @param $subGroup Sub group for the key
2893 * @return $isValid Whether given sub group is valid
2895 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2897 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2900 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2907 * Checks if a given key is valid (array)
2909 * @param $keyGroup Key group to get
2910 * @param $subGroup Sub group for the key
2911 * @param $key Key to check
2912 * @return $isValid Whether given sub group is valid
2914 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2916 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2919 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2926 * Initializes the web output instance
2930 protected function initWebOutputInstance () {
2931 // Get application instance
2932 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
2934 // Init web output instance
2935 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
2938 $this->setWebOutputInstance($outputInstance);
2942 * Translates boolean true to 'Y' and false to 'N'
2944 * @param $boolean Boolean value
2945 * @return $translated Translated boolean value
2947 public static final function translateBooleanToYesNo ($boolean) {
2948 // Make sure it is really boolean
2949 assert(is_bool($boolean));
2952 $translated = ($boolean === true) ? 'Y' : 'N';
2954 // ... and return it
2959 * Encodes raw data (almost any type) by "serializing" it and then pack it
2960 * into a "binary format".
2962 * @param $rawData Raw data (almost any type)
2963 * @return $encoded Encoded data
2965 protected function encodeData ($rawData) {
2966 // Make sure no objects or resources pass through
2967 assert(!is_object($rawData));
2968 assert(!is_resource($rawData));
2970 // First "serialize" it (json_encode() is faster than serialize())
2971 $encoded = $this->packString(json_encode($rawData));
2978 * Pack a string into a "binary format". Please execuse me that this is
2979 * widely undocumented. :-(
2981 * @param $str Unpacked string
2982 * @return $packed Packed string
2983 * @todo Improve documentation
2985 protected function packString ($str) {
2987 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
2989 // First compress the string (gzcompress is okay)
2990 $str = gzcompress($str);
2995 // And start the "encoding" loop
2996 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
2998 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
2999 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3001 if (($idx + $i) <= strlen($str)) {
3002 $ord = ord(substr($str, ($idx + $i), 1));
3004 $add = $ord * pow(256, $factor);
3008 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3012 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3013 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3015 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3016 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3022 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3027 * Creates a full-qualified file name (FQFN) for given file name by adding
3028 * a configured temporary file path to it.
3030 * @param $infoInstance An instance of a SplFileInfo class
3031 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3032 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3033 * @throws FileIoException If the file cannot be written
3035 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3037 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3039 // Is the path writeable?
3040 if (!is_writable($basePath)) {
3041 // Path is write-protected
3042 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3046 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3049 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3051 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3055 return $tempInstance;
3059 * "Getter" for a printable state name
3061 * @return $stateName Name of the node's state in a printable format
3063 public final function getPrintableState () {
3064 // Default is 'null'
3065 $stateName = 'null';
3067 // Get the state instance
3068 $stateInstance = $this->getStateInstance();
3070 // Is it an instance of Stateable?
3071 if ($stateInstance instanceof Stateable) {
3072 // Then use that state name
3073 $stateName = $stateInstance->getStateName();