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