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\Controller\Controller;
11 use Org\Mxchange\CoreFramework\Criteria\Criteria;
12 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
13 use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
14 use Org\Mxchange\CoreFramework\Crypto\Cryptable;
15 use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
16 use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
17 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
18 use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
19 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
20 use Org\Mxchange\CoreFramework\Filesystem\Block;
21 use Org\Mxchange\CoreFramework\Filesystem\FilePointer;
22 use Org\Mxchange\CoreFramework\Filesystem\FrameworkDirectory;
23 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
24 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
25 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
26 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
27 use Org\Mxchange\CoreFramework\Handler\Handleable;
28 use Org\Mxchange\CoreFramework\Handler\Stream\IoHandler;
29 use Org\Mxchange\CoreFramework\Helper\Helper;
30 use Org\Mxchange\CoreFramework\Index\Indexable;
31 use Org\Mxchange\CoreFramework\Lists\Listable;
32 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
33 use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
34 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
35 use Org\Mxchange\CoreFramework\Menu\RenderableMenu;
36 use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
37 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
38 use Org\Mxchange\CoreFramework\Parser\Parseable;
39 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
40 use Org\Mxchange\CoreFramework\Registry\Register;
41 use Org\Mxchange\CoreFramework\Resolver\Resolver;
42 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
43 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
44 use Org\Mxchange\CoreFramework\Stacker\Stackable;
45 use Org\Mxchange\CoreFramework\State\Stateable;
46 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
47 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
48 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
49 use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
50 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
51 use Org\Mxchange\CoreFramework\User\ManageableAccount;
52 use Org\Mxchange\CoreFramework\Visitor\Visitor;
56 use \InvalidArgumentException;
62 * The simulator system class is the super class of all other classes. This
63 * class handles saving of games etc.
65 * @author Roland Haeder <webmaster@shipsimu.org>
67 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
68 * @license GNU GPL 3.0 or any newer version
69 * @link http://www.shipsimu.org
71 * This program is free software: you can redistribute it and/or modify
72 * it under the terms of the GNU General Public License as published by
73 * the Free Software Foundation, either version 3 of the License, or
74 * (at your option) any later version.
76 * This program is distributed in the hope that it will be useful,
77 * but WITHOUT ANY WARRANTY; without even the implied warranty of
78 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
79 * GNU General Public License for more details.
81 * You should have received a copy of the GNU General Public License
82 * along with this program. If not, see <http://www.gnu.org/licenses/>.
84 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
86 * Length of output from hash()
88 private static $hashLength = NULL;
91 * Self-referencing instance
93 private static $instance = NULL;
98 private $realClass = 'BaseFrameworkSystem';
101 * Search criteria instance
103 private $searchInstance = NULL;
106 * Update criteria instance
108 private $updateInstance = NULL;
111 * The file I/O instance for the template loader
113 private $fileIoInstance = NULL;
118 private $resolverInstance = NULL;
121 * Template engine instance
123 private $templateInstance = NULL;
126 * Database result instance
128 private $resultInstance = NULL;
131 * Instance for user class
133 private $userInstance = NULL;
136 * A controller instance
138 private $controllerInstance = NULL;
143 private $rngInstance = NULL;
146 * Instance of a crypto helper
148 private $cryptoInstance = NULL;
151 * Instance of an Iterator class
153 private $iteratorInstance = NULL;
156 * Instance of the list
158 private $listInstance = NULL;
163 private $menuInstance = NULL;
166 * Instance of the image
168 private $imageInstance = NULL;
171 * Instance of the stacker
173 private $stackInstance = NULL;
176 * A Compressor instance
178 private $compressorInstance = NULL;
181 * A Parseable instance
183 private $parserInstance = NULL;
186 * A database wrapper instance
188 private $databaseInstance = NULL;
191 * A helper instance for the form
193 private $helperInstance = NULL;
196 * An instance of a InputStream class
198 private $inputStreamInstance = NULL;
201 * An instance of a OutputStream class
203 private $outputStreamInstance = NULL;
208 private $handlerInstance = NULL;
211 * Visitor handler instance
213 private $visitorInstance = NULL;
216 * An instance of a database wrapper class
218 private $wrapperInstance = NULL;
221 * An instance of a file I/O pointer class (not handler)
223 private $pointerInstance = NULL;
226 * An instance of an Indexable class
228 private $indexInstance = NULL;
231 * An instance of a Block class
233 private $blockInstance = NULL;
236 * A FrameworkDirectory instance
238 private $directoryInstance = NULL;
241 * The concrete output instance
243 private $outputInstance = NULL;
248 private $stateInstance = NULL;
251 * Registry instance (implementing Register)
253 private $registryInstance = NULL;
258 private $callbackInstance = NULL;
261 * Thousands separator
263 private $thousands = '.'; // German
268 private $decimals = ','; // German
273 private $genericArray = array();
278 private $commandName = '';
283 private $controllerName = '';
286 * Array with bitmasks and such for pack/unpack methods to support both
287 * 32-bit and 64-bit systems
289 private $packingData = array(
292 'left' => 0xffff0000,
293 'right' => 0x0000ffff,
299 'left' => 0xffffffff00000000,
300 'right' => 0x00000000ffffffff,
307 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
309 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
311 private $archArrayElement = false;
313 /***********************
314 * Exception codes.... *
315 ***********************/
317 // @todo Try to clean these constants up
318 const EXCEPTION_IS_NULL_POINTER = 0x001;
319 const EXCEPTION_IS_NO_OBJECT = 0x002;
320 const EXCEPTION_IS_NO_ARRAY = 0x003;
321 const EXCEPTION_MISSING_METHOD = 0x004;
322 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
323 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
324 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
325 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
326 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
327 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
328 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
329 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
330 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
331 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
332 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
333 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
334 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
335 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
336 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
337 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
338 const EXCEPTION_PATH_NOT_FOUND = 0x015;
339 const EXCEPTION_INVALID_PATH_NAME = 0x016;
340 const EXCEPTION_READ_PROTECED_PATH = 0x017;
341 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
342 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
343 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
344 const EXCEPTION_INVALID_RESOURCE = 0x01b;
345 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
346 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
347 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
348 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
349 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
350 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
351 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
352 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
353 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
354 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
355 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
356 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
357 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
358 const EXCEPTION_INVALID_STRING = 0x029;
359 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
360 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
361 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
362 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
363 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
364 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
365 const EXCEPTION_MISSING_ELEMENT = 0x030;
366 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
367 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
368 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
369 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
370 const EXCEPTION_FATAL_ERROR = 0x035;
371 const EXCEPTION_FILE_NOT_FOUND = 0x036;
372 const EXCEPTION_ASSERTION_FAILED = 0x037;
373 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
374 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
375 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
376 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
377 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
378 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
379 const EXCEPTION_INVALID_SOCKET = 0x03e;
380 const EXCEPTION_SELF_INSTANCE = 0x03f;
383 * Hexadecimal->Decimal translation array
385 private static $hexdec = array(
405 * Decimal->hexadecimal translation array
407 private static $dechex = array(
427 * Startup time in miliseconds
429 private static $startupTime = 0;
432 * Protected super constructor
434 * @param $className Name of the class
437 protected function __construct ($className) {
439 $this->setRealClass($className);
441 // Set configuration instance if no registry ...
442 if (!$this instanceof Register) {
443 // ... because registries doesn't need to be configured
444 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
447 // Is the startup time set? (0 cannot be true anymore)
448 if (self::$startupTime == 0) {
450 self::$startupTime = microtime(true);
454 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
458 * Destructor for all classes. You should not call this method on your own.
462 public function __destruct () {
463 // Flush any updated entries to the database
464 $this->flushPendingUpdates();
466 // Is this object already destroyed?
467 if ($this->__toString() != 'DestructedObject') {
468 // Destroy all informations about this class but keep some text about it alive
469 $this->setRealClass('DestructedObject');
470 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
471 // Already destructed object
472 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
476 // Do not call this twice
477 trigger_error(__METHOD__ . ': Called twice.');
483 * The __call() method where all non-implemented methods end up
485 * @param $methodName Name of the missing method
486 * @args $args Arguments passed to the method
489 public final function __call ($methodName, $args) {
491 self::$instance = $this;
493 // Call static method
494 self::__callStatic($methodName, $args);
496 // Clear self-instance
497 self::$instance = NULL;
501 * The __callStatic() method where all non-implemented static methods end up
503 * @param $methodName Name of the missing method
504 * @param $args Arguments passed to the method
506 * @throws InvalidArgumentException If self::$instance is not a framework's own object
508 public static final function __callStatic ($methodName, $args) {
510 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
512 // Init argument string and class name
514 $className = 'unknown';
516 // Is self-instance set?
517 if (self::$instance instanceof FrameworkInterface) {
518 // Framework's own instance
519 $className = self::$instance->__toString();
520 } elseif (!is_null(self::$instance)) {
522 throw new InvalidArgumentException(sprintf('self::instance[%s] is not expected.', gettype(self::$instance)), self::EXCEPTION_SELF_INSTANCE);
525 // Is it NULL, empty or an array?
526 if (is_null($args)) {
528 $argsString = 'NULL';
529 } elseif (is_array($args)) {
533 // Some arguments are there
534 foreach ($args as $arg) {
535 // Add data about the argument
536 $argsString .= gettype($arg) . ':';
539 // Found a NULL argument
540 $argsString .= 'NULL';
541 } elseif (is_string($arg)) {
542 // Add length for strings
543 $argsString .= strlen($arg);
544 } elseif ((is_int($arg)) || (is_float($arg))) {
547 } elseif (is_array($arg)) {
548 // .. or size if array
549 $argsString .= count($arg);
550 } elseif (is_object($arg)) {
552 $reflection = new ReflectionClass($arg);
554 // Is an other object, maybe no __toString() available
555 $argsString .= $reflection->getName();
556 } elseif ($arg === true) {
557 // ... is boolean 'true'
558 $argsString .= 'true';
559 } elseif ($arg === false) {
560 // ... is boolean 'false'
561 $argsString .= 'false';
564 // Comma for next one
569 if (substr($argsString, -2, 1) == ',') {
571 $argsString = substr($argsString, 0, -2);
577 // Invalid arguments!
578 $argsString = sprintf('!INVALID:%s!', gettype($args));
581 // Output stub message
582 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
583 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s::%s]: Stub! Args: %s',
594 * Getter for $realClass
596 * @return $realClass The name of the real class (not BaseFrameworkSystem)
598 public function __toString () {
599 return $this->realClass;
603 * Magic method to catch setting of missing but set class fields/attributes
605 * @param $name Name of the field/attribute
606 * @param $value Value to store
609 public final function __set ($name, $value) {
610 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
613 print_r($value, true)
618 * Magic method to catch getting of missing fields/attributes
620 * @param $name Name of the field/attribute
623 public final function __get ($name) {
624 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
630 * Magic method to catch unsetting of missing fields/attributes
632 * @param $name Name of the field/attribute
635 public final function __unset ($name) {
636 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
642 * Magic method to catch object serialization
644 * @return $unsupported Unsupported method
645 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
647 public final function __sleep () {
648 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
652 * Magic method to catch object deserialization
654 * @return $unsupported Unsupported method
655 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
657 public final function __wakeup () {
658 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
662 * Magic method to catch calls when an object instance is called
664 * @return $unsupported Unsupported method
665 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
667 public final function __invoke () {
668 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
672 * Setter for the real class name
674 * @param $realClass Class name (string)
677 public final function setRealClass ($realClass) {
679 $this->realClass = (string) $realClass;
683 * Setter for database result instance
685 * @param $resultInstance An instance of a database result class
687 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
689 protected final function setResultInstance (SearchableResult $resultInstance) {
690 $this->resultInstance = $resultInstance;
694 * Getter for database result instance
696 * @return $resultInstance An instance of a database result class
698 public final function getResultInstance () {
699 return $this->resultInstance;
703 * Setter for template engine instances
705 * @param $templateInstance An instance of a template engine class
708 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
709 $this->templateInstance = $templateInstance;
713 * Getter for template engine instances
715 * @return $templateInstance An instance of a template engine class
717 protected final function getTemplateInstance () {
718 return $this->templateInstance;
722 * Setter for search instance
724 * @param $searchInstance Searchable criteria instance
727 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
728 $this->searchInstance = $searchInstance;
732 * Getter for search instance
734 * @return $searchInstance Searchable criteria instance
736 public final function getSearchInstance () {
737 return $this->searchInstance;
741 * Setter for update instance
743 * @param $updateInstance An instance of a LocalUpdateCriteria clase
746 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
747 $this->updateInstance = $updateInstance;
751 * Getter for update instance
753 * @return $updateInstance Updateable criteria instance
755 public final function getUpdateInstance () {
756 return $this->updateInstance;
760 * Setter for resolver instance
762 * @param $resolverInstance Instance of a command resolver class
765 public final function setResolverInstance (Resolver $resolverInstance) {
766 $this->resolverInstance = $resolverInstance;
770 * Getter for resolver instance
772 * @return $resolverInstance Instance of a command resolver class
774 public final function getResolverInstance () {
775 return $this->resolverInstance;
779 * Setter for language instance
781 * @param $configInstance The configuration instance which shall
782 * be FrameworkConfiguration
785 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
786 GenericRegistry::getRegistry()->addInstance('config', $configInstance);
790 * Getter for configuration instance
792 * @return $configInstance Configuration instance
794 public final function getConfigInstance () {
795 $configInstance = GenericRegistry::getRegistry()->getInstance('config');
796 return $configInstance;
800 * Setter for debug instance
802 * @param $debugInstance The instance for debug output class
805 public final function setDebugInstance (DebugMiddleware $debugInstance) {
806 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
810 * Getter for debug instance
812 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
814 public final function getDebugInstance () {
815 // Get debug instance
816 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
819 return $debugInstance;
823 * Setter for web output instance
825 * @param $webInstance The instance for web output class
828 public final function setWebOutputInstance (OutputStreamer $webInstance) {
829 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
833 * Getter for web output instance
835 * @return $webOutputInstance - Instance to class WebOutput
837 public final function getWebOutputInstance () {
838 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
839 return $webOutputInstance;
843 * Setter for database instance
845 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
848 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
849 GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
853 * Getter for database layer
855 * @return $databaseInstance The database layer instance
857 public final function getDatabaseInstance () {
859 $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
862 return $databaseInstance;
866 * Setter for compressor channel
868 * @param $compressorInstance An instance of CompressorChannel
871 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
872 GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
876 * Getter for compressor channel
878 * @return $compressorInstance The compressor channel
880 public final function getCompressorChannel () {
881 $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
882 return $compressorInstance;
886 * Private getter for language instance
888 * @return $langInstance An instance to the language sub-system
890 protected final function getLanguageInstance () {
891 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
892 return $langInstance;
896 * Setter for language instance
898 * @param $langInstance An instance to the language sub-system
900 * @see LanguageSystem
902 public final function setLanguageInstance (ManageableLanguage $langInstance) {
903 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
907 * Private getter for file IO instance
909 * @return $fileIoInstance An instance to the file I/O sub-system
911 protected final function getFileIoInstance () {
912 return $this->fileIoInstance;
916 * Setter for file I/O instance
918 * @param $fileIoInstance An instance to the file I/O sub-system
921 public final function setFileIoInstance (IoHandler $fileIoInstance) {
922 $this->fileIoInstance = $fileIoInstance;
926 * Protected setter for user instance
928 * @param $userInstance An instance of a user class
931 protected final function setUserInstance (ManageableAccount $userInstance) {
932 $this->userInstance = $userInstance;
936 * Getter for user instance
938 * @return $userInstance An instance of a user class
940 public final function getUserInstance () {
941 return $this->userInstance;
945 * Setter for controller instance (this surely breaks a bit the MVC patterm)
947 * @param $controllerInstance An instance of the controller
950 public final function setControllerInstance (Controller $controllerInstance) {
951 $this->controllerInstance = $controllerInstance;
955 * Getter for controller instance (this surely breaks a bit the MVC patterm)
957 * @return $controllerInstance An instance of the controller
959 public final function getControllerInstance () {
960 return $this->controllerInstance;
964 * Setter for RNG instance
966 * @param $rngInstance An instance of a random number generator (RNG)
969 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
970 $this->rngInstance = $rngInstance;
974 * Getter for RNG instance
976 * @return $rngInstance An instance of a random number generator (RNG)
978 public final function getRngInstance () {
979 return $this->rngInstance;
983 * Setter for Cryptable instance
985 * @param $cryptoInstance An instance of a Cryptable class
988 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
989 $this->cryptoInstance = $cryptoInstance;
993 * Getter for Cryptable instance
995 * @return $cryptoInstance An instance of a Cryptable class
997 public final function getCryptoInstance () {
998 return $this->cryptoInstance;
1002 * Setter for the list instance
1004 * @param $listInstance A list of Listable
1007 protected final function setListInstance (Listable $listInstance) {
1008 $this->listInstance = $listInstance;
1012 * Getter for the list instance
1014 * @return $listInstance A list of Listable
1016 protected final function getListInstance () {
1017 return $this->listInstance;
1021 * Setter for the menu instance
1023 * @param $menuInstance A RenderableMenu instance
1026 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1027 $this->menuInstance = $menuInstance;
1031 * Getter for the menu instance
1033 * @return $menuInstance A RenderableMenu instance
1035 protected final function getMenuInstance () {
1036 return $this->menuInstance;
1040 * Setter for image instance
1042 * @param $imageInstance An instance of an image
1045 public final function setImageInstance (BaseImage $imageInstance) {
1046 $this->imageInstance = $imageInstance;
1050 * Getter for image instance
1052 * @return $imageInstance An instance of an image
1054 public final function getImageInstance () {
1055 return $this->imageInstance;
1059 * Setter for stacker instance
1061 * @param $stackInstance An instance of an stacker
1064 public final function setStackInstance (Stackable $stackInstance) {
1065 $this->stackInstance = $stackInstance;
1069 * Getter for stacker instance
1071 * @return $stackInstance An instance of an stacker
1073 public final function getStackInstance () {
1074 return $this->stackInstance;
1078 * Setter for compressor instance
1080 * @param $compressorInstance An instance of an compressor
1083 public final function setCompressorInstance (Compressor $compressorInstance) {
1084 $this->compressorInstance = $compressorInstance;
1088 * Getter for compressor instance
1090 * @return $compressorInstance An instance of an compressor
1092 public final function getCompressorInstance () {
1093 return $this->compressorInstance;
1097 * Setter for Parseable instance
1099 * @param $parserInstance An instance of an Parseable
1102 public final function setParserInstance (Parseable $parserInstance) {
1103 $this->parserInstance = $parserInstance;
1107 * Getter for Parseable instance
1109 * @return $parserInstance An instance of an Parseable
1111 public final function getParserInstance () {
1112 return $this->parserInstance;
1116 * Setter for DatabaseWrapper instance
1118 * @param $wrapperInstance An instance of an DatabaseWrapper
1121 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1122 $this->wrapperInstance = $wrapperInstance;
1126 * Getter for DatabaseWrapper instance
1128 * @return $wrapperInstance An instance of an DatabaseWrapper
1130 public final function getWrapperInstance () {
1131 return $this->wrapperInstance;
1135 * Setter for helper instance
1137 * @param $helperInstance An instance of a helper class
1140 protected final function setHelperInstance (Helper $helperInstance) {
1141 $this->helperInstance = $helperInstance;
1145 * Getter for helper instance
1147 * @return $helperInstance An instance of a helper class
1149 public final function getHelperInstance () {
1150 return $this->helperInstance;
1154 * Getter for a InputStream instance
1156 * @param $inputStreamInstance The InputStream instance
1158 protected final function getInputStreamInstance () {
1159 return $this->inputStreamInstance;
1163 * Setter for a InputStream instance
1165 * @param $inputStreamInstance The InputStream instance
1168 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1169 $this->inputStreamInstance = $inputStreamInstance;
1173 * Getter for a OutputStream instance
1175 * @param $outputStreamInstance The OutputStream instance
1177 protected final function getOutputStreamInstance () {
1178 return $this->outputStreamInstance;
1182 * Setter for a OutputStream instance
1184 * @param $outputStreamInstance The OutputStream instance
1187 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1188 $this->outputStreamInstance = $outputStreamInstance;
1192 * Setter for handler instance
1194 * @param $handlerInstance An instance of a Handleable class
1197 protected final function setHandlerInstance (Handleable $handlerInstance) {
1198 $this->handlerInstance = $handlerInstance;
1202 * Getter for handler instance
1204 * @return $handlerInstance A Handleable instance
1206 protected final function getHandlerInstance () {
1207 return $this->handlerInstance;
1211 * Setter for visitor instance
1213 * @param $visitorInstance A Visitor instance
1216 protected final function setVisitorInstance (Visitor $visitorInstance) {
1217 $this->visitorInstance = $visitorInstance;
1221 * Getter for visitor instance
1223 * @return $visitorInstance A Visitor instance
1225 protected final function getVisitorInstance () {
1226 return $this->visitorInstance;
1230 * Setter for Iterator instance
1232 * @param $iteratorInstance An instance of an Iterator
1235 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1236 $this->iteratorInstance = $iteratorInstance;
1240 * Getter for Iterator instance
1242 * @return $iteratorInstance An instance of an Iterator
1244 public final function getIteratorInstance () {
1245 return $this->iteratorInstance;
1249 * Setter for FilePointer instance
1251 * @param $pointerInstance An instance of an FilePointer class
1254 protected final function setPointerInstance (FilePointer $pointerInstance) {
1255 $this->pointerInstance = $pointerInstance;
1259 * Getter for FilePointer instance
1261 * @return $pointerInstance An instance of an FilePointer class
1263 public final function getPointerInstance () {
1264 return $this->pointerInstance;
1268 * Unsets pointer instance which triggers a call of __destruct() if the
1269 * instance is still there. This is surely not fatal on already "closed"
1270 * file pointer instances.
1272 * I don't want to mess around with above setter by giving it a default
1273 * value NULL as setter should always explicitly only set (existing) object
1274 * instances and NULL is NULL.
1278 protected final function unsetPointerInstance () {
1279 // Simply it to NULL
1280 $this->pointerInstance = NULL;
1284 * Setter for Indexable instance
1286 * @param $indexInstance An instance of an Indexable class
1289 protected final function setIndexInstance (Indexable $indexInstance) {
1290 $this->indexInstance = $indexInstance;
1294 * Getter for Indexable instance
1296 * @return $indexInstance An instance of an Indexable class
1298 public final function getIndexInstance () {
1299 return $this->indexInstance;
1303 * Setter for Block instance
1305 * @param $blockInstance An instance of an Block class
1308 protected final function setBlockInstance (Block $blockInstance) {
1309 $this->blockInstance = $blockInstance;
1313 * Getter for Block instance
1315 * @return $blockInstance An instance of an Block class
1317 public final function getBlockInstance () {
1318 return $this->blockInstance;
1322 * Setter for FrameworkDirectory instance
1324 * @param $directoryInstance A FrameworkDirectory instance
1327 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1328 $this->directoryInstance = $directoryInstance;
1332 * Getter for FrameworkDirectory instance
1334 * @return $directoryInstance A FrameworkDirectory instance
1336 protected final function getDirectoryInstance () {
1337 return $this->directoryInstance;
1341 * Setter for state instance
1343 * @param $stateInstance A Stateable instance
1346 public final function setStateInstance (Stateable $stateInstance) {
1347 $this->stateInstance = $stateInstance;
1351 * Getter for state instance
1353 * @return $stateInstance A Stateable instance
1355 public final function getStateInstance () {
1356 return $this->stateInstance;
1360 * Setter for output instance
1362 * @param $outputInstance The debug output instance
1365 public final function setOutputInstance (OutputStreamer $outputInstance) {
1366 $this->outputInstance = $outputInstance;
1370 * Getter for output instance
1372 * @return $outputInstance The debug output instance
1374 public final function getOutputInstance () {
1375 return $this->outputInstance;
1379 * Setter for registry instance
1381 * @param $registryInstance An instance of a Register class
1384 protected final function setRegistryInstance (Register $registryInstance) {
1385 $this->registryInstance = $registryInstance;
1389 * Getter for registry instance
1391 * @return $registryInstance The debug registry instance
1393 public final function getRegistryInstance () {
1394 return $this->registryInstance;
1398 * Setter for call-back instance
1400 * @param $callbackInstance An instance of a FrameworkInterface class
1403 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1404 $this->callbackInstance = $callbackInstance;
1408 * Getter for call-back instance
1410 * @return $callbackInstance An instance of a FrameworkInterface class
1412 protected final function getCallbackInstance () {
1413 return $this->callbackInstance;
1417 * Setter for command name
1419 * @param $commandName Last validated command name
1422 protected final function setCommandName ($commandName) {
1423 $this->commandName = $commandName;
1427 * Getter for command name
1429 * @return $commandName Last validated command name
1431 protected final function getCommandName () {
1432 return $this->commandName;
1436 * Setter for controller name
1438 * @param $controllerName Last validated controller name
1441 protected final function setControllerName ($controllerName) {
1442 $this->controllerName = $controllerName;
1446 * Getter for controller name
1448 * @return $controllerName Last validated controller name
1450 protected final function getControllerName () {
1451 return $this->controllerName;
1455 * Checks whether an object equals this object. You should overwrite this
1456 * method to implement own equality checks
1458 * @param $objectInstance An instance of a FrameworkInterface object
1459 * @return $equals Whether both objects equals
1461 public function equals (FrameworkInterface $objectInstance) {
1464 $this->__toString() == $objectInstance->__toString()
1466 $this->hashCode() == $objectInstance->hashCode()
1469 // Return the result
1474 * Generates a generic hash code of this class. You should really overwrite
1475 * this method with your own hash code generator code. But keep KISS in mind.
1477 * @return $hashCode A generic hash code respresenting this whole class
1479 public function hashCode () {
1481 return crc32($this->__toString());
1485 * Formats computer generated price values into human-understandable formats
1486 * with thousand and decimal separators.
1488 * @param $value The in computer format value for a price
1489 * @param $currency The currency symbol (use HTML-valid characters!)
1490 * @param $decNum Number of decimals after commata
1491 * @return $price The for the current language formated price string
1492 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1493 * thousands separator
1496 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1497 // Are all required attriutes set?
1498 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1499 // Throw an exception
1500 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1504 $value = (float) $value;
1506 // Reformat the US number
1507 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1509 // Return as string...
1514 * Appends a trailing slash to a string
1516 * @param $str A string (maybe) without trailing slash
1517 * @return $str A string with an auto-appended trailing slash
1519 public final function addMissingTrailingSlash ($str) {
1520 // Is there a trailing slash?
1521 if (substr($str, -1, 1) != '/') {
1525 // Return string with trailing slash
1530 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1531 * application helper instance (ApplicationHelper by default).
1533 * @param $applicationInstance An application helper instance or
1534 * null if we shall use the default
1535 * @return $templateInstance The template engine instance
1536 * @throws NullPointerException If the discovered application
1537 * instance is still null
1539 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1540 // Is the application instance set?
1541 if (is_null($applicationInstance)) {
1542 // Get the current instance
1543 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1546 if (is_null($applicationInstance)) {
1547 // Thrown an exception
1548 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1552 // Initialize the template engine
1553 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1555 // Return the prepared instance
1556 return $templateInstance;
1560 * Debugs this instance by putting out it's full content
1562 * @param $message Optional message to show in debug output
1565 public final function debugInstance ($message = '') {
1566 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1567 restore_error_handler();
1572 // Is a message set?
1573 if (!empty($message)) {
1574 // Construct message
1575 $content = sprintf('<div class="debug_message">
1577 </div>' . PHP_EOL, $message);
1580 // Generate the output
1581 $content .= sprintf('<pre>%s</pre>',
1584 print_r($this, true)
1590 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1593 <div class="debug_content">
1597 <div class="debug_include_list">
1600 $this->__toString(),
1602 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1607 * Replaces control characters with printable output
1609 * @param $str String with control characters
1610 * @return $str Replaced string
1612 protected function replaceControlCharacters ($str) {
1615 chr(13), '[r]', str_replace(
1616 chr(10), '[n]', str_replace(
1626 * Output a partial stub message for the caller method
1628 * @param $message An optional message to display
1631 protected function partialStub ($message = '') {
1633 $stubMessage = 'Partial stub!';
1635 // Is an extra message given?
1636 if (!empty($message)) {
1637 // Then add it as well
1638 $stubMessage .= ' Message: ' . $message;
1641 // Debug instance is there?
1642 if (!is_null($this->getDebugInstance())) {
1643 // Output stub message
1644 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1647 trigger_error($stubMessage);
1653 * Outputs a debug backtrace and stops further script execution
1655 * @param $message An optional message to output
1656 * @param $doExit Whether exit the program (true is default)
1659 public function debugBackTrace ($message = '', $doExit = true) {
1660 // Sorry, there is no other way getting this nice backtrace
1661 if (!empty($message)) {
1663 printf('Message: %s<br />' . PHP_EOL, $message);
1667 debug_print_backtrace();
1671 if ($doExit === true) {
1677 * Creates an instance of a debugger instance
1679 * @param $className Name of the class (currently unsupported)
1680 * @param $lineNumber Line number where the call was made
1681 * @return $debugInstance An instance of a debugger class
1682 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1684 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1685 // Is the instance set?
1686 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1687 // Init debug instance
1688 $debugInstance = NULL;
1692 // Get a debugger instance
1693 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1694 } catch (NullPointerException $e) {
1695 // Didn't work, no instance there
1696 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1699 // Empty string should be ignored and used for testing the middleware
1700 DebugMiddleware::getSelfInstance()->output('');
1702 // Set it in registry
1703 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1705 // Get instance from registry
1706 $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1710 return $debugInstance;
1714 * Simple output of a message with line-break
1716 * @param $message Message to output
1719 public function outputLine ($message) {
1721 print($message . PHP_EOL);
1725 * Outputs a debug message whether to debug instance (should be set!) or
1726 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1727 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1729 * @param $message Message we shall send out...
1730 * @param $doPrint Whether print or die here (default: print)
1731 * @paran $stripTags Whether to strip tags (default: false)
1734 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1735 // Set debug instance to NULL
1736 $debugInstance = NULL;
1739 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1741 // Is function partialStub/__callStatic ?
1742 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1743 // Prepend class::function:line from 3rd element
1744 $message = sprintf('[%s::%s:%d]: %s',
1745 $backtrace[2]['class'],
1746 $backtrace[2]['function'],
1747 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1751 // Prepend class::function:line from 2nd element
1752 $message = sprintf('[%s::%s:%d]: %s',
1753 $backtrace[1]['class'],
1754 $backtrace[1]['function'],
1755 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1762 // Get debug instance
1763 $debugInstance = $this->getDebugInstance();
1764 } catch (NullPointerException $e) {
1765 // The debug instance is not set (yet)
1768 // Is the debug instance there?
1769 if (is_object($debugInstance)) {
1770 // Use debug output handler
1771 $debugInstance->output($message, $stripTags);
1773 if ($doPrint === false) {
1774 // Die here if not printed
1778 // Are debug times enabled?
1779 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1781 $message = $this->getPrintableExecutionTime() . $message;
1785 if ($doPrint === true) {
1787 $this->outputLine($message);
1796 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1798 * @param $str The string, what ever it is needs to be converted
1799 * @return $className Generated class name
1801 public static final function convertToClassName ($str) {
1805 // Convert all dashes in underscores
1806 $str = StringUtils::convertDashesToUnderscores($str);
1808 // Now use that underscores to get classname parts for hungarian style
1809 foreach (explode('_', $str) as $strPart) {
1810 // Make the class name part lower case and first upper case
1811 $className .= ucfirst(strtolower($strPart));
1814 // Return class name
1819 * Marks up the code by adding e.g. line numbers
1821 * @param $phpCode Unmarked PHP code
1822 * @return $markedCode Marked PHP code
1824 public function markupCode ($phpCode) {
1829 $errorArray = error_get_last();
1831 // Init the code with error message
1832 if (is_array($errorArray)) {
1834 $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>',
1835 basename($errorArray['file']),
1836 $errorArray['line'],
1837 $errorArray['message'],
1842 // Add line number to the code
1843 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1845 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1847 htmlentities($code, ENT_QUOTES)
1856 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1857 * beatiful for web-based front-ends. If null is given a message id
1858 * null_timestamp will be resolved and returned.
1860 * @param $timestamp Timestamp to prepare (filter) for display
1861 * @return $readable A readable timestamp
1863 public function doFilterFormatTimestamp ($timestamp) {
1864 // Default value to return
1867 // Is the timestamp null?
1868 if (is_null($timestamp)) {
1869 // Get a message string
1870 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1872 switch ($this->getLanguageInstance()->getLanguageCode()) {
1873 case 'de': // German format is a bit different to default
1874 // Split the GMT stamp up
1875 $dateTime = explode(' ', $timestamp );
1876 $dateArray = explode('-', $dateTime[0]);
1877 $timeArray = explode(':', $dateTime[1]);
1879 // Construct the timestamp
1880 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1890 default: // Default is pass-through
1891 $readable = $timestamp;
1901 * Filter a given number into a localized number
1903 * @param $value The raw value from e.g. database
1904 * @return $localized Localized value
1906 public function doFilterFormatNumber ($value) {
1907 // Generate it from config and localize dependencies
1908 switch ($this->getLanguageInstance()->getLanguageCode()) {
1909 case 'de': // German format is a bit different to default
1910 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1913 default: // US, etc.
1914 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1923 * "Getter" for databse entry
1925 * @return $entry An array with database entries
1926 * @throws NullPointerException If the database result is not found
1927 * @throws InvalidDatabaseResultException If the database result is invalid
1929 protected final function getDatabaseEntry () {
1930 // Is there an instance?
1931 if (!$this->getResultInstance() instanceof SearchableResult) {
1932 // Throw an exception here
1933 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1937 $this->getResultInstance()->rewind();
1939 // Do we have an entry?
1940 if ($this->getResultInstance()->valid() === false) {
1941 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
1942 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1946 $this->getResultInstance()->next();
1949 $entry = $this->getResultInstance()->current();
1956 * Getter for field name
1958 * @param $fieldName Field name which we shall get
1959 * @return $fieldValue Field value from the user
1960 * @throws NullPointerException If the result instance is null
1962 public final function getField ($fieldName) {
1963 // Default field value
1966 // Get result instance
1967 $resultInstance = $this->getResultInstance();
1969 // Is this instance null?
1970 if (is_null($resultInstance)) {
1971 // Then the user instance is no longer valid (expired cookies?)
1972 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1975 // Get current array
1976 $fieldArray = $resultInstance->current();
1977 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1979 // Convert dashes to underscore
1980 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
1982 // Does the field exist?
1983 if ($this->isFieldSet($fieldName)) {
1985 $fieldValue = $fieldArray[$fieldName2];
1986 } elseif (defined('DEVELOPER')) {
1987 // Missing field entry, may require debugging
1988 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
1990 // Missing field entry, may require debugging
1991 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
1999 * Checks if given field is set
2001 * @param $fieldName Field name to check
2002 * @return $isSet Whether the given field name is set
2003 * @throws NullPointerException If the result instance is null
2005 public function isFieldSet ($fieldName) {
2006 // Get result instance
2007 $resultInstance = $this->getResultInstance();
2009 // Is this instance null?
2010 if (is_null($resultInstance)) {
2011 // Then the user instance is no longer valid (expired cookies?)
2012 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2015 // Get current array
2016 $fieldArray = $resultInstance->current();
2017 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2019 // Convert dashes to underscore
2020 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
2023 $isSet = isset($fieldArray[$fieldName]);
2030 * Flushs all pending updates to the database layer
2034 public function flushPendingUpdates () {
2035 // Get result instance
2036 $resultInstance = $this->getResultInstance();
2038 // Do we have data to update?
2039 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2040 // Get wrapper class name config entry
2041 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2043 // Create object instance
2044 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2046 // Yes, then send the whole result to the database layer
2047 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2052 * Outputs a deprecation warning to the developer.
2054 * @param $message The message we shall output to the developer
2056 * @todo Write a logging mechanism for productive mode
2058 public function deprecationWarning ($message) {
2059 // Is developer mode active?
2060 if (defined('DEVELOPER')) {
2061 // Debug instance is there?
2062 if (!is_null($this->getDebugInstance())) {
2063 // Output stub message
2064 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2067 trigger_error($message . "<br />\n");
2071 // @TODO Finish this part!
2072 $this->partialStub('Developer mode inactive. Message:' . $message);
2077 * Checks whether the given PHP extension is loaded
2079 * @param $phpExtension The PHP extension we shall check
2080 * @return $isLoaded Whether the PHP extension is loaded
2082 public final function isPhpExtensionLoaded ($phpExtension) {
2084 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2091 * "Getter" as a time() replacement but with milliseconds. You should use this
2092 * method instead of the encapsulated getimeofday() function.
2094 * @return $milliTime Timestamp with milliseconds
2096 public function getMilliTime () {
2097 // Get the time of day as float
2098 $milliTime = gettimeofday(true);
2105 * Idles (sleeps) for given milliseconds
2107 * @return $hasSlept Whether it goes fine
2109 public function idle ($milliSeconds) {
2110 // Sleep is fine by default
2113 // Idle so long with found function
2114 if (function_exists('time_sleep_until')) {
2115 // Get current time and add idle time
2116 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2118 // New PHP 5.1.0 function found, ignore errors
2119 $hasSlept = @time_sleep_until($sleepUntil);
2122 * My Sun station doesn't have that function even with latest PHP
2125 usleep($milliSeconds * 1000);
2132 * Converts a hexadecimal string, even with negative sign as first string to
2133 * a decimal number using BC functions.
2135 * This work is based on comment #86673 on php.net documentation page at:
2136 * <http://de.php.net/manual/en/function.dechex.php#86673>
2138 * @param $hex Hexadecimal string
2139 * @return $dec Decimal number
2141 protected function hex2dec ($hex) {
2142 // Convert to all lower-case
2143 $hex = strtolower($hex);
2145 // Detect sign (negative/positive numbers)
2147 if (substr($hex, 0, 1) == '-') {
2149 $hex = substr($hex, 1);
2152 // Decode the hexadecimal string into a decimal number
2154 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2155 $factor = self::$hexdec[substr($hex, $i, 1)];
2156 $dec = bcadd($dec, bcmul($factor, $e));
2159 // Return the decimal number
2160 return $sign . $dec;
2164 * Converts even very large decimal numbers, also signed, to a hexadecimal
2167 * This work is based on comment #97756 on php.net documentation page at:
2168 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2170 * @param $dec Decimal number, even with negative sign
2171 * @param $maxLength Optional maximum length of the string
2172 * @return $hex Hexadecimal string
2174 protected function dec2hex ($dec, $maxLength = 0) {
2175 // maxLength can be zero or devideable by 2
2176 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2178 // Detect sign (negative/positive numbers)
2185 // Encode the decimal number into a hexadecimal string
2188 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2190 } while ($dec >= 1);
2193 * Leading zeros are required for hex-decimal "numbers". In some
2194 * situations more leading zeros are wanted, so check for both
2197 if ($maxLength > 0) {
2198 // Prepend more zeros
2199 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2200 } elseif ((strlen($hex) % 2) != 0) {
2201 // Only make string's length dividable by 2
2205 // Return the hexadecimal string
2206 return $sign . $hex;
2210 * Converts a ASCII string (0 to 255) into a decimal number.
2212 * @param $asc The ASCII string to be converted
2213 * @return $dec Decimal number
2215 protected function asc2dec ($asc) {
2216 // Convert it into a hexadecimal number
2217 $hex = bin2hex($asc);
2219 // And back into a decimal number
2220 $dec = $this->hex2dec($hex);
2227 * Converts a decimal number into an ASCII string.
2229 * @param $dec Decimal number
2230 * @return $asc An ASCII string
2232 protected function dec2asc ($dec) {
2233 // First convert the number into a hexadecimal string
2234 $hex = $this->dec2hex($dec);
2236 // Then convert it into the ASCII string
2237 $asc = $this->hex2asc($hex);
2244 * Converts a hexadecimal number into an ASCII string. Negative numbers
2247 * @param $hex Hexadecimal string
2248 * @return $asc An ASCII string
2250 protected function hex2asc ($hex) {
2251 // Check for length, it must be devideable by 2
2252 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2253 assert((strlen($hex) % 2) == 0);
2257 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2258 // Get the decimal number of the chunk
2259 $part = hexdec(substr($hex, $idx, 2));
2261 // Add it to the final string
2265 // Return the final string
2270 * Checks whether the given encoded data was encoded with Base64
2272 * @param $encodedData Encoded data we shall check
2273 * @return $isBase64 Whether the encoded data is Base64
2275 protected function isBase64Encoded ($encodedData) {
2277 $isBase64 = (@base64_decode($encodedData, true) !== false);
2284 * Gets a cache key from Criteria instance
2286 * @param $criteriaInstance An instance of a Criteria class
2287 * @param $onlyKeys Only use these keys for a cache key
2288 * @return $cacheKey A cache key suitable for lookup/storage purposes
2290 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2292 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: criteriaInstance=' . $criteriaInstance->__toString() . ',onlyKeys()=' . count($onlyKeys) . ' - CALLED!');
2293 $cacheKey = sprintf('%s@%s',
2294 $this->__toString(),
2295 $criteriaInstance->getCacheKey($onlyKeys)
2299 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: cacheKey=' . $cacheKey . ' - EXIT!');
2304 * Getter for startup time in miliseconds
2306 * @return $startupTime Startup time in miliseconds
2308 protected function getStartupTime () {
2309 return self::$startupTime;
2313 * "Getter" for a printable currently execution time in nice braces
2315 * @return $executionTime Current execution time in nice braces
2317 protected function getPrintableExecutionTime () {
2318 // Caculate the execution time
2319 $executionTime = microtime(true) - $this->getStartupTime();
2321 // Pack it in nice braces
2322 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2325 return $executionTime;
2329 * Hashes a given string with a simple but stronger hash function (no salt)
2330 * and hex-encode it.
2332 * @param $str The string to be hashed
2333 * @return $hash The hash from string $str
2335 public static final function hash ($str) {
2336 // Hash given string with (better secure) hasher
2337 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2344 * "Getter" for length of hash() output. This will be "cached" to speed up
2347 * @return $length Length of hash() output
2349 public static final function getHashLength () {
2351 if (is_null(self::$hashLength)) {
2352 // No, then hash a string and save its length.
2353 self::$hashLength = strlen(self::hash('abc123'));
2357 return self::$hashLength;
2361 * Checks whether the given number is really a number (only chars 0-9).
2363 * @param $num A string consisting only chars between 0 and 9
2364 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2365 * @param $assertMismatch Whether to assert mismatches
2366 * @return $ret The (hopefully) secured numbered value
2368 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2369 // Filter all numbers out
2370 $ret = preg_replace('/[^0123456789]/', '', $num);
2373 if ($castValue === true) {
2374 // Cast to biggest numeric type
2375 $ret = (double) $ret;
2378 // Assert only if requested
2379 if ($assertMismatch === true) {
2380 // Has the whole value changed?
2381 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2389 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2391 * @param $num A string consisting only chars between 0 and 9
2392 * @param $assertMismatch Whether to assert mismatches
2393 * @return $ret The (hopefully) secured hext-numbered value
2395 public function hexval ($num, $assertMismatch = false) {
2396 // Filter all numbers out
2397 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2399 // Assert only if requested
2400 if ($assertMismatch === true) {
2401 // Has the whole value changed?
2402 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2410 * Determines if an element is set in the generic array
2412 * @param $keyGroup Main group for the key
2413 * @param $subGroup Sub group for the key
2414 * @param $key Key to check
2415 * @param $element Element to check
2416 * @return $isset Whether the given key is set
2418 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2420 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2423 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2429 * Determines if a key is set in the generic array
2431 * @param $keyGroup Main group for the key
2432 * @param $subGroup Sub group for the key
2433 * @param $key Key to check
2434 * @return $isset Whether the given key is set
2436 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2438 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2441 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2449 * Determines if a group is set in the generic array
2451 * @param $keyGroup Main group
2452 * @param $subGroup Sub group
2453 * @return $isset Whether the given group is set
2455 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2457 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2460 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2467 * Getter for sub key group
2469 * @param $keyGroup Main key group
2470 * @param $subGroup Sub key group
2471 * @return $array An array with all array elements
2473 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2475 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2476 // No, then abort here
2477 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2482 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2485 return $this->genericArray[$keyGroup][$subGroup];
2489 * Unsets a given key in generic array
2491 * @param $keyGroup Main group for the key
2492 * @param $subGroup Sub group for the key
2493 * @param $key Key to unset
2496 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2498 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2501 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2505 * Unsets a given element in generic array
2507 * @param $keyGroup Main group for the key
2508 * @param $subGroup Sub group for the key
2509 * @param $key Key to unset
2510 * @param $element Element to unset
2513 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2515 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2518 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2522 * Append a string to a given generic array key
2524 * @param $keyGroup Main group for the key
2525 * @param $subGroup Sub group for the key
2526 * @param $key Key to unset
2527 * @param $value Value to add/append
2530 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2532 //* 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);
2534 // Is it already there?
2535 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2537 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2540 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2545 * Append a string to a given generic array element
2547 * @param $keyGroup Main group for the key
2548 * @param $subGroup Sub group for the key
2549 * @param $key Key to unset
2550 * @param $element Element to check
2551 * @param $value Value to add/append
2554 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2556 //* 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);
2558 // Is it already there?
2559 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2561 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2564 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2569 * Sets a string in a given generic array element
2571 * @param $keyGroup Main group for the key
2572 * @param $subGroup Sub group for the key
2573 * @param $key Key to unset
2574 * @param $element Element to check
2575 * @param $value Value to add/append
2578 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2580 //* 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);
2583 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2587 * Initializes given generic array group
2589 * @param $keyGroup Main group for the key
2590 * @param $subGroup Sub group for the key
2591 * @param $key Key to use
2592 * @param $forceInit Optionally force initialization
2595 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2597 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2599 // Is it already set?
2600 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2601 // Already initialized
2602 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2607 $this->genericArray[$keyGroup][$subGroup] = array();
2611 * Initializes given generic array key
2613 * @param $keyGroup Main group for the key
2614 * @param $subGroup Sub group for the key
2615 * @param $key Key to use
2616 * @param $forceInit Optionally force initialization
2619 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2621 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2623 // Is it already set?
2624 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2625 // Already initialized
2626 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2631 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2635 * Initializes given generic array element
2637 * @param $keyGroup Main group for the key
2638 * @param $subGroup Sub group for the key
2639 * @param $key Key to use
2640 * @param $element Element to use
2641 * @param $forceInit Optionally force initialization
2644 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2646 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2648 // Is it already set?
2649 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2650 // Already initialized
2651 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2656 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2660 * Pushes an element to a generic key
2662 * @param $keyGroup Main group for the key
2663 * @param $subGroup Sub group for the key
2664 * @param $key Key to use
2665 * @param $value Value to add/append
2666 * @return $count Number of array elements
2668 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2670 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2673 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2675 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2679 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2682 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2683 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2688 * Pushes an element to a generic array element
2690 * @param $keyGroup Main group for the key
2691 * @param $subGroup Sub group for the key
2692 * @param $key Key to use
2693 * @param $element Element to check
2694 * @param $value Value to add/append
2695 * @return $count Number of array elements
2697 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2699 //* 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));
2702 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2704 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2708 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2711 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2712 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2717 * Pops an element from a generic group
2719 * @param $keyGroup Main group for the key
2720 * @param $subGroup Sub group for the key
2721 * @param $key Key to unset
2722 * @return $value Last "popped" value
2724 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2726 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2729 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2731 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2736 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2739 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2740 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2745 * Shifts an element from a generic group
2747 * @param $keyGroup Main group for the key
2748 * @param $subGroup Sub group for the key
2749 * @param $key Key to unset
2750 * @return $value Last "popped" value
2752 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2754 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2757 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2759 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2764 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2767 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2768 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2773 * Count generic array group
2775 * @param $keyGroup Main group for the key
2776 * @return $count Count of given group
2778 protected final function countGenericArray ($keyGroup) {
2780 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2783 if (!isset($this->genericArray[$keyGroup])) {
2785 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2790 $count = count($this->genericArray[$keyGroup]);
2793 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2800 * Count generic array sub group
2802 * @param $keyGroup Main group for the key
2803 * @param $subGroup Sub group for the key
2804 * @return $count Count of given group
2806 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2808 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2811 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2813 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2818 $count = count($this->genericArray[$keyGroup][$subGroup]);
2821 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2828 * Count generic array elements
2830 * @param $keyGroup Main group for the key
2831 * @param $subGroup Sub group for the key
2832 * @para $key Key to count
2833 * @return $count Count of given key
2835 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2837 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2840 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2842 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2844 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2846 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2851 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2854 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2861 * Getter for whole generic group array
2863 * @param $keyGroup Key group to get
2864 * @return $array Whole generic array group
2866 protected final function getGenericArray ($keyGroup) {
2868 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2871 if (!isset($this->genericArray[$keyGroup])) {
2873 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2878 return $this->genericArray[$keyGroup];
2882 * Setter for generic array key
2884 * @param $keyGroup Key group to get
2885 * @param $subGroup Sub group for the key
2886 * @param $key Key to unset
2887 * @param $value Mixed value from generic array element
2890 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2892 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2895 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2899 * Getter for generic array key
2901 * @param $keyGroup Key group to get
2902 * @param $subGroup Sub group for the key
2903 * @param $key Key to unset
2904 * @return $value Mixed value from generic array element
2906 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2908 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2911 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2913 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2918 return $this->genericArray[$keyGroup][$subGroup][$key];
2922 * Sets a value in given generic array key/element
2924 * @param $keyGroup Main group for the key
2925 * @param $subGroup Sub group for the key
2926 * @param $key Key to set
2927 * @param $element Element to set
2928 * @param $value Value to set
2931 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2933 //* 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));
2936 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2940 * Getter for generic array element
2942 * @param $keyGroup Key group to get
2943 * @param $subGroup Sub group for the key
2944 * @param $key Key to look for
2945 * @param $element Element to look for
2946 * @return $value Mixed value from generic array element
2948 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2950 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2953 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2955 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2960 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2964 * Checks if a given sub group is valid (array)
2966 * @param $keyGroup Key group to get
2967 * @param $subGroup Sub group for the key
2968 * @return $isValid Whether given sub group is valid
2970 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2972 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2975 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2982 * Checks if a given key is valid (array)
2984 * @param $keyGroup Key group to get
2985 * @param $subGroup Sub group for the key
2986 * @param $key Key to check
2987 * @return $isValid Whether given sub group is valid
2989 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2991 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2994 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3001 * Initializes the web output instance
3005 protected function initWebOutputInstance () {
3006 // Get application instance
3007 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
3009 // Init web output instance
3010 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3013 $this->setWebOutputInstance($outputInstance);
3017 * Translates boolean true to 'Y' and false to 'N'
3019 * @param $boolean Boolean value
3020 * @return $translated Translated boolean value
3022 public static final function translateBooleanToYesNo ($boolean) {
3023 // Make sure it is really boolean
3024 assert(is_bool($boolean));
3027 $translated = ($boolean === true) ? 'Y' : 'N';
3029 // ... and return it
3034 * Encodes raw data (almost any type) by "serializing" it and then pack it
3035 * into a "binary format".
3037 * @param $rawData Raw data (almost any type)
3038 * @return $encoded Encoded data
3040 protected function encodeData ($rawData) {
3041 // Make sure no objects or resources pass through
3042 assert(!is_object($rawData));
3043 assert(!is_resource($rawData));
3045 // First "serialize" it (json_encode() is faster than serialize())
3046 $encoded = $this->packString(json_encode($rawData));
3053 * Pack a string into a "binary format". Please execuse me that this is
3054 * widely undocumented. :-(
3056 * @param $str Unpacked string
3057 * @return $packed Packed string
3058 * @todo Improve documentation
3060 protected function packString ($str) {
3062 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3064 // First compress the string (gzcompress is okay)
3065 $str = gzcompress($str);
3070 // And start the "encoding" loop
3071 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3073 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3074 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3076 if (($idx + $i) <= strlen($str)) {
3077 $ord = ord(substr($str, ($idx + $i), 1));
3079 $add = $ord * pow(256, $factor);
3083 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3087 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3088 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3090 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3091 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3097 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3102 * Creates a full-qualified file name (FQFN) for given file name by adding
3103 * a configured temporary file path to it.
3105 * @param $infoInstance An instance of a SplFileInfo class
3106 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3107 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3108 * @throws FileIoException If the file cannot be written
3110 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3112 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3114 // Is the path writeable?
3115 if (!is_writable($basePath)) {
3116 // Path is write-protected
3117 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3121 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3124 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3126 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3130 return $tempInstance;
3134 * "Getter" for a printable state name
3136 * @return $stateName Name of the node's state in a printable format
3138 public final function getPrintableState () {
3139 // Default is 'null'
3140 $stateName = 'null';
3142 // Get the state instance
3143 $stateInstance = $this->getStateInstance();
3145 // Is it an instance of Stateable?
3146 if ($stateInstance instanceof Stateable) {
3147 // Then use that state name
3148 $stateName = $stateInstance->getStateName();