]> git.mxchange.org Git - core.git/blob - framework/main/classes/class_BaseFrameworkSystem.php
ddfaef4682dcf5765e05689440168582cb9055b1
[core.git] / framework / main / classes / class_BaseFrameworkSystem.php
1 <?php
2 // Own namespace
3 namespace Org\Mxchange\CoreFramework\Object;
4
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\Helper\Helper;
29 use Org\Mxchange\CoreFramework\Index\Indexable;
30 use Org\Mxchange\CoreFramework\Lists\Listable;
31 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
32 use Org\Mxchange\CoreFramework\Localization\ManageableLanguage;
33 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
34 use Org\Mxchange\CoreFramework\Menu\RenderableMenu;
35 use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
36 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
37 use Org\Mxchange\CoreFramework\Parser\Parseable;
38 use Org\Mxchange\CoreFramework\Registry\GenericRegistry;
39 use Org\Mxchange\CoreFramework\Registry\Register;
40 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
41 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
42 use Org\Mxchange\CoreFramework\Stacker\Stackable;
43 use Org\Mxchange\CoreFramework\State\Stateable;
44 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
45 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
46 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
47 use Org\Mxchange\CoreFramework\String\Utils\StringUtils;
48 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
49 use Org\Mxchange\CoreFramework\User\ManageableAccount;
50 use Org\Mxchange\CoreFramework\Visitor\Visitor;
51
52 // Import SPL stuff
53 use \stdClass;
54 use \InvalidArgumentException;
55 use \Iterator;
56 use \ReflectionClass;
57 use \SplFileInfo;
58
59 /**
60  * The simulator system class is the super class of all other classes. This
61  * class handles saving of games etc.
62  *
63  * @author              Roland Haeder <webmaster@shipsimu.org>
64  * @version             0.0.0
65  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2020 Core Developer Team
66  * @license             GNU GPL 3.0 or any newer version
67  * @link                http://www.shipsimu.org
68  *
69  * This program is free software: you can redistribute it and/or modify
70  * it under the terms of the GNU General Public License as published by
71  * the Free Software Foundation, either version 3 of the License, or
72  * (at your option) any later version.
73  *
74  * This program is distributed in the hope that it will be useful,
75  * but WITHOUT ANY WARRANTY; without even the implied warranty of
76  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
77  * GNU General Public License for more details.
78  *
79  * You should have received a copy of the GNU General Public License
80  * along with this program. If not, see <http://www.gnu.org/licenses/>.
81  */
82 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
83         /**
84          * Length of output from hash()
85          */
86         private static $hashLength = NULL;
87
88         /**
89          * Self-referencing instance
90          */
91         private static $instance = NULL;
92
93         /**
94          * The real class name
95          */
96         private $realClass = 'BaseFrameworkSystem';
97
98         /**
99          * Search criteria instance
100          */
101         private $searchInstance = NULL;
102
103         /**
104          * Update criteria instance
105          */
106         private $updateInstance = NULL;
107
108         /**
109          * Template engine instance
110          */
111         private $templateInstance = NULL;
112
113         /**
114          * Database result instance
115          */
116         private $resultInstance = NULL;
117
118         /**
119          * Instance for user class
120          */
121         private $userInstance = NULL;
122
123         /**
124          * A controller instance
125          */
126         private $controllerInstance = NULL;
127
128         /**
129          * Instance of a RNG
130          */
131         private $rngInstance = NULL;
132
133         /**
134          * Instance of a crypto helper
135          */
136         private $cryptoInstance = NULL;
137
138         /**
139          * Instance of an Iterator class
140          */
141         private $iteratorInstance = NULL;
142
143         /**
144          * Instance of the list
145          */
146         private $listInstance = NULL;
147
148         /**
149          * Instance of a menu
150          */
151         private $menuInstance = NULL;
152
153         /**
154          * Instance of the image
155          */
156         private $imageInstance = NULL;
157
158         /**
159          * Instance of the stacker
160          */
161         private $stackInstance = NULL;
162
163         /**
164          * A Compressor instance
165          */
166         private $compressorInstance = NULL;
167
168         /**
169          * A Parseable instance
170          */
171         private $parserInstance = NULL;
172
173         /**
174          * A database wrapper instance
175          */
176         private $databaseInstance = NULL;
177
178         /**
179          * A helper instance for the form
180          */
181         private $helperInstance = NULL;
182
183         /**
184          * An instance of a InputStream class
185          */
186         private $inputStreamInstance = NULL;
187
188         /**
189          * An instance of a OutputStream class
190          */
191         private $outputStreamInstance = NULL;
192
193         /**
194          * Handler instance
195          */
196         private $handlerInstance = NULL;
197
198         /**
199          * Visitor handler instance
200          */
201         private $visitorInstance = NULL;
202
203         /**
204          * An instance of a database wrapper class
205          */
206         private $wrapperInstance = NULL;
207
208         /**
209          * An instance of a file I/O pointer class (not handler)
210          */
211         private $pointerInstance = NULL;
212
213         /**
214          * An instance of an Indexable class
215          */
216         private $indexInstance = NULL;
217
218         /**
219          * An instance of a Block class
220          */
221         private $blockInstance = NULL;
222
223         /**
224          * A FrameworkDirectory instance
225          */
226         private $directoryInstance = NULL;
227
228         /**
229          * The concrete output instance
230          */
231         private $outputInstance = NULL;
232
233         /**
234          * State instance
235          */
236         private $stateInstance = NULL;
237
238         /**
239          * Registry instance (implementing Register)
240          */
241         private $registryInstance = NULL;
242
243         /**
244          * Call-back instance
245          */
246         private $callbackInstance = NULL;
247
248         /**
249          * Thousands separator
250          */
251         private $thousands = '.'; // German
252
253         /**
254          * Decimal separator
255          */
256         private $decimals  = ','; // German
257
258         /**
259          * Generic array
260          */
261         private $genericArray = array();
262
263         /**
264          * Command name
265          */
266         private $commandName = '';
267
268         /**
269          * Controller name
270          */
271         private $controllerName = '';
272
273         /**
274          * Array with bitmasks and such for pack/unpack methods to support both
275          * 32-bit and 64-bit systems
276          */
277         private $packingData = array(
278                 32 => array(
279                         'step'   => 3,
280                         'left'   => 0xffff0000,
281                         'right'  => 0x0000ffff,
282                         'factor' => 16,
283                         'format' => 'II',
284                 ),
285                 64 => array(
286                         'step'   => 7,
287                         'left'   => 0xffffffff00000000,
288                         'right'  => 0x00000000ffffffff,
289                         'factor' => 32,
290                         'format' => 'NN'
291                 )
292         );
293
294         /**
295          * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
296          *
297          * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
298          */
299         private $archArrayElement = false;
300
301         /***********************
302          * Exception codes.... *
303          ***********************/
304
305         // @todo Try to clean these constants up
306         const EXCEPTION_IS_NULL_POINTER              = 0x001;
307         const EXCEPTION_IS_NO_OBJECT                 = 0x002;
308         const EXCEPTION_IS_NO_ARRAY                  = 0x003;
309         const EXCEPTION_MISSING_METHOD               = 0x004;
310         const EXCEPTION_CLASSES_NOT_MATCHING         = 0x005;
311         const EXCEPTION_INDEX_OUT_OF_BOUNDS          = 0x006;
312         const EXCEPTION_DIMENSION_ARRAY_INVALID      = 0x007;
313         const EXCEPTION_ITEM_NOT_TRADEABLE           = 0x008;
314         const EXCEPTION_ITEM_NOT_IN_PRICE_LIST       = 0x009;
315         const EXCEPTION_GENDER_IS_WRONG              = 0x00a;
316         const EXCEPTION_BIRTH_DATE_IS_INVALID        = 0x00b;
317         const EXCEPTION_EMPTY_STRUCTURES_ARRAY       = 0x00c;
318         const EXCEPTION_HAS_ALREADY_PERSONELL_LIST   = 0x00d;
319         const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES      = 0x00e;
320         const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED   = 0x00f;
321         const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS      = 0x010;
322         const EXCEPTION_CONTRACT_PARTNER_INVALID     = 0x011;
323         const EXCEPTION_CONTRACT_PARTNER_MISMATCH    = 0x012;
324         const EXCEPTION_CONTRACT_ALREADY_SIGNED      = 0x013;
325         const EXCEPTION_UNEXPECTED_EMPTY_STRING      = 0x014;
326         const EXCEPTION_PATH_NOT_FOUND               = 0x015;
327         const EXCEPTION_INVALID_PATH_NAME            = 0x016;
328         const EXCEPTION_READ_PROTECED_PATH           = 0x017;
329         const EXCEPTION_WRITE_PROTECED_PATH          = 0x018;
330         const EXCEPTION_DIR_POINTER_INVALID          = 0x019;
331         const EXCEPTION_FILE_POINTER_INVALID         = 0x01a;
332         const EXCEPTION_INVALID_RESOURCE             = 0x01b;
333         const EXCEPTION_UNEXPECTED_OBJECT            = 0x01c;
334         const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
335         const EXCEPTION_GETTER_IS_MISSING            = 0x01e;
336         const EXCEPTION_ARRAY_EXPECTED               = 0x01f;
337         const EXCEPTION_ARRAY_HAS_INVALID_COUNT      = 0x020;
338         const EXCEPTION_ID_IS_INVALID_FORMAT         = 0x021;
339         const EXCEPTION_MD5_CHECKSUMS_MISMATCH       = 0x022;
340         const EXCEPTION_UNEXPECTED_STRING_SIZE       = 0x023;
341         const EXCEPTION_SIMULATOR_ID_INVALID         = 0x024;
342         const EXCEPTION_MISMATCHING_COMPRESSORS      = 0x025;
343         const EXCEPTION_CONTAINER_ITEM_IS_NULL       = 0x026;
344         const EXCEPTION_ITEM_IS_NO_ARRAY             = 0x027;
345         const EXCEPTION_CONTAINER_MAYBE_DAMAGED      = 0x028;
346         const EXCEPTION_INVALID_STRING               = 0x029;
347         const EXCEPTION_VARIABLE_NOT_SET             = 0x02a;
348         const EXCEPTION_ATTRIBUTES_ARE_MISSING       = 0x02b;
349         const EXCEPTION_ARRAY_ELEMENTS_MISSING       = 0x02c;
350         const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED  = 0x02d;
351         const EXCEPTION_UNSPPORTED_OPERATION         = 0x02e;
352         const EXCEPTION_FACTORY_REQUIRE_PARAMETER    = 0x02f;
353         const EXCEPTION_MISSING_ELEMENT              = 0x030;
354         const EXCEPTION_HEADERS_ALREADY_SENT         = 0x031;
355         const EXCEPTION_DEFAULT_CONTROLLER_GONE      = 0x032;
356         const EXCEPTION_CLASS_NOT_FOUND              = 0x033;
357         const EXCEPTION_REQUIRED_INTERFACE_MISSING   = 0x034;
358         const EXCEPTION_FATAL_ERROR                  = 0x035;
359         const EXCEPTION_FILE_NOT_FOUND               = 0x036;
360         const EXCEPTION_ASSERTION_FAILED             = 0x037;
361         const EXCEPTION_FILE_NOT_REACHABLE           = 0x038;
362         const EXCEPTION_FILE_CANNOT_BE_READ          = 0x039;
363         const EXCEPTION_FILE_CANNOT_BE_WRITTEN       = 0x03a;
364         const EXCEPTION_PATH_CANNOT_BE_WRITTEN       = 0x03b;
365         const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
366         const EXCEPTION_FILTER_CHAIN_INTERCEPTED     = 0x03d;
367         const EXCEPTION_INVALID_SOCKET               = 0x03e;
368         const EXCEPTION_SELF_INSTANCE                = 0x03f;
369
370         /**
371          * Hexadecimal->Decimal translation array
372          */
373         private static $hexdec = array(
374                 '0' => 0,
375                 '1' => 1,
376                 '2' => 2,
377                 '3' => 3,
378                 '4' => 4,
379                 '5' => 5,
380                 '6' => 6,
381                 '7' => 7,
382                 '8' => 8,
383                 '9' => 9,
384                 'a' => 10,
385                 'b' => 11,
386                 'c' => 12,
387                 'd' => 13,
388                 'e' => 14,
389                 'f' => 15
390         );
391
392         /**
393          * Decimal->hexadecimal translation array
394          */
395         private static $dechex = array(
396                  0 => '0',
397                  1 => '1',
398                  2 => '2',
399                  3 => '3',
400                  4 => '4',
401                  5 => '5',
402                  6 => '6',
403                  7 => '7',
404                  8 => '8',
405                  9 => '9',
406                 10 => 'a',
407                 11 => 'b',
408                 12 => 'c',
409                 13 => 'd',
410                 14 => 'e',
411                 15 => 'f'
412         );
413
414         /**
415          * Startup time in miliseconds
416          */
417         private static $startupTime = 0;
418
419         /**
420          * Protected super constructor
421          *
422          * @param       $className      Name of the class
423          * @return      void
424          */
425         protected function __construct ($className) {
426                 // Set real class
427                 $this->setRealClass($className);
428
429                 // Set configuration instance if no registry ...
430                 if (!$this instanceof Register) {
431                         // ... because registries doesn't need to be configured
432                         $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
433                 } // END - if
434
435                 // Is the startup time set? (0 cannot be true anymore)
436                 if (self::$startupTime == 0) {
437                         // Then set it
438                         self::$startupTime = microtime(true);
439                 } // END - if
440
441                 // Set array element
442                 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
443         }
444
445         /**
446          * Destructor for all classes. You should not call this method on your own.
447          *
448          * @return      void
449          */
450         public function __destruct () {
451                 // Flush any updated entries to the database
452                 $this->flushPendingUpdates();
453
454                 // Is this object already destroyed?
455                 if ($this->__toString() != 'DestructedObject') {
456                         // Destroy all informations about this class but keep some text about it alive
457                         $this->setRealClass('DestructedObject');
458                 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
459                         // Already destructed object
460                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
461                                 $this->__toString()
462                         ));
463                 } else {
464                         // Do not call this twice
465                         trigger_error(__METHOD__ . ': Called twice.');
466                         exit;
467                 }
468         }
469
470         /**
471          * The __call() method where all non-implemented methods end up
472          *
473          * @param       $methodName             Name of the missing method
474          * @args        $args                   Arguments passed to the method
475          * @return      void
476          */
477         public final function __call ($methodName, $args) {
478                 // Set self-instance
479                 self::$instance = $this;
480
481                 // Call static method
482                 self::__callStatic($methodName, $args);
483
484                 // Clear self-instance
485                 self::$instance = NULL;
486         }
487
488         /**
489          * The __callStatic() method where all non-implemented static methods end up
490          *
491          * @param       $methodName             Name of the missing method
492          * @param       $args                   Arguments passed to the method
493          * @return      void
494          * @throws      InvalidArgumentException If self::$instance is not a framework's own object
495          */
496         public static final function __callStatic ($methodName, $args) {
497                 // Trace message
498                 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
499
500                 // Init argument string and class name
501                 $argsString = '';
502                 $className = 'unknown';
503
504                 // Is self-instance set?
505                 if (self::$instance instanceof FrameworkInterface) {
506                         // Framework's own instance
507                         $className = self::$instance->__toString();
508                 } elseif (!is_null(self::$instance)) {
509                         // Invalid argument!
510                         throw new InvalidArgumentException(sprintf('self::instance[%s] is not expected.', gettype(self::$instance)), self::EXCEPTION_SELF_INSTANCE);
511                 }
512
513                 // Is it NULL, empty or an array?
514                 if (is_null($args)) {
515                         // No arguments
516                         $argsString = 'NULL';
517                 } elseif (is_array($args)) {
518                         // Start braces
519                         $argsString = '(';
520
521                         // Some arguments are there
522                         foreach ($args as $arg) {
523                                 // Add data about the argument
524                                 $argsString .= gettype($arg) . ':';
525
526                                 if (is_null($arg)) {
527                                         // Found a NULL argument
528                                         $argsString .= 'NULL';
529                                 } elseif (is_string($arg)) {
530                                         // Add length for strings
531                                         $argsString .= strlen($arg);
532                                 } elseif ((is_int($arg)) || (is_float($arg))) {
533                                         // ... integer/float
534                                         $argsString .= $arg;
535                                 } elseif (is_array($arg)) {
536                                         // .. or size if array
537                                         $argsString .= count($arg);
538                                 } elseif (is_object($arg)) {
539                                         // Get reflection
540                                         $reflection = new ReflectionClass($arg);
541
542                                         // Is an other object, maybe no __toString() available
543                                         $argsString .= $reflection->getName();
544                                 } elseif ($arg === true) {
545                                         // ... is boolean 'true'
546                                         $argsString .= 'true';
547                                 } elseif ($arg === false) {
548                                         // ... is boolean 'false'
549                                         $argsString .= 'false';
550                                 }
551
552                                 // Comma for next one
553                                 $argsString .= ', ';
554                         } // END - foreach
555
556                         // Last comma found?
557                         if (substr($argsString, -2, 1) == ',') {
558                                 // Remove last comma
559                                 $argsString = substr($argsString, 0, -2);
560                         } // END - if
561
562                         // Close braces
563                         $argsString .= ')';
564                 } else {
565                         // Invalid arguments!
566                         $argsString = sprintf('!INVALID:%s!', gettype($args));
567                 }
568
569                 // Output stub message
570                 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
571                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s::%s]: Stub! Args: %s',
572                         $className,
573                         $methodName,
574                         $argsString
575                 ));
576
577                 // Return nothing
578                 return NULL;
579         }
580
581         /**
582          * Getter for $realClass
583          *
584          * @return      $realClass The name of the real class (not BaseFrameworkSystem)
585          */
586         public function __toString () {
587                 return $this->realClass;
588         }
589
590         /**
591          * Magic method to catch setting of missing but set class fields/attributes
592          *
593          * @param       $name   Name of the field/attribute
594          * @param       $value  Value to store
595          * @return      void
596          */
597         public final function __set ($name, $value) {
598                 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
599                         $name,
600                         gettype($value),
601                         print_r($value, true)
602                 ));
603         }
604
605         /**
606          * Magic method to catch getting of missing fields/attributes
607          *
608          * @param       $name   Name of the field/attribute
609          * @return      void
610          */
611         public final function __get ($name) {
612                 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
613                         $name
614                 ));
615         }
616
617         /**
618          * Magic method to catch unsetting of missing fields/attributes
619          *
620          * @param       $name   Name of the field/attribute
621          * @return      void
622          */
623         public final function __unset ($name) {
624                 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
625                         $name
626                 ));
627         }
628
629         /**
630          * Magic method to catch object serialization
631          *
632          * @return      $unsupported    Unsupported method
633          * @throws      UnsupportedOperationException   Objects of this framework cannot be serialized
634          */
635         public final function __sleep () {
636                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
637         }
638
639         /**
640          * Magic method to catch object deserialization
641          *
642          * @return      $unsupported    Unsupported method
643          * @throws      UnsupportedOperationException   Objects of this framework cannot be serialized
644          */
645         public final function __wakeup () {
646                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
647         }
648
649         /**
650          * Magic method to catch calls when an object instance is called
651          *
652          * @return      $unsupported    Unsupported method
653          * @throws      UnsupportedOperationException   Objects of this framework cannot be serialized
654          */
655         public final function __invoke () {
656                 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
657         }
658
659         /**
660          * Setter for the real class name
661          *
662          * @param       $realClass      Class name (string)
663          * @return      void
664          */
665         public final function setRealClass ($realClass) {
666                 // Set real class
667                 $this->realClass = (string) $realClass;
668         }
669
670         /**
671          * Setter for database result instance
672          *
673          * @param       $resultInstance         An instance of a database result class
674          * @return      void
675          * @todo        SearchableResult and UpdateableResult shall have a super interface to use here
676          */
677         protected final function setResultInstance (SearchableResult $resultInstance) {
678                 $this->resultInstance =  $resultInstance;
679         }
680
681         /**
682          * Getter for database result instance
683          *
684          * @return      $resultInstance         An instance of a database result class
685          */
686         public final function getResultInstance () {
687                 return $this->resultInstance;
688         }
689
690         /**
691          * Setter for template engine instances
692          *
693          * @param       $templateInstance       An instance of a template engine class
694          * @return      void
695          */
696         protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
697                 $this->templateInstance = $templateInstance;
698         }
699
700         /**
701          * Getter for template engine instances
702          *
703          * @return      $templateInstance       An instance of a template engine class
704          */
705         protected final function getTemplateInstance () {
706                 return $this->templateInstance;
707         }
708
709         /**
710          * Setter for search instance
711          *
712          * @param       $searchInstance         Searchable criteria instance
713          * @return      void
714          */
715         public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
716                 $this->searchInstance = $searchInstance;
717         }
718
719         /**
720          * Getter for search instance
721          *
722          * @return      $searchInstance         Searchable criteria instance
723          */
724         public final function getSearchInstance () {
725                 return $this->searchInstance;
726         }
727
728         /**
729          * Setter for update instance
730          *
731          * @param       $updateInstance         An instance of a LocalUpdateCriteria clase
732          * @return      void
733          */
734         public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
735                 $this->updateInstance = $updateInstance;
736         }
737
738         /**
739          * Getter for update instance
740          *
741          * @return      $updateInstance         Updateable criteria instance
742          */
743         public final function getUpdateInstance () {
744                 return $this->updateInstance;
745         }
746
747         /**
748          * Setter for language instance
749          *
750          * @param       $configInstance         The configuration instance which shall
751          *                                                              be FrameworkConfiguration
752          * @return      void
753          */
754         public final function setConfigInstance (FrameworkConfiguration $configInstance) {
755                 GenericRegistry::getRegistry()->addInstance('config', $configInstance);
756         }
757
758         /**
759          * Getter for configuration instance
760          *
761          * @return      $configInstance         Configuration instance
762          */
763         public final function getConfigInstance () {
764                 $configInstance = GenericRegistry::getRegistry()->getInstance('config');
765                 return $configInstance;
766         }
767
768         /**
769          * Setter for debug instance
770          *
771          * @param       $debugInstance  The instance for debug output class
772          * @return      void
773          */
774         public final function setDebugInstance (DebugMiddleware $debugInstance) {
775                 GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
776         }
777
778         /**
779          * Getter for debug instance
780          *
781          * @return      $debugInstance  Instance to class DebugConsoleOutput or DebugWebOutput
782          */
783         public final function getDebugInstance () {
784                 // Get debug instance
785                 $debugInstance = GenericRegistry::getRegistry()->getInstance('debug');
786
787                 // Return it
788                 return $debugInstance;
789         }
790
791         /**
792          * Setter for web output instance
793          *
794          * @param       $webInstance    The instance for web output class
795          * @return      void
796          */
797         public final function setWebOutputInstance (OutputStreamer $webInstance) {
798                 GenericRegistry::getRegistry()->addInstance('web_output', $webInstance);
799         }
800
801         /**
802          * Getter for web output instance
803          *
804          * @return      $webOutputInstance - Instance to class WebOutput
805          */
806         public final function getWebOutputInstance () {
807                 $webOutputInstance = GenericRegistry::getRegistry()->getInstance('web_output');
808                 return $webOutputInstance;
809         }
810
811         /**
812          * Setter for database instance
813          *
814          * @param       $databaseInstance       The instance for the database connection (forced DatabaseConnection)
815          * @return      void
816          */
817         public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
818                 GenericRegistry::getRegistry()->addInstance('db_instance', $databaseInstance);
819         }
820
821         /**
822          * Getter for database layer
823          *
824          * @return      $databaseInstance       The database layer instance
825          */
826         public final function getDatabaseInstance () {
827                 // Get instance
828                 $databaseInstance = GenericRegistry::getRegistry()->getInstance('db_instance');
829
830                 // Return instance
831                 return $databaseInstance;
832         }
833
834         /**
835          * Setter for compressor channel
836          *
837          * @param       $compressorInstance             An instance of CompressorChannel
838          * @return      void
839          */
840         public final function setCompressorChannel (CompressorChannel $compressorInstance) {
841                 GenericRegistry::getRegistry()->addInstance('compressor', $compressorInstance);
842         }
843
844         /**
845          * Getter for compressor channel
846          *
847          * @return      $compressorInstance             The compressor channel
848          */
849         public final function getCompressorChannel () {
850                 $compressorInstance = GenericRegistry::getRegistry()->getInstance('compressor');
851                 return $compressorInstance;
852         }
853
854         /**
855          * Private getter for language instance
856          *
857          * @return      $langInstance   An instance to the language sub-system
858          */
859         protected final function getLanguageInstance () {
860                 $langInstance = GenericRegistry::getRegistry()->getInstance('language');
861                 return $langInstance;
862         }
863
864         /**
865          * Setter for language instance
866          *
867          * @param       $langInstance   An instance to the language sub-system
868          * @return      void
869          * @see         LanguageSystem
870          */
871         public final function setLanguageInstance (ManageableLanguage $langInstance) {
872                 GenericRegistry::getRegistry()->addInstance('language', $langInstance);
873         }
874
875         /**
876          * Protected setter for user instance
877          *
878          * @param       $userInstance   An instance of a user class
879          * @return      void
880          */
881         protected final function setUserInstance (ManageableAccount $userInstance) {
882                 $this->userInstance = $userInstance;
883         }
884
885         /**
886          * Getter for user instance
887          *
888          * @return      $userInstance   An instance of a user class
889          */
890         public final function getUserInstance () {
891                 return $this->userInstance;
892         }
893
894         /**
895          * Setter for controller instance (this surely breaks a bit the MVC patterm)
896          *
897          * @param       $controllerInstance             An instance of the controller
898          * @return      void
899          */
900         public final function setControllerInstance (Controller $controllerInstance) {
901                 $this->controllerInstance = $controllerInstance;
902         }
903
904         /**
905          * Getter for controller instance (this surely breaks a bit the MVC patterm)
906          *
907          * @return      $controllerInstance             An instance of the controller
908          */
909         public final function getControllerInstance () {
910                 return $this->controllerInstance;
911         }
912
913         /**
914          * Setter for RNG instance
915          *
916          * @param       $rngInstance    An instance of a random number generator (RNG)
917          * @return      void
918          */
919         protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
920                 $this->rngInstance = $rngInstance;
921         }
922
923         /**
924          * Getter for RNG instance
925          *
926          * @return      $rngInstance    An instance of a random number generator (RNG)
927          */
928         public final function getRngInstance () {
929                 return $this->rngInstance;
930         }
931
932         /**
933          * Setter for Cryptable instance
934          *
935          * @param       $cryptoInstance An instance of a Cryptable class
936          * @return      void
937          */
938         protected final function setCryptoInstance (Cryptable $cryptoInstance) {
939                 $this->cryptoInstance = $cryptoInstance;
940         }
941
942         /**
943          * Getter for Cryptable instance
944          *
945          * @return      $cryptoInstance An instance of a Cryptable class
946          */
947         public final function getCryptoInstance () {
948                 return $this->cryptoInstance;
949         }
950
951         /**
952          * Setter for the list instance
953          *
954          * @param       $listInstance   A list of Listable
955          * @return      void
956          */
957         protected final function setListInstance (Listable $listInstance) {
958                 $this->listInstance = $listInstance;
959         }
960
961         /**
962          * Getter for the list instance
963          *
964          * @return      $listInstance   A list of Listable
965          */
966         protected final function getListInstance () {
967                 return $this->listInstance;
968         }
969
970         /**
971          * Setter for the menu instance
972          *
973          * @param       $menuInstance   A RenderableMenu instance
974          * @return      void
975          */
976         protected final function setMenuInstance (RenderableMenu $menuInstance) {
977                 $this->menuInstance = $menuInstance;
978         }
979
980         /**
981          * Getter for the menu instance
982          *
983          * @return      $menuInstance   A RenderableMenu instance
984          */
985         protected final function getMenuInstance () {
986                 return $this->menuInstance;
987         }
988
989         /**
990          * Setter for image instance
991          *
992          * @param       $imageInstance  An instance of an image
993          * @return      void
994          */
995         public final function setImageInstance (BaseImage $imageInstance) {
996                 $this->imageInstance = $imageInstance;
997         }
998
999         /**
1000          * Getter for image instance
1001          *
1002          * @return      $imageInstance  An instance of an image
1003          */
1004         public final function getImageInstance () {
1005                 return $this->imageInstance;
1006         }
1007
1008         /**
1009          * Setter for stacker instance
1010          *
1011          * @param       $stackInstance  An instance of an stacker
1012          * @return      void
1013          */
1014         public final function setStackInstance (Stackable $stackInstance) {
1015                 $this->stackInstance = $stackInstance;
1016         }
1017
1018         /**
1019          * Getter for stacker instance
1020          *
1021          * @return      $stackInstance  An instance of an stacker
1022          */
1023         public final function getStackInstance () {
1024                 return $this->stackInstance;
1025         }
1026
1027         /**
1028          * Setter for compressor instance
1029          *
1030          * @param       $compressorInstance     An instance of an compressor
1031          * @return      void
1032          */
1033         public final function setCompressorInstance (Compressor $compressorInstance) {
1034                 $this->compressorInstance = $compressorInstance;
1035         }
1036
1037         /**
1038          * Getter for compressor instance
1039          *
1040          * @return      $compressorInstance     An instance of an compressor
1041          */
1042         public final function getCompressorInstance () {
1043                 return $this->compressorInstance;
1044         }
1045
1046         /**
1047          * Setter for Parseable instance
1048          *
1049          * @param       $parserInstance An instance of an Parseable
1050          * @return      void
1051          */
1052         public final function setParserInstance (Parseable $parserInstance) {
1053                 $this->parserInstance = $parserInstance;
1054         }
1055
1056         /**
1057          * Getter for Parseable instance
1058          *
1059          * @return      $parserInstance An instance of an Parseable
1060          */
1061         public final function getParserInstance () {
1062                 return $this->parserInstance;
1063         }
1064
1065         /**
1066          * Setter for DatabaseWrapper instance
1067          *
1068          * @param       $wrapperInstance        An instance of an DatabaseWrapper
1069          * @return      void
1070          */
1071         public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1072                 $this->wrapperInstance = $wrapperInstance;
1073         }
1074
1075         /**
1076          * Getter for DatabaseWrapper instance
1077          *
1078          * @return      $wrapperInstance        An instance of an DatabaseWrapper
1079          */
1080         public final function getWrapperInstance () {
1081                 return $this->wrapperInstance;
1082         }
1083
1084         /**
1085          * Setter for helper instance
1086          *
1087          * @param       $helperInstance         An instance of a helper class
1088          * @return      void
1089          */
1090         protected final function setHelperInstance (Helper $helperInstance) {
1091                 $this->helperInstance = $helperInstance;
1092         }
1093
1094         /**
1095          * Getter for helper instance
1096          *
1097          * @return      $helperInstance         An instance of a helper class
1098          */
1099         public final function getHelperInstance () {
1100                 return $this->helperInstance;
1101         }
1102
1103         /**
1104          * Getter for a InputStream instance
1105          *
1106          * @param       $inputStreamInstance    The InputStream instance
1107          */
1108         protected final function getInputStreamInstance () {
1109                 return $this->inputStreamInstance;
1110         }
1111
1112         /**
1113          * Setter for a InputStream instance
1114          *
1115          * @param       $inputStreamInstance    The InputStream instance
1116          * @return      void
1117          */
1118         protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1119                 $this->inputStreamInstance = $inputStreamInstance;
1120         }
1121
1122         /**
1123          * Getter for a OutputStream instance
1124          *
1125          * @param       $outputStreamInstance   The OutputStream instance
1126          */
1127         protected final function getOutputStreamInstance () {
1128                 return $this->outputStreamInstance;
1129         }
1130
1131         /**
1132          * Setter for a OutputStream instance
1133          *
1134          * @param       $outputStreamInstance   The OutputStream instance
1135          * @return      void
1136          */
1137         protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1138                 $this->outputStreamInstance = $outputStreamInstance;
1139         }
1140
1141         /**
1142          * Setter for handler instance
1143          *
1144          * @param       $handlerInstance        An instance of a Handleable class
1145          * @return      void
1146          */
1147         protected final function setHandlerInstance (Handleable $handlerInstance) {
1148                 $this->handlerInstance = $handlerInstance;
1149         }
1150
1151         /**
1152          * Getter for handler instance
1153          *
1154          * @return      $handlerInstance        A Handleable instance
1155          */
1156         protected final function getHandlerInstance () {
1157                 return $this->handlerInstance;
1158         }
1159
1160         /**
1161          * Setter for visitor instance
1162          *
1163          * @param       $visitorInstance        A Visitor instance
1164          * @return      void
1165          */
1166         protected final function setVisitorInstance (Visitor $visitorInstance) {
1167                 $this->visitorInstance = $visitorInstance;
1168         }
1169
1170         /**
1171          * Getter for visitor instance
1172          *
1173          * @return      $visitorInstance        A Visitor instance
1174          */
1175         protected final function getVisitorInstance () {
1176                 return $this->visitorInstance;
1177         }
1178
1179         /**
1180          * Setter for Iterator instance
1181          *
1182          * @param       $iteratorInstance       An instance of an Iterator
1183          * @return      void
1184          */
1185         protected final function setIteratorInstance (Iterator $iteratorInstance) {
1186                 $this->iteratorInstance = $iteratorInstance;
1187         }
1188
1189         /**
1190          * Getter for Iterator instance
1191          *
1192          * @return      $iteratorInstance       An instance of an Iterator
1193          */
1194         public final function getIteratorInstance () {
1195                 return $this->iteratorInstance;
1196         }
1197
1198         /**
1199          * Setter for FilePointer instance
1200          *
1201          * @param       $pointerInstance        An instance of an FilePointer class
1202          * @return      void
1203          */
1204         protected final function setPointerInstance (FilePointer $pointerInstance) {
1205                 $this->pointerInstance = $pointerInstance;
1206         }
1207
1208         /**
1209          * Getter for FilePointer instance
1210          *
1211          * @return      $pointerInstance        An instance of an FilePointer class
1212          */
1213         public final function getPointerInstance () {
1214                 return $this->pointerInstance;
1215         }
1216
1217         /**
1218          * Unsets pointer instance which triggers a call of __destruct() if the
1219          * instance is still there. This is surely not fatal on already "closed"
1220          * file pointer instances.
1221          *
1222          * I don't want to mess around with above setter by giving it a default
1223          * value NULL as setter should always explicitly only set (existing) object
1224          * instances and NULL is NULL.
1225          *
1226          * @return      void
1227          */
1228         protected final function unsetPointerInstance () {
1229                 // Simply it to NULL
1230                 $this->pointerInstance = NULL;
1231         }
1232
1233         /**
1234          * Setter for Indexable instance
1235          *
1236          * @param       $indexInstance  An instance of an Indexable class
1237          * @return      void
1238          */
1239         protected final function setIndexInstance (Indexable $indexInstance) {
1240                 $this->indexInstance = $indexInstance;
1241         }
1242
1243         /**
1244          * Getter for Indexable instance
1245          *
1246          * @return      $indexInstance  An instance of an Indexable class
1247          */
1248         public final function getIndexInstance () {
1249                 return $this->indexInstance;
1250         }
1251
1252         /**
1253          * Setter for Block instance
1254          *
1255          * @param       $blockInstance  An instance of an Block class
1256          * @return      void
1257          */
1258         protected final function setBlockInstance (Block $blockInstance) {
1259                 $this->blockInstance = $blockInstance;
1260         }
1261
1262         /**
1263          * Getter for Block instance
1264          *
1265          * @return      $blockInstance  An instance of an Block class
1266          */
1267         public final function getBlockInstance () {
1268                 return $this->blockInstance;
1269         }
1270
1271         /**
1272          * Setter for FrameworkDirectory instance
1273          *
1274          * @param       $directoryInstance      A FrameworkDirectory instance
1275          * @return      void
1276          */
1277         protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1278                 $this->directoryInstance = $directoryInstance;
1279         }
1280
1281         /**
1282          * Getter for FrameworkDirectory instance
1283          *
1284          * @return      $directoryInstance      A FrameworkDirectory instance
1285          */
1286         protected final function getDirectoryInstance () {
1287                 return $this->directoryInstance;
1288         }
1289
1290         /**
1291          * Setter for state instance
1292          *
1293          * @param       $stateInstance  A Stateable instance
1294          * @return      void
1295          */
1296         public final function setStateInstance (Stateable $stateInstance) {
1297                 $this->stateInstance = $stateInstance;
1298         }
1299
1300         /**
1301          * Getter for state instance
1302          *
1303          * @return      $stateInstance  A Stateable instance
1304          */
1305         public final function getStateInstance () {
1306                 return $this->stateInstance;
1307         }
1308
1309         /**
1310          * Setter for output instance
1311          *
1312          * @param       $outputInstance The debug output instance
1313          * @return      void
1314          */
1315         public final function setOutputInstance (OutputStreamer $outputInstance) {
1316                 $this->outputInstance = $outputInstance;
1317         }
1318
1319         /**
1320          * Getter for output instance
1321          *
1322          * @return      $outputInstance The debug output instance
1323          */
1324         public final function getOutputInstance () {
1325                 return $this->outputInstance;
1326         }
1327
1328         /**
1329          * Setter for registry instance
1330          *
1331          * @param       $registryInstance               An instance of a Register class
1332          * @return      void
1333          */
1334         protected final function setRegistryInstance (Register $registryInstance) {
1335                 $this->registryInstance = $registryInstance;
1336         }
1337
1338         /**
1339          * Getter for registry instance
1340          *
1341          * @return      $registryInstance       The debug registry instance
1342          */
1343         public final function getRegistryInstance () {
1344                 return $this->registryInstance;
1345         }
1346
1347         /**
1348          * Setter for call-back instance
1349          *
1350          * @param       $callbackInstance       An instance of a FrameworkInterface class
1351          * @return      void
1352          */
1353         public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1354                 $this->callbackInstance = $callbackInstance;
1355         }
1356
1357         /**
1358          * Getter for call-back instance
1359          *
1360          * @return      $callbackInstance       An instance of a FrameworkInterface class
1361          */
1362         protected final function getCallbackInstance () {
1363                 return $this->callbackInstance;
1364         }
1365
1366         /**
1367          * Setter for command name
1368          *
1369          * @param       $commandName    Last validated command name
1370          * @return      void
1371          */
1372         protected final function setCommandName ($commandName) {
1373                 $this->commandName = $commandName;
1374         }
1375
1376         /**
1377          * Getter for command name
1378          *
1379          * @return      $commandName    Last validated command name
1380          */
1381         protected final function getCommandName () {
1382                 return $this->commandName;
1383         }
1384
1385         /**
1386          * Setter for controller name
1387          *
1388          * @param       $controllerName Last validated controller name
1389          * @return      void
1390          */
1391         protected final function setControllerName ($controllerName) {
1392                 $this->controllerName = $controllerName;
1393         }
1394
1395         /**
1396          * Getter for controller name
1397          *
1398          * @return      $controllerName Last validated controller name
1399          */
1400         protected final function getControllerName () {
1401                 return $this->controllerName;
1402         }
1403
1404         /**
1405          * Checks whether an object equals this object. You should overwrite this
1406          * method to implement own equality checks
1407          *
1408          * @param       $objectInstance         An instance of a FrameworkInterface object
1409          * @return      $equals                         Whether both objects equals
1410          */
1411         public function equals (FrameworkInterface $objectInstance) {
1412                 // Now test it
1413                 $equals = ((
1414                         $this->__toString() == $objectInstance->__toString()
1415                 ) && (
1416                         $this->hashCode() == $objectInstance->hashCode()
1417                 ));
1418
1419                 // Return the result
1420                 return $equals;
1421         }
1422
1423         /**
1424          * Generates a generic hash code of this class. You should really overwrite
1425          * this method with your own hash code generator code. But keep KISS in mind.
1426          *
1427          * @return      $hashCode       A generic hash code respresenting this whole class
1428          */
1429         public function hashCode () {
1430                 // Simple hash code
1431                 return crc32($this->__toString());
1432         }
1433
1434         /**
1435          * Formats computer generated price values into human-understandable formats
1436          * with thousand and decimal separators.
1437          *
1438          * @param       $value          The in computer format value for a price
1439          * @param       $currency       The currency symbol (use HTML-valid characters!)
1440          * @param       $decNum         Number of decimals after commata
1441          * @return      $price          The for the current language formated price string
1442          * @throws      MissingDecimalsThousandsSeparatorException      If decimals or
1443          *                                                                                              thousands separator
1444          *                                                                                              is missing
1445          */
1446         public function formatCurrency ($value, $currency = '&euro;', $decNum = 2) {
1447                 // Are all required attriutes set?
1448                 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1449                         // Throw an exception
1450                         throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1451                 } // END - if
1452
1453                 // Cast the number
1454                 $value = (float) $value;
1455
1456                 // Reformat the US number
1457                 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1458
1459                 // Return as string...
1460                 return $price;
1461         }
1462
1463         /**
1464          * Appends a trailing slash to a string
1465          *
1466          * @param       $str    A string (maybe) without trailing slash
1467          * @return      $str    A string with an auto-appended trailing slash
1468          */
1469         public final function addMissingTrailingSlash ($str) {
1470                 // Is there a trailing slash?
1471                 if (substr($str, -1, 1) != '/') {
1472                         $str .= '/';
1473                 } // END - if
1474
1475                 // Return string with trailing slash
1476                 return $str;
1477         }
1478
1479         /**
1480          * Prepare the template engine (HtmlTemplateEngine by default) for a given
1481          * application helper instance (ApplicationHelper by default).
1482          *
1483          * @param               $applicationInstance    An application helper instance or
1484          *                                                                              null if we shall use the default
1485          * @return              $templateInstance               The template engine instance
1486          * @throws              NullPointerException    If the discovered application
1487          *                                                                              instance is still null
1488          */
1489         protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1490                 // Is the application instance set?
1491                 if (is_null($applicationInstance)) {
1492                         // Get the current instance
1493                         $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
1494
1495                         // Still null?
1496                         if (is_null($applicationInstance)) {
1497                                 // Thrown an exception
1498                                 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1499                         } // END - if
1500                 } // END - if
1501
1502                 // Initialize the template engine
1503                 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1504
1505                 // Return the prepared instance
1506                 return $templateInstance;
1507         }
1508
1509         /**
1510          * Debugs this instance by putting out it's full content
1511          *
1512          * @param       $message        Optional message to show in debug output
1513          * @return      void
1514          */
1515         public final function debugInstance ($message = '') {
1516                 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1517                 restore_error_handler();
1518
1519                 // Init content
1520                 $content = '';
1521
1522                 // Is a message set?
1523                 if (!empty($message)) {
1524                         // Construct message
1525                         $content = sprintf('<div class="debug_message">
1526         Message: %s
1527 </div>' . PHP_EOL, $message);
1528                 } // END - if
1529
1530                 // Generate the output
1531                 $content .= sprintf('<pre>%s</pre>',
1532                         trim(
1533                                 htmlentities(
1534                                         print_r($this, true)
1535                                 )
1536                         )
1537                 );
1538
1539                 // Output it
1540                 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1541         %s debug output:
1542 </div>
1543 <div class="debug_content">
1544         %s
1545 </div>
1546 Loaded includes:
1547 <div class="debug_include_list">
1548         %s
1549 </div>',
1550                         $this->__toString(),
1551                         $content,
1552                         ClassLoader::getSelfInstance()->getPrintableIncludeList()
1553                 ));
1554         }
1555
1556         /**
1557          * Replaces control characters with printable output
1558          *
1559          * @param       $str    String with control characters
1560          * @return      $str    Replaced string
1561          */
1562         protected function replaceControlCharacters ($str) {
1563                 // Replace them
1564                 $str = str_replace(
1565                         chr(13), '[r]', str_replace(
1566                         chr(10), '[n]', str_replace(
1567                         chr(9) , '[t]',
1568                         $str
1569                 )));
1570
1571                 // Return it
1572                 return $str;
1573         }
1574
1575         /**
1576          * Output a partial stub message for the caller method
1577          *
1578          * @param       $message        An optional message to display
1579          * @return      void
1580          */
1581         protected function partialStub ($message = '') {
1582                 // Init variable
1583                 $stubMessage = 'Partial stub!';
1584
1585                 // Is an extra message given?
1586                 if (!empty($message)) {
1587                         // Then add it as well
1588                         $stubMessage .= ' Message: ' . $message;
1589                 } // END - if
1590
1591                 // Debug instance is there?
1592                 if (!is_null($this->getDebugInstance())) {
1593                         // Output stub message
1594                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1595                 } else {
1596                         // Trigger an error
1597                         trigger_error($stubMessage);
1598                         exit;
1599                 }
1600         }
1601
1602         /**
1603          * Outputs a debug backtrace and stops further script execution
1604          *
1605          * @param       $message        An optional message to output
1606          * @param       $doExit         Whether exit the program (true is default)
1607          * @return      void
1608          */
1609         public function debugBackTrace ($message = '', $doExit = true) {
1610                 // Sorry, there is no other way getting this nice backtrace
1611                 if (!empty($message)) {
1612                         // Output message
1613                         printf('Message: %s<br />' . PHP_EOL, $message);
1614                 } // END - if
1615
1616                 print('<pre>');
1617                 debug_print_backtrace();
1618                 print('</pre>');
1619
1620                 // Exit program?
1621                 if ($doExit === true) {
1622                         exit();
1623                 } // END - if
1624         }
1625
1626         /**
1627          * Creates an instance of a debugger instance
1628          *
1629          * @param       $className              Name of the class (currently unsupported)
1630          * @param       $lineNumber             Line number where the call was made
1631          * @return      $debugInstance  An instance of a debugger class
1632          * @deprecated  Not fully, as the new Logger facilities are not finished yet.
1633          */
1634         public final static function createDebugInstance ($className, $lineNumber = NULL) {
1635                 // Is the instance set?
1636                 if (!GenericRegistry::getRegistry()->instanceExists('debug')) {
1637                         // Init debug instance
1638                         $debugInstance = NULL;
1639
1640                         // Try it
1641                         try {
1642                                 // Get a debugger instance
1643                                 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1644                         } catch (NullPointerException $e) {
1645                                 // Didn't work, no instance there
1646                                 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1647                         }
1648
1649                         // Empty string should be ignored and used for testing the middleware
1650                         DebugMiddleware::getSelfInstance()->output('');
1651
1652                         // Set it in registry
1653                         GenericRegistry::getRegistry()->addInstance('debug', $debugInstance);
1654                 } else {
1655                         // Get instance from registry
1656                         $debugInstance = GenericRegistry::getRegistry()->getDebugInstance();
1657                 }
1658
1659                 // Return it
1660                 return $debugInstance;
1661         }
1662
1663         /**
1664          * Simple output of a message with line-break
1665          *
1666          * @param       $message        Message to output
1667          * @return      void
1668          */
1669         public function outputLine ($message) {
1670                 // Simply output it
1671                 print($message . PHP_EOL);
1672         }
1673
1674         /**
1675          * Outputs a debug message whether to debug instance (should be set!) or
1676          * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1677          * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1678          *
1679          * @param       $message        Message we shall send out...
1680          * @param       $doPrint        Whether print or die here (default: print)
1681          * @paran       $stripTags      Whether to strip tags (default: false)
1682          * @return      void
1683          */
1684         public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1685                 // Set debug instance to NULL
1686                 $debugInstance = NULL;
1687
1688                 // Get backtrace
1689                 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1690
1691                 // Is function partialStub/__callStatic ?
1692                 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1693                         // Prepend class::function:line from 3rd element
1694                         $message = sprintf('[%s::%s:%d]: %s',
1695                                 $backtrace[2]['class'],
1696                                 $backtrace[2]['function'],
1697                                 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1698                                 $message
1699                         );
1700                 } else {
1701                         // Prepend class::function:line from 2nd element
1702                         $message = sprintf('[%s::%s:%d]: %s',
1703                                 $backtrace[1]['class'],
1704                                 $backtrace[1]['function'],
1705                                 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1706                                 $message
1707                         );
1708                 }
1709
1710                 // Try it:
1711                 try {
1712                         // Get debug instance
1713                         $debugInstance = $this->getDebugInstance();
1714                 } catch (NullPointerException $e) {
1715                         // The debug instance is not set (yet)
1716                 }
1717
1718                 // Is the debug instance there?
1719                 if (is_object($debugInstance)) {
1720                         // Use debug output handler
1721                         $debugInstance->output($message, $stripTags);
1722
1723                         if ($doPrint === false) {
1724                                 // Die here if not printed
1725                                 exit();
1726                         } // END - if
1727                 } else {
1728                         // Are debug times enabled?
1729                         if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1730                                 // Prepent it
1731                                 $message = $this->getPrintableExecutionTime() . $message;
1732                         } // END - if
1733
1734                         // Put directly out
1735                         if ($doPrint === true) {
1736                                 // Print message
1737                                 $this->outputLine($message);
1738                         } else {
1739                                 // Die here
1740                                 exit($message);
1741                         }
1742                 }
1743         }
1744
1745         /**
1746          * Converts e.g. a command from URL to a valid class by keeping out bad characters
1747          *
1748          * @param       $str            The string, what ever it is needs to be converted
1749          * @return      $className      Generated class name
1750          */
1751         public static final function convertToClassName ($str) {
1752                 // Init class name
1753                 $className = '';
1754
1755                 // Convert all dashes in underscores
1756                 $str = StringUtils::convertDashesToUnderscores($str);
1757
1758                 // Now use that underscores to get classname parts for hungarian style
1759                 foreach (explode('_', $str) as $strPart) {
1760                         // Make the class name part lower case and first upper case
1761                         $className .= ucfirst(strtolower($strPart));
1762                 } // END - foreach
1763
1764                 // Return class name
1765                 return $className;
1766         }
1767
1768         /**
1769          * Marks up the code by adding e.g. line numbers
1770          *
1771          * @param       $phpCode                Unmarked PHP code
1772          * @return      $markedCode             Marked PHP code
1773          */
1774         public function markupCode ($phpCode) {
1775                 // Init marked code
1776                 $markedCode = '';
1777
1778                 // Get last error
1779                 $errorArray = error_get_last();
1780
1781                 // Init the code with error message
1782                 if (is_array($errorArray)) {
1783                         // Get error infos
1784                         $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>',
1785                                 basename($errorArray['file']),
1786                                 $errorArray['line'],
1787                                 $errorArray['message'],
1788                                 $errorArray['type']
1789                         );
1790                 } // END - if
1791
1792                 // Add line number to the code
1793                 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1794                         // Add line numbers
1795                         $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
1796                                 ($lineNo + 1),
1797                                 htmlentities($code, ENT_QUOTES)
1798                         );
1799                 } // END - foreach
1800
1801                 // Return the code
1802                 return $markedCode;
1803         }
1804
1805         /**
1806          * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1807          * beatiful for web-based front-ends. If null is given a message id
1808          * null_timestamp will be resolved and returned.
1809          *
1810          * @param       $timestamp      Timestamp to prepare (filter) for display
1811          * @return      $readable       A readable timestamp
1812          */
1813         public function doFilterFormatTimestamp ($timestamp) {
1814                 // Default value to return
1815                 $readable = '???';
1816
1817                 // Is the timestamp null?
1818                 if (is_null($timestamp)) {
1819                         // Get a message string
1820                         $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1821                 } else {
1822                         switch ($this->getLanguageInstance()->getLanguageCode()) {
1823                                 case 'de': // German format is a bit different to default
1824                                         // Split the GMT stamp up
1825                                         $dateTime  = explode(' ', $timestamp  );
1826                                         $dateArray = explode('-', $dateTime[0]);
1827                                         $timeArray = explode(':', $dateTime[1]);
1828
1829                                         // Construct the timestamp
1830                                         $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1831                                                 $dateArray[0],
1832                                                 $dateArray[1],
1833                                                 $dateArray[2],
1834                                                 $timeArray[0],
1835                                                 $timeArray[1],
1836                                                 $timeArray[2]
1837                                         );
1838                                         break;
1839
1840                                 default: // Default is pass-through
1841                                         $readable = $timestamp;
1842                                         break;
1843                         } // END - switch
1844                 }
1845
1846                 // Return the stamp
1847                 return $readable;
1848         }
1849
1850         /**
1851          * Filter a given number into a localized number
1852          *
1853          * @param       $value          The raw value from e.g. database
1854          * @return      $localized      Localized value
1855          */
1856         public function doFilterFormatNumber ($value) {
1857                 // Generate it from config and localize dependencies
1858                 switch ($this->getLanguageInstance()->getLanguageCode()) {
1859                         case 'de': // German format is a bit different to default
1860                                 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1861                                 break;
1862
1863                         default: // US, etc.
1864                                 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1865                                 break;
1866                 } // END - switch
1867
1868                 // Return it
1869                 return $localized;
1870         }
1871
1872         /**
1873          * "Getter" for databse entry
1874          *
1875          * @return      $entry  An array with database entries
1876          * @throws      NullPointerException    If the database result is not found
1877          * @throws      InvalidDatabaseResultException  If the database result is invalid
1878          */
1879         protected final function getDatabaseEntry () {
1880                 // Is there an instance?
1881                 if (!$this->getResultInstance() instanceof SearchableResult) {
1882                         // Throw an exception here
1883                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1884                 } // END - if
1885
1886                 // Rewind it
1887                 $this->getResultInstance()->rewind();
1888
1889                 // Do we have an entry?
1890                 if ($this->getResultInstance()->valid() === false) {
1891                         // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
1892                         throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1893                 } // END - if
1894
1895                 // Get next entry
1896                 $this->getResultInstance()->next();
1897
1898                 // Fetch it
1899                 $entry = $this->getResultInstance()->current();
1900
1901                 // And return it
1902                 return $entry;
1903         }
1904
1905         /**
1906          * Getter for field name
1907          *
1908          * @param       $fieldName              Field name which we shall get
1909          * @return      $fieldValue             Field value from the user
1910          * @throws      NullPointerException    If the result instance is null
1911          */
1912         public final function getField ($fieldName) {
1913                 // Default field value
1914                 $fieldValue = NULL;
1915
1916                 // Get result instance
1917                 $resultInstance = $this->getResultInstance();
1918
1919                 // Is this instance null?
1920                 if (is_null($resultInstance)) {
1921                         // Then the user instance is no longer valid (expired cookies?)
1922                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1923                 } // END - if
1924
1925                 // Get current array
1926                 $fieldArray = $resultInstance->current();
1927                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1928
1929                 // Convert dashes to underscore
1930                 $fieldName2 = StringUtils::convertDashesToUnderscores($fieldName);
1931
1932                 // Does the field exist?
1933                 if ($this->isFieldSet($fieldName)) {
1934                         // Get it
1935                         $fieldValue = $fieldArray[$fieldName2];
1936                 } elseif (defined('DEVELOPER')) {
1937                         // Missing field entry, may require debugging
1938                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
1939                 } else {
1940                         // Missing field entry, may require debugging
1941                         self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
1942                 }
1943
1944                 // Return it
1945                 return $fieldValue;
1946         }
1947
1948         /**
1949          * Checks if given field is set
1950          *
1951          * @param       $fieldName      Field name to check
1952          * @return      $isSet          Whether the given field name is set
1953          * @throws      NullPointerException    If the result instance is null
1954          */
1955         public function isFieldSet ($fieldName) {
1956                 // Get result instance
1957                 $resultInstance = $this->getResultInstance();
1958
1959                 // Is this instance null?
1960                 if (is_null($resultInstance)) {
1961                         // Then the user instance is no longer valid (expired cookies?)
1962                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1963                 } // END - if
1964
1965                 // Get current array
1966                 $fieldArray = $resultInstance->current();
1967                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
1968
1969                 // Convert dashes to underscore
1970                 $fieldName = StringUtils::convertDashesToUnderscores($fieldName);
1971
1972                 // Determine it
1973                 $isSet = isset($fieldArray[$fieldName]);
1974
1975                 // Return result
1976                 return $isSet;
1977         }
1978
1979         /**
1980          * Flushs all pending updates to the database layer
1981          *
1982          * @return      void
1983          */
1984         public function flushPendingUpdates () {
1985                 // Get result instance
1986                 $resultInstance = $this->getResultInstance();
1987
1988                 // Do we have data to update?
1989                 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1990                         // Get wrapper class name config entry
1991                         $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1992
1993                         // Create object instance
1994                         $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
1995
1996                         // Yes, then send the whole result to the database layer
1997                         $wrapperInstance->doUpdateByResult($this->getResultInstance());
1998                 } // END - if
1999         }
2000
2001         /**
2002          * Outputs a deprecation warning to the developer.
2003          *
2004          * @param       $message        The message we shall output to the developer
2005          * @return      void
2006          * @todo        Write a logging mechanism for productive mode
2007          */
2008         public function deprecationWarning ($message) {
2009                 // Is developer mode active?
2010                 if (defined('DEVELOPER')) {
2011                         // Debug instance is there?
2012                         if (!is_null($this->getDebugInstance())) {
2013                                 // Output stub message
2014                                 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2015                         } else {
2016                                 // Trigger an error
2017                                 trigger_error($message . "<br />\n");
2018                                 exit;
2019                         }
2020                 } else {
2021                         // @TODO Finish this part!
2022                         $this->partialStub('Developer mode inactive. Message:' . $message);
2023                 }
2024         }
2025
2026         /**
2027          * Checks whether the given PHP extension is loaded
2028          *
2029          * @param       $phpExtension   The PHP extension we shall check
2030          * @return      $isLoaded       Whether the PHP extension is loaded
2031          */
2032         public final function isPhpExtensionLoaded ($phpExtension) {
2033                 // Is it loaded?
2034                 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2035
2036                 // Return result
2037                 return $isLoaded;
2038         }
2039
2040         /**
2041          * "Getter" as a time() replacement but with milliseconds. You should use this
2042          * method instead of the encapsulated getimeofday() function.
2043          *
2044          * @return      $milliTime      Timestamp with milliseconds
2045          */
2046         public function getMilliTime () {
2047                 // Get the time of day as float
2048                 $milliTime = gettimeofday(true);
2049
2050                 // Return it
2051                 return $milliTime;
2052         }
2053
2054         /**
2055          * Idles (sleeps) for given milliseconds
2056          *
2057          * @return      $hasSlept       Whether it goes fine
2058          */
2059         public function idle ($milliSeconds) {
2060                 // Sleep is fine by default
2061                 $hasSlept = true;
2062
2063                 // Idle so long with found function
2064                 if (function_exists('time_sleep_until')) {
2065                         // Get current time and add idle time
2066                         $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2067
2068                         // New PHP 5.1.0 function found, ignore errors
2069                         $hasSlept = @time_sleep_until($sleepUntil);
2070                 } else {
2071                         /*
2072                          * My Sun station doesn't have that function even with latest PHP
2073                          * package. :(
2074                          */
2075                         usleep($milliSeconds * 1000);
2076                 }
2077
2078                 // Return result
2079                 return $hasSlept;
2080         }
2081         /**
2082          * Converts a hexadecimal string, even with negative sign as first string to
2083          * a decimal number using BC functions.
2084          *
2085          * This work is based on comment #86673 on php.net documentation page at:
2086          * <http://de.php.net/manual/en/function.dechex.php#86673>
2087          *
2088          * @param       $hex    Hexadecimal string
2089          * @return      $dec    Decimal number
2090          */
2091         protected function hex2dec ($hex) {
2092                 // Convert to all lower-case
2093                 $hex = strtolower($hex);
2094
2095                 // Detect sign (negative/positive numbers)
2096                 $sign = '';
2097                 if (substr($hex, 0, 1) == '-') {
2098                         $sign = '-';
2099                         $hex = substr($hex, 1);
2100                 } // END - if
2101
2102                 // Decode the hexadecimal string into a decimal number
2103                 $dec = 0;
2104                 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2105                         $factor = self::$hexdec[substr($hex, $i, 1)];
2106                         $dec = bcadd($dec, bcmul($factor, $e));
2107                 } // END - for
2108
2109                 // Return the decimal number
2110                 return $sign . $dec;
2111         }
2112
2113         /**
2114          * Converts even very large decimal numbers, also signed, to a hexadecimal
2115          * string.
2116          *
2117          * This work is based on comment #97756 on php.net documentation page at:
2118          * <http://de.php.net/manual/en/function.hexdec.php#97756>
2119          *
2120          * @param       $dec            Decimal number, even with negative sign
2121          * @param       $maxLength      Optional maximum length of the string
2122          * @return      $hex    Hexadecimal string
2123          */
2124         protected function dec2hex ($dec, $maxLength = 0) {
2125                 // maxLength can be zero or devideable by 2
2126                 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2127
2128                 // Detect sign (negative/positive numbers)
2129                 $sign = '';
2130                 if ($dec < 0) {
2131                         $sign = '-';
2132                         $dec = abs($dec);
2133                 } // END - if
2134
2135                 // Encode the decimal number into a hexadecimal string
2136                 $hex = '';
2137                 do {
2138                         $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2139                         $dec /= (2 ^ 4);
2140                 } while ($dec >= 1);
2141
2142                 /*
2143                  * Leading zeros are required for hex-decimal "numbers". In some
2144                  * situations more leading zeros are wanted, so check for both
2145                  * conditions.
2146                  */
2147                 if ($maxLength > 0) {
2148                         // Prepend more zeros
2149                         $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2150                 } elseif ((strlen($hex) % 2) != 0) {
2151                         // Only make string's length dividable by 2
2152                         $hex = '0' . $hex;
2153                 }
2154
2155                 // Return the hexadecimal string
2156                 return $sign . $hex;
2157         }
2158
2159         /**
2160          * Converts a ASCII string (0 to 255) into a decimal number.
2161          *
2162          * @param       $asc    The ASCII string to be converted
2163          * @return      $dec    Decimal number
2164          */
2165         protected function asc2dec ($asc) {
2166                 // Convert it into a hexadecimal number
2167                 $hex = bin2hex($asc);
2168
2169                 // And back into a decimal number
2170                 $dec = $this->hex2dec($hex);
2171
2172                 // Return it
2173                 return $dec;
2174         }
2175
2176         /**
2177          * Converts a decimal number into an ASCII string.
2178          *
2179          * @param       $dec            Decimal number
2180          * @return      $asc    An ASCII string
2181          */
2182         protected function dec2asc ($dec) {
2183                 // First convert the number into a hexadecimal string
2184                 $hex = $this->dec2hex($dec);
2185
2186                 // Then convert it into the ASCII string
2187                 $asc = $this->hex2asc($hex);
2188
2189                 // Return it
2190                 return $asc;
2191         }
2192
2193         /**
2194          * Converts a hexadecimal number into an ASCII string. Negative numbers
2195          * are not allowed.
2196          *
2197          * @param       $hex    Hexadecimal string
2198          * @return      $asc    An ASCII string
2199          */
2200         protected function hex2asc ($hex) {
2201                 // Check for length, it must be devideable by 2
2202                 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2203                 assert((strlen($hex) % 2) == 0);
2204
2205                 // Walk the string
2206                 $asc = '';
2207                 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2208                         // Get the decimal number of the chunk
2209                         $part = hexdec(substr($hex, $idx, 2));
2210
2211                         // Add it to the final string
2212                         $asc .= chr($part);
2213                 } // END - for
2214
2215                 // Return the final string
2216                 return $asc;
2217         }
2218
2219         /**
2220          * Checks whether the given encoded data was encoded with Base64
2221          *
2222          * @param       $encodedData    Encoded data we shall check
2223          * @return      $isBase64               Whether the encoded data is Base64
2224          */
2225         protected function isBase64Encoded ($encodedData) {
2226                 // Determine it
2227                 $isBase64 = (@base64_decode($encodedData, true) !== false);
2228
2229                 // Return it
2230                 return $isBase64;
2231         }
2232
2233         /**
2234          * Gets a cache key from Criteria instance
2235          *
2236          * @param       $criteriaInstance       An instance of a Criteria class
2237          * @param       $onlyKeys                       Only use these keys for a cache key
2238          * @return      $cacheKey                       A cache key suitable for lookup/storage purposes
2239          */
2240         protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2241                 // Generate it
2242                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: criteriaInstance=' . $criteriaInstance->__toString() . ',onlyKeys()=' . count($onlyKeys) . ' - CALLED!');
2243                 $cacheKey = sprintf('%s@%s',
2244                         $this->__toString(),
2245                         $criteriaInstance->getCacheKey($onlyKeys)
2246                 );
2247
2248                 // And return it
2249                 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('BASE-FRAMEWORK-SYSTEM: cacheKey=' . $cacheKey . ' - EXIT!');
2250                 return $cacheKey;
2251         }
2252
2253         /**
2254          * Getter for startup time in miliseconds
2255          *
2256          * @return      $startupTime    Startup time in miliseconds
2257          */
2258         protected function getStartupTime () {
2259                 return self::$startupTime;
2260         }
2261
2262         /**
2263          * "Getter" for a printable currently execution time in nice braces
2264          *
2265          * @return      $executionTime  Current execution time in nice braces
2266          */
2267         protected function getPrintableExecutionTime () {
2268                 // Caculate the execution time
2269                 $executionTime = microtime(true) - $this->getStartupTime();
2270
2271                 // Pack it in nice braces
2272                 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2273
2274                 // And return it
2275                 return $executionTime;
2276         }
2277
2278         /**
2279          * Hashes a given string with a simple but stronger hash function (no salt)
2280          * and hex-encode it.
2281          *
2282          * @param       $str    The string to be hashed
2283          * @return      $hash   The hash from string $str
2284          */
2285         public static final function hash ($str) {
2286                 // Hash given string with (better secure) hasher
2287                 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2288
2289                 // Return it
2290                 return $hash;
2291         }
2292
2293         /**
2294          * "Getter" for length of hash() output. This will be "cached" to speed up
2295          * things.
2296          *
2297          * @return      $length         Length of hash() output
2298          */
2299         public static final function getHashLength () {
2300                 // Is it cashed?
2301                 if (is_null(self::$hashLength)) {
2302                         // No, then hash a string and save its length.
2303                         self::$hashLength = strlen(self::hash('abc123'));
2304                 } // END - if
2305
2306                 // Return it
2307                 return self::$hashLength;
2308         }
2309
2310         /**
2311          * Checks whether the given number is really a number (only chars 0-9).
2312          *
2313          * @param       $num            A string consisting only chars between 0 and 9
2314          * @param       $castValue      Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2315          * @param       $assertMismatch         Whether to assert mismatches
2316          * @return      $ret            The (hopefully) secured numbered value
2317          */
2318         public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2319                 // Filter all numbers out
2320                 $ret = preg_replace('/[^0123456789]/', '', $num);
2321
2322                 // Shall we cast?
2323                 if ($castValue === true) {
2324                         // Cast to biggest numeric type
2325                         $ret = (double) $ret;
2326                 } // END - if
2327
2328                 // Assert only if requested
2329                 if ($assertMismatch === true) {
2330                         // Has the whole value changed?
2331                         assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2332                 } // END - if
2333
2334                 // Return result
2335                 return $ret;
2336         }
2337
2338         /**
2339          * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2340          *
2341          * @param       $num    A string consisting only chars between 0 and 9
2342          * @param       $assertMismatch         Whether to assert mismatches
2343          * @return      $ret    The (hopefully) secured hext-numbered value
2344          */
2345         public function hexval ($num, $assertMismatch = false) {
2346                 // Filter all numbers out
2347                 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2348
2349                 // Assert only if requested
2350                 if ($assertMismatch === true) {
2351                         // Has the whole value changed?
2352                         assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2353                 } // END - if
2354
2355                 // Return result
2356                 return $ret;
2357         }
2358
2359         /**
2360          * Determines if an element is set in the generic array
2361          *
2362          * @param       $keyGroup       Main group for the key
2363          * @param       $subGroup       Sub group for the key
2364          * @param       $key            Key to check
2365          * @param       $element        Element to check
2366          * @return      $isset          Whether the given key is set
2367          */
2368         protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2369                 // Debug message
2370                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2371
2372                 // Is it there?
2373                 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2374
2375                 // Return it
2376                 return $isset;
2377         }
2378         /**
2379          * Determines if a key is set in the generic array
2380          *
2381          * @param       $keyGroup       Main group for the key
2382          * @param       $subGroup       Sub group for the key
2383          * @param       $key            Key to check
2384          * @return      $isset          Whether the given key is set
2385          */
2386         protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2387                 // Debug message
2388                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2389
2390                 // Is it there?
2391                 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2392
2393                 // Return it
2394                 return $isset;
2395         }
2396
2397
2398         /**
2399          * Determines if a group is set in the generic array
2400          *
2401          * @param       $keyGroup       Main group
2402          * @param       $subGroup       Sub group
2403          * @return      $isset          Whether the given group is set
2404          */
2405         protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2406                 // Debug message
2407                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2408
2409                 // Is it there?
2410                 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2411
2412                 // Return it
2413                 return $isset;
2414         }
2415
2416         /**
2417          * Getter for sub key group
2418          *
2419          * @param       $keyGroup       Main key group
2420          * @param       $subGroup       Sub key group
2421          * @return      $array          An array with all array elements
2422          */
2423         protected final function getGenericSubArray ($keyGroup, $subGroup) {
2424                 // Is it there?
2425                 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2426                         // No, then abort here
2427                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2428                         exit;
2429                 } // END - if
2430
2431                 // Debug message
2432                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2433
2434                 // Return it
2435                 return $this->genericArray[$keyGroup][$subGroup];
2436         }
2437
2438         /**
2439          * Unsets a given key in generic array
2440          *
2441          * @param       $keyGroup       Main group for the key
2442          * @param       $subGroup       Sub group for the key
2443          * @param       $key            Key to unset
2444          * @return      void
2445          */
2446         protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2447                 // Debug message
2448                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2449
2450                 // Remove it
2451                 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2452         }
2453
2454         /**
2455          * Unsets a given element in generic array
2456          *
2457          * @param       $keyGroup       Main group for the key
2458          * @param       $subGroup       Sub group for the key
2459          * @param       $key            Key to unset
2460          * @param       $element        Element to unset
2461          * @return      void
2462          */
2463         protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2464                 // Debug message
2465                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2466
2467                 // Remove it
2468                 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2469         }
2470
2471         /**
2472          * Append a string to a given generic array key
2473          *
2474          * @param       $keyGroup       Main group for the key
2475          * @param       $subGroup       Sub group for the key
2476          * @param       $key            Key to unset
2477          * @param       $value          Value to add/append
2478          * @return      void
2479          */
2480         protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2481                 // Debug message
2482                 //* 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);
2483
2484                 // Is it already there?
2485                 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2486                         // Append it
2487                         $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2488                 } else {
2489                         // Add it
2490                         $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2491                 }
2492         }
2493
2494         /**
2495          * Append a string to a given generic array element
2496          *
2497          * @param       $keyGroup       Main group for the key
2498          * @param       $subGroup       Sub group for the key
2499          * @param       $key            Key to unset
2500          * @param       $element        Element to check
2501          * @param       $value          Value to add/append
2502          * @return      void
2503          */
2504         protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2505                 // Debug message
2506                 //* 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);
2507
2508                 // Is it already there?
2509                 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2510                         // Append it
2511                         $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2512                 } else {
2513                         // Add it
2514                         $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2515                 }
2516         }
2517
2518         /**
2519          * Sets a string in a given generic array element
2520          *
2521          * @param       $keyGroup       Main group for the key
2522          * @param       $subGroup       Sub group for the key
2523          * @param       $key            Key to unset
2524          * @param       $element        Element to check
2525          * @param       $value          Value to add/append
2526          * @return      void
2527          */
2528         protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2529                 // Debug message
2530                 //* 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);
2531
2532                 // Set it
2533                 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2534         }
2535
2536         /**
2537          * Initializes given generic array group
2538          *
2539          * @param       $keyGroup       Main group for the key
2540          * @param       $subGroup       Sub group for the key
2541          * @param       $key            Key to use
2542          * @param       $forceInit      Optionally force initialization
2543          * @return      void
2544          */
2545         protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2546                 // Debug message
2547                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2548
2549                 // Is it already set?
2550                 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2551                         // Already initialized
2552                         trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2553                         exit;
2554                 } // END - if
2555
2556                 // Initialize it
2557                 $this->genericArray[$keyGroup][$subGroup] = array();
2558         }
2559
2560         /**
2561          * Initializes given generic array key
2562          *
2563          * @param       $keyGroup       Main group for the key
2564          * @param       $subGroup       Sub group for the key
2565          * @param       $key            Key to use
2566          * @param       $forceInit      Optionally force initialization
2567          * @return      void
2568          */
2569         protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2570                 // Debug message
2571                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2572
2573                 // Is it already set?
2574                 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2575                         // Already initialized
2576                         trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2577                         exit;
2578                 } // END - if
2579
2580                 // Initialize it
2581                 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2582         }
2583
2584         /**
2585          * Initializes given generic array element
2586          *
2587          * @param       $keyGroup       Main group for the key
2588          * @param       $subGroup       Sub group for the key
2589          * @param       $key            Key to use
2590          * @param       $element        Element to use
2591          * @param       $forceInit      Optionally force initialization
2592          * @return      void
2593          */
2594         protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2595                 // Debug message
2596                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2597
2598                 // Is it already set?
2599                 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2600                         // Already initialized
2601                         trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2602                         exit;
2603                 } // END - if
2604
2605                 // Initialize it
2606                 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2607         }
2608
2609         /**
2610          * Pushes an element to a generic key
2611          *
2612          * @param       $keyGroup       Main group for the key
2613          * @param       $subGroup       Sub group for the key
2614          * @param       $key            Key to use
2615          * @param       $value          Value to add/append
2616          * @return      $count          Number of array elements
2617          */
2618         protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2619                 // Debug message
2620                 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2621
2622                 // Is it set?
2623                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2624                         // Initialize array
2625                         $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2626                 } // END - if
2627
2628                 // Then push it
2629                 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2630
2631                 // Return count
2632                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2633                 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2634                 return $count;
2635         }
2636
2637         /**
2638          * Pushes an element to a generic array element
2639          *
2640          * @param       $keyGroup       Main group for the key
2641          * @param       $subGroup       Sub group for the key
2642          * @param       $key            Key to use
2643          * @param       $element        Element to check
2644          * @param       $value          Value to add/append
2645          * @return      $count          Number of array elements
2646          */
2647         protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2648                 // Debug message
2649                 //* 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));
2650
2651                 // Is it set?
2652                 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2653                         // Initialize array
2654                         $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2655                 } // END - if
2656
2657                 // Then push it
2658                 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2659
2660                 // Return count
2661                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2662                 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2663                 return $count;
2664         }
2665
2666         /**
2667          * Pops an element from  a generic group
2668          *
2669          * @param       $keyGroup       Main group for the key
2670          * @param       $subGroup       Sub group for the key
2671          * @param       $key            Key to unset
2672          * @return      $value          Last "popped" value
2673          */
2674         protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2675                 // Debug message
2676                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2677
2678                 // Is it set?
2679                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2680                         // Not found
2681                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2682                         exit;
2683                 } // END - if
2684
2685                 // Then "pop" it
2686                 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2687
2688                 // Return value
2689                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2690                 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2691                 return $value;
2692         }
2693
2694         /**
2695          * Shifts an element from  a generic group
2696          *
2697          * @param       $keyGroup       Main group for the key
2698          * @param       $subGroup       Sub group for the key
2699          * @param       $key            Key to unset
2700          * @return      $value          Last "popped" value
2701          */
2702         protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2703                 // Debug message
2704                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2705
2706                 // Is it set?
2707                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2708                         // Not found
2709                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2710                         exit;
2711                 } // END - if
2712
2713                 // Then "shift" it
2714                 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2715
2716                 // Return value
2717                 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2718                 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2719                 return $value;
2720         }
2721
2722         /**
2723          * Count generic array group
2724          *
2725          * @param       $keyGroup       Main group for the key
2726          * @return      $count          Count of given group
2727          */
2728         protected final function countGenericArray ($keyGroup) {
2729                 // Debug message
2730                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2731
2732                 // Is it there?
2733                 if (!isset($this->genericArray[$keyGroup])) {
2734                         // Abort here
2735                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2736                         exit;
2737                 } // END - if
2738
2739                 // Then count it
2740                 $count = count($this->genericArray[$keyGroup]);
2741
2742                 // Debug message
2743                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2744
2745                 // Return it
2746                 return $count;
2747         }
2748
2749         /**
2750          * Count generic array sub group
2751          *
2752          * @param       $keyGroup       Main group for the key
2753          * @param       $subGroup       Sub group for the key
2754          * @return      $count          Count of given group
2755          */
2756         protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2757                 // Debug message
2758                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2759
2760                 // Is it there?
2761                 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2762                         // Abort here
2763                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2764                         exit;
2765                 } // END - if
2766
2767                 // Then count it
2768                 $count = count($this->genericArray[$keyGroup][$subGroup]);
2769
2770                 // Debug message
2771                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
2772
2773                 // Return it
2774                 return $count;
2775         }
2776
2777         /**
2778          * Count generic array elements
2779          *
2780          * @param       $keyGroup       Main group for the key
2781          * @param       $subGroup       Sub group for the key
2782          * @para        $key            Key to count
2783          * @return      $count          Count of given key
2784          */
2785         protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
2786                 // Debug message
2787                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2788
2789                 // Is it there?
2790                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2791                         // Abort here
2792                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2793                         exit;
2794                 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
2795                         // Not valid
2796                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
2797                         exit;
2798                 }
2799
2800                 // Then count it
2801                 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
2802
2803                 // Debug message
2804                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
2805
2806                 // Return it
2807                 return $count;
2808         }
2809
2810         /**
2811          * Getter for whole generic group array
2812          *
2813          * @param       $keyGroup       Key group to get
2814          * @return      $array          Whole generic array group
2815          */
2816         protected final function getGenericArray ($keyGroup) {
2817                 // Debug message
2818                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2819
2820                 // Is it there?
2821                 if (!isset($this->genericArray[$keyGroup])) {
2822                         // Then abort here
2823                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
2824                         exit;
2825                 } // END - if
2826
2827                 // Return it
2828                 return $this->genericArray[$keyGroup];
2829         }
2830
2831         /**
2832          * Setter for generic array key
2833          *
2834          * @param       $keyGroup       Key group to get
2835          * @param       $subGroup       Sub group for the key
2836          * @param       $key            Key to unset
2837          * @param       $value          Mixed value from generic array element
2838          * @return      void
2839          */
2840         protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2841                 // Debug message
2842                 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2843
2844                 // Set value here
2845                 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
2846         }
2847
2848         /**
2849          * Getter for generic array key
2850          *
2851          * @param       $keyGroup       Key group to get
2852          * @param       $subGroup       Sub group for the key
2853          * @param       $key            Key to unset
2854          * @return      $value          Mixed value from generic array element
2855          */
2856         protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
2857                 // Debug message
2858                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2859
2860                 // Is it there?
2861                 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2862                         // Then abort here
2863                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
2864                         exit;
2865                 } // END - if
2866
2867                 // Return it
2868                 return $this->genericArray[$keyGroup][$subGroup][$key];
2869         }
2870
2871         /**
2872          * Sets a value in given generic array key/element
2873          *
2874          * @param       $keyGroup       Main group for the key
2875          * @param       $subGroup       Sub group for the key
2876          * @param       $key            Key to set
2877          * @param       $element        Element to set
2878          * @param       $value          Value to set
2879          * @return      void
2880          */
2881         protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2882                 // Debug message
2883                 //* 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));
2884
2885                 // Then set it
2886                 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
2887         }
2888
2889         /**
2890          * Getter for generic array element
2891          *
2892          * @param       $keyGroup       Key group to get
2893          * @param       $subGroup       Sub group for the key
2894          * @param       $key            Key to look for
2895          * @param       $element        Element to look for
2896          * @return      $value          Mixed value from generic array element
2897          */
2898         protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2899                 // Debug message
2900                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2901
2902                 // Is it there?
2903                 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2904                         // Then abort here
2905                         trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
2906                         exit;
2907                 } // END - if
2908
2909                 // Return it
2910                 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
2911         }
2912
2913         /**
2914          * Checks if a given sub group is valid (array)
2915          *
2916          * @param       $keyGroup       Key group to get
2917          * @param       $subGroup       Sub group for the key
2918          * @return      $isValid        Whether given sub group is valid
2919          */
2920         protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
2921                 // Debug message
2922                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2923
2924                 // Determine it
2925                 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
2926
2927                 // Return it
2928                 return $isValid;
2929         }
2930
2931         /**
2932          * Checks if a given key is valid (array)
2933          *
2934          * @param       $keyGroup       Key group to get
2935          * @param       $subGroup       Sub group for the key
2936          * @param       $key            Key to check
2937          * @return      $isValid        Whether given sub group is valid
2938          */
2939         protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
2940                 // Debug message
2941                 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2942
2943                 // Determine it
2944                 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
2945
2946                 // Return it
2947                 return $isValid;
2948         }
2949
2950         /**
2951          * Initializes the web output instance
2952          *
2953          * @return      void
2954          */
2955         protected function initWebOutputInstance () {
2956                 // Get application instance
2957                 $applicationInstance = GenericRegistry::getRegistry()->getInstance('application');
2958
2959                 // Init web output instance
2960                 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
2961
2962                 // Set it locally
2963                 $this->setWebOutputInstance($outputInstance);
2964         }
2965
2966         /**
2967          * Translates boolean true to 'Y' and false to 'N'
2968          *
2969          * @param       $boolean                Boolean value
2970          * @return      $translated             Translated boolean value
2971          */
2972         public static final function translateBooleanToYesNo ($boolean) {
2973                 // Make sure it is really boolean
2974                 assert(is_bool($boolean));
2975
2976                 // "Translate" it
2977                 $translated = ($boolean === true) ? 'Y' : 'N';
2978
2979                 // ... and return it
2980                 return $translated;
2981         }
2982
2983         /**
2984          * Encodes raw data (almost any type) by "serializing" it and then pack it
2985          * into a "binary format".
2986          *
2987          * @param       $rawData        Raw data (almost any type)
2988          * @return      $encoded        Encoded data
2989          */
2990         protected function encodeData ($rawData) {
2991                 // Make sure no objects or resources pass through
2992                 assert(!is_object($rawData));
2993                 assert(!is_resource($rawData));
2994
2995                 // First "serialize" it (json_encode() is faster than serialize())
2996                 $encoded = $this->packString(json_encode($rawData));
2997
2998                 // And return it
2999                 return $encoded;
3000         }
3001
3002         /**
3003          * Pack a string into a "binary format". Please execuse me that this is
3004          * widely undocumented. :-(
3005          *
3006          * @param       $str            Unpacked string
3007          * @return      $packed         Packed string
3008          * @todo        Improve documentation
3009          */
3010         protected function packString ($str) {
3011                 // Debug message
3012                 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3013
3014                 // First compress the string (gzcompress is okay)
3015                 $str = gzcompress($str);
3016
3017                 // Init variable
3018                 $packed = '';
3019
3020                 // And start the "encoding" loop
3021                 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3022                         $big = 0;
3023                         for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3024                                 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3025
3026                                 if (($idx + $i) <= strlen($str)) {
3027                                         $ord = ord(substr($str, ($idx + $i), 1));
3028
3029                                         $add = $ord * pow(256, $factor);
3030
3031                                         $big += $add;
3032
3033                                         //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3034                                 } // END - if
3035                         } // END - for
3036
3037                         $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3038                         $r = $big & $this->packingData[$this->archArrayElement]['right'];
3039
3040                         $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3041                         //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3042
3043                         $packed .= $chunk;
3044                 } // END - for
3045
3046                 // Return it
3047                 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3048                 return $packed;
3049         }
3050
3051         /**
3052          * Creates a full-qualified file name (FQFN) for given file name by adding
3053          * a configured temporary file path to it.
3054          *
3055          * @param       $infoInstance   An instance of a SplFileInfo class
3056          * @return      $tempInstance   An instance of a SplFileInfo class (temporary file)
3057          * @throw       PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3058          * @throws      FileIoException If the file cannot be written
3059          */
3060          protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3061                 // Get config entry
3062                 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3063
3064                 // Is the path writeable?
3065                 if (!is_writable($basePath)) {
3066                         // Path is write-protected
3067                         throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3068                 } // END - if
3069
3070                 // Add it
3071                 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3072
3073                 // Is it reachable?
3074                 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3075                         // Not reachable
3076                         throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3077                 } // END - if
3078
3079                 // Return it
3080                 return $tempInstance;
3081          }
3082
3083         /**
3084          * "Getter" for a printable state name
3085          *
3086          * @return      $stateName      Name of the node's state in a printable format
3087          */
3088         public final function getPrintableState () {
3089                 // Default is 'null'
3090                 $stateName = 'null';
3091
3092                 // Get the state instance
3093                 $stateInstance = $this->getStateInstance();
3094
3095                 // Is it an instance of Stateable?
3096                 if ($stateInstance instanceof Stateable) {
3097                         // Then use that state name
3098                         $stateName = $stateInstance->getStateName();
3099                 } // END - if
3100
3101                 // Return result
3102                 return $stateName;
3103         }
3104
3105 }