63ba260e0abee10cbdd9861196d86455a0252d8b
[core.git] / inc / classes / main / class_BaseFrameworkSystem.php
1 <?php
2 /**
3  * The simulator system class is the super class of all other classes. This
4  * class handles saving of games etc.
5  *
6  * @author              Roland Haeder <webmaster@ship-simu.org>
7  * @version             0.0.0
8  * @copyright   Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2012 Core Developer Team
9  * @license             GNU GPL 3.0 or any newer version
10  * @link                http://www.ship-simu.org
11  *
12  * This program is free software: you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation, either version 3 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program. If not, see <http://www.gnu.org/licenses/>.
24  */
25 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
26         /**
27          * The real class name
28          */
29         private $realClass = 'BaseFrameworkSystem';
30
31         /**
32          * Instance of a request class
33          */
34         private $requestInstance = NULL;
35
36         /**
37          * Instance of a response class
38          */
39         private $responseInstance = NULL;
40
41         /**
42          * Search criteria instance
43          */
44         private $searchInstance = NULL;
45
46         /**
47          * Update criteria instance
48          */
49         private $updateInstance = NULL;
50
51         /**
52          * The file I/O instance for the template loader
53          */
54         private $fileIoInstance = NULL;
55
56         /**
57          * Resolver instance
58          */
59         private $resolverInstance = NULL;
60
61         /**
62          * Template engine instance
63          */
64         private $templateInstance = NULL;
65
66         /**
67          * Database result instance
68          */
69         private $resultInstance = NULL;
70
71         /**
72          * Instance for user class
73          */
74         private $userInstance = NULL;
75
76         /**
77          * A controller instance
78          */
79         private $controllerInstance = NULL;
80
81         /**
82          * Instance of a RNG
83          */
84         private $rngInstance = NULL;
85
86         /**
87          * Instance of a crypto helper
88          */
89         private $cryptoInstance = NULL;
90
91         /**
92          * Instance of an Iterator class
93          */
94         private $iteratorInstance = NULL;
95
96         /**
97          * Instance of the list
98          */
99         private $listInstance = NULL;
100
101         /**
102          * Instance of a menu
103          */
104         private $menuInstance = NULL;
105
106         /**
107          * Instance of the image
108          */
109         private $imageInstance = NULL;
110
111         /**
112          * Instance of the stacker
113          */
114         private $stackerInstance = NULL;
115
116         /**
117          * A Compressor instance
118          */
119         private $compressorInstance = NULL;
120
121         /**
122          * A Parseable instance
123          */
124         private $parserInstance = NULL;
125
126         /**
127          * A ProtocolHandler instance
128          */
129         private $protocolInstance = NULL;
130
131         /**
132          * A database wrapper instance
133          */
134         private $databaseInstance = NULL;
135
136         /**
137          * A helper instance for the form
138          */
139         private $helperInstance = NULL;
140
141         /**
142          * An instance of a Sourceable class
143          */
144         private $sourceInstance = NULL;
145
146         /**
147          * An instance of a InputStreamable class
148          */
149         private $inputStreamInstance = NULL;
150
151         /**
152          * An instance of a OutputStreamable class
153          */
154         private $outputStreamInstance = NULL;
155
156         /**
157          * Networkable handler instance
158          */
159         private $handlerInstance = NULL;
160
161         /**
162          * Visitor handler instance
163          */
164         private $visitorInstance = NULL;
165
166         /**
167          * An instance of a database wrapper class
168          */
169         private $wrapperInstance = NULL;
170
171         /**
172          * Thousands separator
173          */
174         private $thousands = '.'; // German
175
176         /**
177          * Decimal separator
178          */
179         private $decimals  = ','; // German
180
181         /**
182          * Socket resource
183          */
184         private $socketResource = false;
185
186         /**
187          * Package data
188          */
189         private $packageData = array();
190
191         /***********************
192          * Exception codes.... *
193          ***********************/
194
195         // @todo Try to clean these constants up
196         const EXCEPTION_IS_NULL_POINTER              = 0x001;
197         const EXCEPTION_IS_NO_OBJECT                 = 0x002;
198         const EXCEPTION_IS_NO_ARRAY                  = 0x003;
199         const EXCEPTION_MISSING_METHOD               = 0x004;
200         const EXCEPTION_CLASSES_NOT_MATCHING         = 0x005;
201         const EXCEPTION_INDEX_OUT_OF_BOUNDS          = 0x006;
202         const EXCEPTION_DIMENSION_ARRAY_INVALID      = 0x007;
203         const EXCEPTION_ITEM_NOT_TRADEABLE           = 0x008;
204         const EXCEPTION_ITEM_NOT_IN_PRICE_LIST       = 0x009;
205         const EXCEPTION_GENDER_IS_WRONG              = 0x00a;
206         const EXCEPTION_BIRTH_DATE_IS_INVALID        = 0x00b;
207         const EXCEPTION_EMPTY_STRUCTURES_ARRAY       = 0x00c;
208         const EXCEPTION_HAS_ALREADY_PERSONELL_LIST   = 0x00d;
209         const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES      = 0x00e;
210         const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED   = 0x00f;
211         const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS      = 0x010;
212         const EXCEPTION_CONTRACT_PARTNER_INVALID     = 0x011;
213         const EXCEPTION_CONTRACT_PARTNER_MISMATCH    = 0x012;
214         const EXCEPTION_CONTRACT_ALREADY_SIGNED      = 0x013;
215         const EXCEPTION_UNEXPECTED_EMPTY_STRING      = 0x014;
216         const EXCEPTION_PATH_NOT_FOUND               = 0x015;
217         const EXCEPTION_INVALID_PATH_NAME            = 0x016;
218         const EXCEPTION_READ_PROTECED_PATH           = 0x017;
219         const EXCEPTION_WRITE_PROTECED_PATH          = 0x018;
220         const EXCEPTION_DIR_POINTER_INVALID          = 0x019;
221         const EXCEPTION_FILE_POINTER_INVALID         = 0x01a;
222         const EXCEPTION_INVALID_RESOURCE             = 0x01b;
223         const EXCEPTION_UNEXPECTED_OBJECT            = 0x01c;
224         const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
225         const EXCEPTION_GETTER_IS_MISSING            = 0x01e;
226         const EXCEPTION_ARRAY_EXPECTED               = 0x01f;
227         const EXCEPTION_ARRAY_HAS_INVALID_COUNT      = 0x020;
228         const EXCEPTION_ID_IS_INVALID_FORMAT         = 0x021;
229         const EXCEPTION_MD5_CHECKSUMS_MISMATCH       = 0x022;
230         const EXCEPTION_UNEXPECTED_STRING_SIZE       = 0x023;
231         const EXCEPTION_SIMULATOR_ID_INVALID         = 0x024;
232         const EXCEPTION_MISMATCHING_COMPRESSORS      = 0x025;
233         const EXCEPTION_CONTAINER_ITEM_IS_NULL       = 0x026;
234         const EXCEPTION_ITEM_IS_NO_ARRAY             = 0x027;
235         const EXCEPTION_CONTAINER_MAYBE_DAMAGED      = 0x028;
236         const EXCEPTION_INVALID_STRING               = 0x029;
237         const EXCEPTION_VARIABLE_NOT_SET             = 0x02a;
238         const EXCEPTION_ATTRIBUTES_ARE_MISSING       = 0x02b;
239         const EXCEPTION_ARRAY_ELEMENTS_MISSING       = 0x02c;
240         const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED  = 0x02d;
241         const EXCEPTION_UNSPPORTED_OPERATION         = 0x02e;
242         const EXCEPTION_MISSING_ELEMENT              = 0x030;
243         const EXCEPTION_HEADERS_ALREADY_SENT         = 0x031;
244         const EXCEPTION_DEFAULT_CONTROLLER_GONE      = 0x032;
245         const EXCEPTION_CLASS_NOT_FOUND              = 0x033;
246         const EXCEPTION_REQUIRED_INTERFACE_MISSING   = 0x034;
247         const EXCEPTION_FATAL_ERROR                  = 0x035;
248         const EXCEPTION_FILE_NOT_FOUND               = 0x036;
249         const EXCEPTION_ASSERTION_FAILED             = 0x037;
250         const EXCEPTION_FILE_CANNOT_BE_READ          = 0x038;
251         const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x039;
252         const EXCEPTION_FILTER_CHAIN_INTERCEPTED     = 0x040;
253
254         /**
255          * Hexadecimal->Decimal translation array
256          */
257         private static $hexdec = array(
258                 '0' => 0,
259                 '1' => 1,
260                 '2' => 2,
261                 '3' => 3,
262                 '4' => 4,
263                 '5' => 5,
264                 '6' => 6,
265                 '7' => 7,
266                 '8' => 8,
267                 '9' => 9,
268                 'a' => 10,
269                 'b' => 11,
270                 'c' => 12,
271                 'd' => 13,
272                 'e' => 14,
273                 'f' => 15
274         );
275
276         /**
277          * Decimal->hexadecimal translation array
278          */
279         private static $dechex = array(
280                  0 => '0',
281                  1 => '1',
282                  2 => '2',
283                  3 => '3',
284                  4 => '4',
285                  5 => '5',
286                  6 => '6',
287                  7 => '7',
288                  8 => '8',
289                  9 => '9',
290                 10 => 'a',
291                 11 => 'b',
292                 12 => 'c',
293                 13 => 'd',
294                 14 => 'e',
295                 15 => 'f'
296         );
297
298         /**
299          * Startup time in miliseconds
300          */
301         private static $startupTime = 0;
302
303         /**
304          * Protected super constructor
305          *
306          * @param       $className      Name of the class
307          * @return      void
308          */
309         protected function __construct ($className) {
310                 // Set real class
311                 $this->setRealClass($className);
312
313                 // Set configuration instance if no registry ...
314                 if (!$this instanceof Register) {
315                         // ... because registries doesn't need to be configured
316                         $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
317                 } // END - if
318
319                 // Is the startup time set? (0 cannot be true anymore)
320                 if (self::$startupTime == 0) {
321                         // Then set it
322                         self::$startupTime = microtime(true);
323                 } // END - if
324         }
325
326         /**
327          * Destructor for all classes
328          *
329          * @return      void
330          */
331         public function __destruct() {
332                 // Flush any updated entries to the database
333                 $this->flushPendingUpdates();
334
335                 // Is this object already destroyed?
336                 if ($this->__toString() != 'DestructedObject') {
337                         // Destroy all informations about this class but keep some text about it alive
338                         $this->setRealClass('DestructedObject');
339                 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
340                         // Already destructed object
341                         $this->debugOutput(sprintf("[%s:] The object <span class=\"object_name\">%s</span> is already destroyed.",
342                                 __CLASS__,
343                                 $this->__toString()
344                         ));
345                 }
346         }
347
348         /**
349          * The __call() method where all non-implemented methods end up
350          *
351          * @param       $methodName             Name of the missing method
352          * @args        $args                   Arguments passed to the method
353          * @return      void
354          */
355         public final function __call ($methodName, $args) {
356                 // Implode all given arguments
357                 $argsString = '';
358                 if (empty($args)) {
359                         // No arguments
360                         $argsString = 'NULL';
361                 } elseif (is_array($args)) {
362                         // Some arguments are there
363                         foreach ($args as $arg) {
364                                 // Add the value itself if not array. This prevents 'array to string conversion' message
365                                 if (is_array($arg)) {
366                                         $argsString .= 'Array';
367                                 } else {
368                                         $argsString .= $arg;
369                                 }
370
371                                 // Add data about the argument
372                                 $argsString .= ' (' . gettype($arg);
373
374                                 if (is_string($arg)) {
375                                         // Add length for strings
376                                         $argsString .= ', '.strlen($arg);
377                                 } elseif (is_array($arg)) {
378                                         // .. or size if array
379                                         $argsString .= ', '.count($arg);
380                                 } elseif ($arg === true) {
381                                         // ... is boolean 'true'
382                                         $argsString .= ', true';
383                                 } elseif ($arg === false) {
384                                         // ... is boolean 'true'
385                                         $argsString .= ', false';
386                                 }
387
388                                 // Closing bracket
389                                 $argsString .= '), ';
390                         } // END - foreach
391
392                         // Remove last comma
393                         if (substr($argsString, -2, 1) == ',') {
394                                 $argsString = substr($argsString, 0, -2);
395                         } // END - if
396                 } else {
397                         // Invalid arguments!
398                         $argsString = '!INVALID:' . gettype($args) . '!';
399                 }
400
401                 // Output stub message
402                 $this->debugOutput(sprintf("[%s-&gt;%s] Stub! Args: %s",
403                         $this->__toString(),
404                         $methodName,
405                         $argsString
406                 ));
407
408                 // Return nothing
409                 return NULL;
410         }
411
412         /**
413          * Getter for $realClass
414          *
415          * @return      $realClass The name of the real class (not BaseFrameworkSystem)
416          */
417         public function __toString () {
418                 return $this->realClass;
419         }
420
421         /**
422          * Magic function to catch setting of missing but set class fields/attributes
423          *
424          * @param       $name   Name of the field/attribute
425          * @param       $value  Value to store
426          * @return      void
427          */
428         public final function __set ($name, $value) {
429                 $this->debugBackTrace(sprintf("Tried to set a missing field. name=%s, value[%s]=%s",
430                         $name,
431                         gettype($value),
432                         $value
433                 ));
434         }
435
436         /**
437          * Magic function to catch getting of missing fields/attributes
438          *
439          * @param       $name   Name of the field/attribute
440          * @return      void
441          */
442         public final function __get ($name) {
443                 $this->debugBackTrace(sprintf("Tried to get a missing field. name=%s",
444                         $name
445                 ));
446         }
447
448         /**
449          * Magic function to catch unsetting of missing fields/attributes
450          *
451          * @param       $name   Name of the field/attribute
452          * @return      void
453          */
454         public final function __unset ($name) {
455                 $this->debugBackTrace(sprintf("Tried to unset a missing field. name=%s",
456                         $name
457                 ));
458         }
459
460         /**
461          * Setter for the real class name
462          *
463          * @param       $realClass      Class name (string)
464          * @return      void
465          */
466         public final function setRealClass ($realClass) {
467                 // Set real class
468                 $this->realClass = (string) $realClass;
469         }
470
471         /**
472          * Setter for database result instance
473          *
474          * @param       $resultInstance         An instance of a database result class
475          * @return      void
476          * @todo        SearchableResult and UpdateableResult shall have a super interface to use here
477          */
478         protected final function setResultInstance (SearchableResult $resultInstance) {
479                 $this->resultInstance =  $resultInstance;
480         }
481
482         /**
483          * Getter for database result instance
484          *
485          * @return      $resultInstance         An instance of a database result class
486          */
487         public final function getResultInstance () {
488                 return $this->resultInstance;
489         }
490
491         /**
492          * Setter for template engine instances
493          *
494          * @param       $templateInstance       An instance of a template engine class
495          * @return      void
496          */
497         protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
498                 $this->templateInstance = $templateInstance;
499         }
500
501         /**
502          * Getter for template engine instances
503          *
504          * @return      $templateInstance       An instance of a template engine class
505          */
506         protected final function getTemplateInstance () {
507                 return $this->templateInstance;
508         }
509
510         /**
511          * Setter for search instance
512          *
513          * @param       $searchInstance         Searchable criteria instance
514          * @return      void
515          */
516         public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
517                 $this->searchInstance = $searchInstance;
518         }
519
520         /**
521          * Getter for search instance
522          *
523          * @return      $searchInstance         Searchable criteria instance
524          */
525         public final function getSearchInstance () {
526                 return $this->searchInstance;
527         }
528
529         /**
530          * Setter for update instance
531          *
532          * @param       $updateInstance         Searchable criteria instance
533          * @return      void
534          */
535         public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
536                 $this->updateInstance = $updateInstance;
537         }
538
539         /**
540          * Getter for update instance
541          *
542          * @return      $updateInstance         Updateable criteria instance
543          */
544         public final function getUpdateInstance () {
545                 return $this->updateInstance;
546         }
547
548         /**
549          * Setter for resolver instance
550          *
551          * @param       $resolverInstance       Instance of a command resolver class
552          * @return      void
553          */
554         public final function setResolverInstance (Resolver $resolverInstance) {
555                 $this->resolverInstance = $resolverInstance;
556         }
557
558         /**
559          * Getter for resolver instance
560          *
561          * @return      $resolverInstance       Instance of a command resolver class
562          */
563         public final function getResolverInstance () {
564                 return $this->resolverInstance;
565         }
566
567         /**
568          * Setter for language instance
569          *
570          * @param       $configInstance         The configuration instance which shall
571          *                                                              be FrameworkConfiguration
572          * @return      void
573          */
574         public final function setConfigInstance (FrameworkConfiguration $configInstance) {
575                 Registry::getRegistry()->addInstance('config', $configInstance);
576         }
577
578         /**
579          * Getter for configuration instance
580          *
581          * @return      $configInstance         Configuration instance
582          */
583         public final function getConfigInstance () {
584                 $configInstance = Registry::getRegistry()->getInstance('config');
585                 return $configInstance;
586         }
587
588         /**
589          * Setter for debug instance
590          *
591          * @param       $debugInstance  The instance for debug output class
592          * @return      void
593          */
594         public final function setDebugInstance (DebugMiddleware $debugInstance) {
595                 Registry::getRegistry()->addInstance('debug', $debugInstance);
596         }
597
598         /**
599          * Getter for debug instance
600          *
601          * @return      $debugInstance  Instance to class DebugConsoleOutput or DebugWebOutput
602          */
603         public final function getDebugInstance () {
604                 // Get debug instance
605                 $debugInstance = Registry::getRegistry()->getInstance('debug');
606
607                 // Return it
608                 return $debugInstance;
609         }
610
611         /**
612          * Setter for web output instance
613          *
614          * @param       $webInstance    The instance for web output class
615          * @return      void
616          */
617         public final function setWebOutputInstance (OutputStreamer $webInstance) {
618                 Registry::getRegistry()->addInstance('web_output', $webInstance);
619         }
620
621         /**
622          * Getter for web output instance
623          *
624          * @return      $webOutputInstance - Instance to class WebOutput
625          */
626         public final function getWebOutputInstance () {
627                 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
628                 return $webOutputInstance;
629         }
630
631         /**
632          * Setter for database instance
633          *
634          * @param       $databaseInstance       The instance for the database connection (forced DatabaseConnection)
635          * @return      void
636          */
637         public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
638                 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
639         }
640
641         /**
642          * Getter for database layer
643          *
644          * @return      $databaseInstance       The database layer instance
645          */
646         public final function getDatabaseInstance () {
647                 // Get instance
648                 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
649
650                 // Return instance
651                 return $databaseInstance;
652         }
653
654         /**
655          * Setter for compressor channel
656          *
657          * @param       $compressorInstance             An instance of CompressorChannel
658          * @return      void
659          */
660         public final function setCompressorChannel (CompressorChannel $compressorInstance) {
661                 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
662         }
663
664         /**
665          * Getter for compressor channel
666          *
667          * @return      $compressorInstance             The compressor channel
668          */
669         public final function getCompressorChannel () {
670                 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
671                 return $compressorInstance;
672         }
673
674         /**
675          * Protected getter for a manageable application helper class
676          *
677          * @return      $applicationInstance    An instance of a manageable application helper class
678          */
679         protected final function getApplicationInstance () {
680                 $applicationInstance = Registry::getRegistry()->getInstance('application');
681                 return $applicationInstance;
682         }
683
684         /**
685          * Setter for a manageable application helper class
686          *
687          * @param       $applicationInstance    An instance of a manageable application helper class
688          * @return      void
689          */
690         public final function setApplicationInstance (ManageableApplication $applicationInstance) {
691                 Registry::getRegistry()->addInstance('application', $applicationInstance);
692         }
693
694         /**
695          * Setter for request instance
696          *
697          * @param       $requestInstance        An instance of a Requestable class
698          * @return      void
699          */
700         public final function setRequestInstance (Requestable $requestInstance) {
701                 $this->requestInstance = $requestInstance;
702         }
703
704         /**
705          * Getter for request instance
706          *
707          * @return      $requestInstance        An instance of a Requestable class
708          */
709         public final function getRequestInstance () {
710                 return $this->requestInstance;
711         }
712
713         /**
714          * Setter for response instance
715          *
716          * @param       $responseInstance       An instance of a Responseable class
717          * @return      void
718          */
719         public final function setResponseInstance (Responseable $responseInstance) {
720                 $this->responseInstance = $responseInstance;
721         }
722
723         /**
724          * Getter for response instance
725          *
726          * @return      $responseInstance       An instance of a Responseable class
727          */
728         public final function getResponseInstance () {
729                 return $this->responseInstance;
730         }
731
732         /**
733          * Private getter for language instance
734          *
735          * @return      $langInstance   An instance to the language sub-system
736          */
737         protected final function getLanguageInstance () {
738                 $langInstance = Registry::getRegistry()->getInstance('language');
739                 return $langInstance;
740         }
741
742         /**
743          * Setter for language instance
744          *
745          * @param       $langInstance   An instance to the language sub-system
746          * @return      void
747          * @see         LanguageSystem
748          */
749         public final function setLanguageInstance (ManageableLanguage $langInstance) {
750                 Registry::getRegistry()->addInstance('language', $langInstance);
751         }
752
753         /**
754          * Private getter for file IO instance
755          *
756          * @return      $fileIoInstance         An instance to the file I/O sub-system
757          */
758         protected final function getFileIoInstance () {
759                 return $this->fileIoInstance;
760         }
761
762         /**
763          * Setter for file I/O instance
764          *
765          * @param       $fileIoInstance         An instance to the file I/O sub-system
766          * @return      void
767          */
768         public final function setFileIoInstance (FileIoHandler $fileIoInstance) {
769                 $this->fileIoInstance = $fileIoInstance;
770         }
771
772         /**
773          * Protected setter for user instance
774          *
775          * @param       $userInstance   An instance of a user class
776          * @return      void
777          */
778         protected final function setUserInstance (ManageableAccount $userInstance) {
779                 $this->userInstance = $userInstance;
780         }
781
782         /**
783          * Getter for user instance
784          *
785          * @return      $userInstance   An instance of a user class
786          */
787         public final function getUserInstance () {
788                 return $this->userInstance;
789         }
790
791         /**
792          * Setter for controller instance (this surely breaks a bit the MVC patterm)
793          *
794          * @param       $controllerInstance             An instance of the controller
795          * @return      void
796          */
797         public final function setControllerInstance (Controller $controllerInstance) {
798                 $this->controllerInstance = $controllerInstance;
799         }
800
801         /**
802          * Getter for controller instance (this surely breaks a bit the MVC patterm)
803          *
804          * @return      $controllerInstance             An instance of the controller
805          */
806         public final function getControllerInstance () {
807                 return $this->controllerInstance;
808         }
809
810         /**
811          * Setter for RNG instance
812          *
813          * @param       $rngInstance    An instance of a random number generator (RNG)
814          * @return      void
815          */
816         protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
817                 $this->rngInstance = $rngInstance;
818         }
819
820         /**
821          * Getter for RNG instance
822          *
823          * @return      $rngInstance    An instance of a random number generator (RNG)
824          */
825         public final function getRngInstance () {
826                 return $this->rngInstance;
827         }
828
829         /**
830          * Setter for Cryptable instance
831          *
832          * @param       $cryptoInstance An instance of a Cryptable class
833          * @return      void
834          */
835         protected final function setCryptoInstance (Cryptable $cryptoInstance) {
836                 $this->cryptoInstance = $cryptoInstance;
837         }
838
839         /**
840          * Getter for Cryptable instance
841          *
842          * @return      $cryptoInstance An instance of a Cryptable class
843          */
844         public final function getCryptoInstance () {
845                 return $this->cryptoInstance;
846         }
847
848         /**
849          * Setter for the list instance
850          *
851          * @param       $listInstance   A list of Listable
852          * @return      void
853          */
854         protected final function setListInstance (Listable $listInstance) {
855                 $this->listInstance = $listInstance;
856         }
857
858         /**
859          * Getter for the list instance
860          *
861          * @return      $listInstance   A list of Listable
862          */
863         protected final function getListInstance () {
864                 return $this->listInstance;
865         }
866
867         /**
868          * Setter for the menu instance
869          *
870          * @param       $menuInstance   A RenderableMenu instance
871          * @return      void
872          */
873         protected final function setMenuInstance (RenderableMenu $menuInstance) {
874                 $this->menuInstance = $menuInstance;
875         }
876
877         /**
878          * Getter for the menu instance
879          *
880          * @return      $menuInstance   A RenderableMenu instance
881          */
882         protected final function getMenuInstance () {
883                 return $this->menuInstance;
884         }
885
886         /**
887          * Setter for image instance
888          *
889          * @param       $imageInstance  An instance of an image
890          * @return      void
891          */
892         public final function setImageInstance (BaseImage $imageInstance) {
893                 $this->imageInstance = $imageInstance;
894         }
895
896         /**
897          * Getter for image instance
898          *
899          * @return      $imageInstance  An instance of an image
900          */
901         public final function getImageInstance () {
902                 return $this->imageInstance;
903         }
904
905         /**
906          * Setter for stacker instance
907          *
908          * @param       $stackerInstance        An instance of an stacker
909          * @return      void
910          */
911         public final function setStackerInstance (Stackable $stackerInstance) {
912                 $this->stackerInstance = $stackerInstance;
913         }
914
915         /**
916          * Getter for stacker instance
917          *
918          * @return      $stackerInstance        An instance of an stacker
919          */
920         public final function getStackerInstance () {
921                 return $this->stackerInstance;
922         }
923
924         /**
925          * Setter for compressor instance
926          *
927          * @param       $compressorInstance     An instance of an compressor
928          * @return      void
929          */
930         public final function setCompressorInstance (Compressor $compressorInstance) {
931                 $this->compressorInstance = $compressorInstance;
932         }
933
934         /**
935          * Getter for compressor instance
936          *
937          * @return      $compressorInstance     An instance of an compressor
938          */
939         public final function getCompressorInstance () {
940                 return $this->compressorInstance;
941         }
942
943         /**
944          * Setter for Parseable instance
945          *
946          * @param       $parserInstance An instance of an Parseable
947          * @return      void
948          */
949         public final function setParserInstance (Parseable $parserInstance) {
950                 $this->parserInstance = $parserInstance;
951         }
952
953         /**
954          * Getter for Parseable instance
955          *
956          * @return      $parserInstance An instance of an Parseable
957          */
958         public final function getParserInstance () {
959                 return $this->parserInstance;
960         }
961
962         /**
963          * Setter for ProtocolHandler instance
964          *
965          * @param       $protocolInstance       An instance of an ProtocolHandler
966          * @return      void
967          */
968         public final function setProtocolInstance (ProtocolHandler $protocolInstance = NULL) {
969                 $this->protocolInstance = $protocolInstance;
970         }
971
972         /**
973          * Getter for ProtocolHandler instance
974          *
975          * @return      $protocolInstance       An instance of an ProtocolHandler
976          */
977         public final function getProtocolInstance () {
978                 return $this->protocolInstance;
979         }
980
981         /**
982          * Setter for BaseDatabaseWrapper instance
983          *
984          * @param       $wrapperInstance        An instance of an BaseDatabaseWrapper
985          * @return      void
986          */
987         public final function setWrapperInstance (BaseDatabaseWrapper $wrapperInstance) {
988                 $this->wrapperInstance = $wrapperInstance;
989         }
990
991         /**
992          * Getter for BaseDatabaseWrapper instance
993          *
994          * @return      $wrapperInstance        An instance of an BaseDatabaseWrapper
995          */
996         public final function getWrapperInstance () {
997                 return $this->wrapperInstance;
998         }
999
1000         /**
1001          * Setter for socket resource
1002          *
1003          * @param       $socketResource         A valid socket resource
1004          * @return      void
1005          */
1006         public final function setSocketResource ($socketResource) {
1007                 //* NOISY-DEBUG: */ $this->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1008                 $this->socketResource = $socketResource;
1009         }
1010
1011         /**
1012          * Getter for socket resource
1013          *
1014          * @return      $socketResource         A valid socket resource
1015          */
1016         public final function getSocketResource () {
1017                 //* NOISY-DEBUG: */ $this->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1018                 return $this->socketResource;
1019         }
1020
1021         /**
1022          * Setter for helper instance
1023          *
1024          * @param       $helperInstance         An instance of a helper class
1025          * @return      void
1026          */
1027         protected final function setHelperInstance (Helper $helperInstance) {
1028                 $this->helperInstance = $helperInstance;
1029         }
1030
1031         /**
1032          * Getter for helper instance
1033          *
1034          * @return      $helperInstance         An instance of a helper class
1035          */
1036         public final function getHelperInstance () {
1037                 return $this->helperInstance;
1038         }
1039
1040         /**
1041          * Setter for a Sourceable instance
1042          *
1043          * @param       $sourceInstance The Sourceable instance
1044          * @return      void
1045          */
1046         protected final function setSourceInstance (Sourceable $sourceInstance) {
1047                 $this->sourceInstance = $sourceInstance;
1048         }
1049
1050         /**
1051          * Getter for a Sourceable instance
1052          *
1053          * @return      $sourceInstance The Sourceable instance
1054          */
1055         protected final function getSourceInstance () {
1056                 return $this->sourceInstance;
1057         }
1058
1059         /**
1060          * Getter for a InputStreamable instance
1061          *
1062          * @param       $inputStreamInstance    The InputStreamable instance
1063          */
1064         protected final function getInputStreamInstance () {
1065                 return $this->inputStreamInstance;
1066         }
1067
1068         /**
1069          * Setter for a InputStreamable instance
1070          *
1071          * @param       $inputStreamInstance    The InputStreamable instance
1072          * @return      void
1073          */
1074         protected final function setInputStreamInstance (InputStreamable $inputStreamInstance) {
1075                 $this->inputStreamInstance = $inputStreamInstance;
1076         }
1077
1078         /**
1079          * Getter for a OutputStreamable instance
1080          *
1081          * @param       $outputStreamInstance   The OutputStreamable instance
1082          */
1083         protected final function getOutputStreamInstance () {
1084                 return $this->outputStreamInstance;
1085         }
1086
1087         /**
1088          * Setter for a OutputStreamable instance
1089          *
1090          * @param       $outputStreamInstance   The OutputStreamable instance
1091          * @return      void
1092          */
1093         protected final function setOutputStreamInstance (OutputStreamable $outputStreamInstance) {
1094                 $this->outputStreamInstance = $outputStreamInstance;
1095         }
1096
1097         /**
1098          * Setter for handler instance
1099          *
1100          * @param       $handlerInstance        An instance of a Handleable class
1101          * @return      void
1102          */
1103         protected final function setHandlerInstance (Handleable $handlerInstance) {
1104                 $this->handlerInstance = $handlerInstance;
1105         }
1106
1107         /**
1108          * Getter for handler instance
1109          *
1110          * @return      $handlerInstance        A Networkable instance
1111          */
1112         protected final function getHandlerInstance () {
1113                 return $this->handlerInstance;
1114         }
1115
1116         /**
1117          * Setter for visitor instance
1118          *
1119          * @param       $visitorInstance        A Visitor instance
1120          * @return      void
1121          */
1122         protected final function setVisitorInstance (Visitor $visitorInstance) {
1123                 $this->visitorInstance = $visitorInstance;
1124         }
1125
1126         /**
1127          * Getter for visitor instance
1128          *
1129          * @return      $visitorInstance        A Visitor instance
1130          */
1131         protected final function getVisitorInstance () {
1132                 return $this->visitorInstance;
1133         }
1134
1135         /**
1136          * Setter for raw package Data
1137          *
1138          * @param       $packageData    Raw package Data
1139          * @return      void
1140          */
1141         public final function setPackageData (array $packageData) {
1142                 $this->packageData = $packageData;
1143         }
1144
1145         /**
1146          * Getter for raw package Data
1147          *
1148          * @return      $packageData    Raw package Data
1149          */
1150         public function getPackageData () {
1151                 return $this->packageData;
1152         }
1153
1154
1155         /**
1156          * Setter for Iterator instance
1157          *
1158          * @param       $iteratorInstance       An instance of an Iterator
1159          * @return      void
1160          */
1161         protected final function setIteratorInstance (Iterator $iteratorInstance) {
1162                 $this->iteratorInstance = $iteratorInstance;
1163         }
1164
1165         /**
1166          * Getter for Iterator instance
1167          *
1168          * @return      $iteratorInstance       An instance of an Iterator
1169          */
1170         public final function getIteratorInstance () {
1171                 return $this->iteratorInstance;
1172         }
1173
1174         /**
1175          * Checks whether an object equals this object. You should overwrite this
1176          * method to implement own equality checks
1177          *
1178          * @param       $objectInstance         An instance of a FrameworkInterface object
1179          * @return      $equals                         Whether both objects equals
1180          */
1181         public function equals (FrameworkInterface $objectInstance) {
1182                 // Now test it
1183                 $equals = ((
1184                         $this->__toString() == $objectInstance->__toString()
1185                 ) && (
1186                         $this->hashCode() == $objectInstance->hashCode()
1187                 ));
1188
1189                 // Return the result
1190                 return $equals;
1191         }
1192
1193         /**
1194          * Generates a generic hash code of this class. You should really overwrite
1195          * this method with your own hash code generator code. But keep KISS in mind.
1196          *
1197          * @return      $hashCode       A generic hash code respresenting this whole class
1198          */
1199         public function hashCode () {
1200                 // Simple hash code
1201                 return crc32($this->__toString());
1202         }
1203
1204         /**
1205          * Formats computer generated price values into human-understandable formats
1206          * with thousand and decimal separators.
1207          *
1208          * @param       $value          The in computer format value for a price
1209          * @param       $currency       The currency symbol (use HTML-valid characters!)
1210          * @param       $decNum         Number of decimals after commata
1211          * @return      $price          The for the current language formated price string
1212          * @throws      MissingDecimalsThousandsSeparatorException      If decimals or
1213          *                                                                                              thousands separator
1214          *                                                                                              is missing
1215          */
1216         public function formatCurrency ($value, $currency = '&euro;', $decNum = 2) {
1217                 // Are all required attriutes set?
1218                 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1219                         // Throw an exception
1220                         throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1221                 } // END - if
1222
1223                 // Cast the number
1224                 $value = (float) $value;
1225
1226                 // Reformat the US number
1227                 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1228
1229                 // Return as string...
1230                 return $price;
1231         }
1232
1233         /**
1234          * Appends a trailing slash to a string
1235          *
1236          * @param       $str    A string (maybe) without trailing slash
1237          * @return      $str    A string with an auto-appended trailing slash
1238          */
1239         public final function addMissingTrailingSlash ($str) {
1240                 // Is there a trailing slash?
1241                 if (substr($str, -1, 1) != '/') {
1242                         $str .= '/';
1243                 } // END - if
1244
1245                 // Return string with trailing slash
1246                 return $str;
1247         }
1248
1249         /**
1250          * Prepare the template engine (WebTemplateEngine by default) for a given
1251          * application helper instance (ApplicationHelper by default).
1252          *
1253          * @param               $applicationInstance    An application helper instance or
1254          *                                                                              null if we shall use the default
1255          * @return              $templateInstance               The template engine instance
1256          * @throws              NullPointerException    If the discovered application
1257          *                                                                              instance is still null
1258          */
1259         protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1260                 // Is the application instance set?
1261                 if (is_null($applicationInstance)) {
1262                         // Get the current instance
1263                         $applicationInstance = $this->getApplicationInstance();
1264
1265                         // Still null?
1266                         if (is_null($applicationInstance)) {
1267                                 // Thrown an exception
1268                                 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1269                         } // END - if
1270                 } // END - if
1271
1272                 // Initialize the template engine
1273                 $templateInstance = ObjectFactory::createObjectByConfiguredName('web_template_class');
1274
1275                 // Return the prepared instance
1276                 return $templateInstance;
1277         }
1278
1279         /**
1280          * Debugs this instance by putting out it's full content
1281          *
1282          * @param       $message        Optional message to show in debug output
1283          * @return      void
1284          */
1285         public final function debugInstance ($message = '') {
1286                 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1287                 restore_error_handler();
1288
1289                 // Init content
1290                 $content = '';
1291
1292                 // Is a message set?
1293                 if (!empty($message)) {
1294                         // Construct message
1295                         $content = sprintf("<div class=\"debug_message\">Message: %s</div>\n", $message);
1296                 } // END - if
1297
1298                 // Generate the output
1299                 $content .= sprintf("<pre>%s</pre>",
1300                         trim(
1301                                 htmlentities(
1302                                         print_r($this, true)
1303                                 )
1304                         )
1305                 );
1306
1307                 // Output it
1308                 ApplicationEntryPoint::app_die(sprintf("<div class=\"debug_header\">%s debug output:</div><div class=\"debug_content\">%s</div>\nLoaded includes: <div class=\"debug_include_list\">%s</div>",
1309                         $this->__toString(),
1310                         $content,
1311                         ClassLoader::getSelfInstance()->getPrintableIncludeList()
1312                 ));
1313         }
1314
1315         /**
1316          * Replaces control characters with printable output
1317          *
1318          * @param       $str    String with control characters
1319          * @return      $str    Replaced string
1320          */
1321         protected function replaceControlCharacters ($str) {
1322                 // Replace them
1323                 $str = str_replace(
1324                         chr(13), '[r]', str_replace(
1325                         chr(10), '[n]', str_replace(
1326                         chr(9) , '[t]',
1327                         $str
1328                 )));
1329
1330                 // Return it
1331                 return $str;
1332         }
1333
1334         /**
1335          * Output a partial stub message for the caller method
1336          *
1337          * @param       $message        An optional message to display
1338          * @return      void
1339          */
1340         protected function partialStub ($message = '') {
1341                 // Get the backtrace
1342                 $backtrace = debug_backtrace();
1343
1344                 // Generate the class::method string
1345                 $methodName = 'UnknownClass-&gt;unknownMethod';
1346                 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1347                         $methodName = $backtrace[1]['class'] . '-&gt;' . $backtrace[1]['function'];
1348                 } // END - if
1349
1350                 // Construct the full message
1351                 $stubMessage = sprintf('[%s:] Partial stub!',
1352                         $methodName
1353                 );
1354
1355                 // Is the extra message given?
1356                 if (!empty($message)) {
1357                         // Then add it as well
1358                         $stubMessage .= ' Message: ' . $message;
1359                 } // END - if
1360
1361                 // Debug instance is there?
1362                 if (!is_null($this->getDebugInstance())) {
1363                         // Output stub message
1364                         $this->debugOutput($stubMessage);
1365                 } else {
1366                         // Trigger an error
1367                         trigger_error($stubMessage);
1368                 }
1369         }
1370
1371         /**
1372          * Outputs a debug backtrace and stops further script execution
1373          *
1374          * @param       $message        An optional message to output
1375          * @param       $doExit         Whether exit the program (true is default)
1376          * @return      void
1377          */
1378         public function debugBackTrace ($message = '', $doExit = true) {
1379                 // Sorry, there is no other way getting this nice backtrace
1380                 if (!empty($message)) {
1381                         // Output message
1382                         printf('Message: %s<br />' . chr(10), $message);
1383                 } // END - if
1384
1385                 print('<pre>');
1386                 debug_print_backtrace();
1387                 print('</pre>');
1388
1389                 // Exit program?
1390                 if ($doExit === true) {
1391                         exit();
1392                 } // END - if
1393         }
1394
1395         /**
1396          * Outputs a debug message whether to debug instance (should be set!) or dies with or pints the message
1397          *
1398          * @param       $message        Message we shall send out...
1399          * @param       $doPrint        Whether print or die here (default: print)
1400          * @paran       $stripTags      Whether to strip tags (default: false)
1401          * @return      void
1402          */
1403         public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1404                 // Set debug instance to NULL
1405                 $debugInstance = NULL;
1406
1407                 // Try it:
1408                 try {
1409                         // Get debug instance
1410                         $debugInstance = $this->getDebugInstance();
1411                 } catch (NullPointerException $e) {
1412                         // The debug instance is not set (yet)
1413                 }
1414
1415                 // Is the debug instance there?
1416                 if (is_object($debugInstance)) {
1417                         // Use debug output handler
1418                         $debugInstance->output($message);
1419
1420                         if ($doPrint === false) {
1421                                 // Die here if not printed
1422                                 die();
1423                         } // END - if
1424                 } else {
1425                         // Put directly out
1426                         if ($doPrint === true) {
1427                                 // Are debug times enabled?
1428                                 if ($this->getConfigInstance()->getConfigEntry('debug_output_timings') == 'Y') {
1429                                         // Output it first
1430                                         print($this->getPrintableExecutionTime());
1431                                 } // END - if
1432
1433                                 // Print message
1434                                 print($message . chr(10));
1435                         } else {
1436                                 /*
1437                                  * BIG FAT NOTE: Do NEVER rewrite this to app_die(), this will
1438                                  * cause an endless loop.
1439                                  */
1440                                 die($message);
1441                         }
1442                 }
1443         }
1444
1445         /**
1446          * Converts e.g. a command from URL to a valid class by keeping out bad characters
1447          *
1448          * @param       $str            The string, what ever it is needs to be converted
1449          * @return      $className      Generated class name
1450          */
1451         public function convertToClassName ($str) {
1452                 // Init class name
1453                 $className = '';
1454
1455                 // Convert all dashes in underscores
1456                 $str = $this->convertDashesToUnderscores($str);
1457
1458                 // Now use that underscores to get classname parts for hungarian style
1459                 foreach (explode('_', $str) as $strPart) {
1460                         // Make the class name part lower case and first upper case
1461                         $className .= ucfirst(strtolower($strPart));
1462                 } // END - foreach
1463
1464                 // Return class name
1465                 return $className;
1466         }
1467
1468         /**
1469          * Converts dashes to underscores, e.g. useable for configuration entries
1470          *
1471          * @param       $str    The string with maybe dashes inside
1472          * @return      $str    The converted string with no dashed, but underscores
1473          */
1474         public final function convertDashesToUnderscores ($str) {
1475                 // Convert them all
1476                 $str = str_replace('-', '_', $str);
1477
1478                 // Return converted string
1479                 return $str;
1480         }
1481
1482         /**
1483          * Marks up the code by adding e.g. line numbers
1484          *
1485          * @param       $phpCode                Unmarked PHP code
1486          * @return      $markedCode             Marked PHP code
1487          */
1488         public function markupCode ($phpCode) {
1489                 // Init marked code
1490                 $markedCode = '';
1491
1492                 // Get last error
1493                 $errorArray = error_get_last();
1494
1495                 // Init the code with error message
1496                 if (is_array($errorArray)) {
1497                         // Get error infos
1498                         $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>',
1499                                 basename($errorArray['file']),
1500                                 $errorArray['line'],
1501                                 $errorArray['message'],
1502                                 $errorArray['type']
1503                         );
1504                 } // END - if
1505
1506                 // Add line number to the code
1507                 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
1508                         // Add line numbers
1509                         $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . chr(10),
1510                                 ($lineNo + 1),
1511                                 htmlentities($code, ENT_QUOTES)
1512                         );
1513                 } // END - foreach
1514
1515                 // Return the code
1516                 return $markedCode;
1517         }
1518
1519         /**
1520          * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
1521          * beatiful for web-based front-ends. If null is given a message id
1522          * null_timestamp will be resolved and returned.
1523          *
1524          * @param       $timestamp      Timestamp to prepare (filter) for display
1525          * @return      $readable       A readable timestamp
1526          */
1527         public function doFilterFormatTimestamp ($timestamp) {
1528                 // Default value to return
1529                 $readable = '???';
1530
1531                 // Is the timestamp null?
1532                 if (is_null($timestamp)) {
1533                         // Get a message string
1534                         $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
1535                 } else {
1536                         switch ($this->getLanguageInstance()->getLanguageCode()) {
1537                                 case 'de': // German format is a bit different to default
1538                                         // Split the GMT stamp up
1539                                         $dateTime  = explode(' ', $timestamp  );
1540                                         $dateArray = explode('-', $dateTime[0]);
1541                                         $timeArray = explode(':', $dateTime[1]);
1542
1543                                         // Construct the timestamp
1544                                         $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
1545                                                 $dateArray[0],
1546                                                 $dateArray[1],
1547                                                 $dateArray[2],
1548                                                 $timeArray[0],
1549                                                 $timeArray[1],
1550                                                 $timeArray[2]
1551                                         );
1552                                         break;
1553
1554                                 default: // Default is pass-through
1555                                         $readable = $timestamp;
1556                                         break;
1557                         } // END - switch
1558                 }
1559
1560                 // Return the stamp
1561                 return $readable;
1562         }
1563
1564         /**
1565          * Filter a given number into a localized number
1566          *
1567          * @param       $value          The raw value from e.g. database
1568          * @return      $localized      Localized value
1569          */
1570         public function doFilterFormatNumber ($value) {
1571                 // Generate it from config and localize dependencies
1572                 switch ($this->getLanguageInstance()->getLanguageCode()) {
1573                         case 'de': // German format is a bit different to default
1574                                 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
1575                                 break;
1576
1577                         default: // US, etc.
1578                                 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
1579                                 break;
1580                 } // END - switch
1581
1582                 // Return it
1583                 return $localized;
1584         }
1585
1586         /**
1587          * "Getter" for databse entry
1588          *
1589          * @return      $entry  An array with database entries
1590          * @throws      NullPointerException    If the database result is not found
1591          * @throws      InvalidDatabaseResultException  If the database result is invalid
1592          */
1593         protected final function getDatabaseEntry () {
1594                 // Is there an instance?
1595                 if (is_null($this->getResultInstance())) {
1596                         // Throw an exception here
1597                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1598                 } // END - if
1599
1600                 // Rewind it
1601                 $this->getResultInstance()->rewind();
1602
1603                 // Do we have an entry?
1604                 if ($this->getResultInstance()->valid() === false) {
1605                         throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), DatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
1606                 } // END - if
1607
1608                 // Get next entry
1609                 $this->getResultInstance()->next();
1610
1611                 // Fetch it
1612                 $entry = $this->getResultInstance()->current();
1613
1614                 // And return it
1615                 return $entry;
1616         }
1617
1618         /**
1619          * Getter for field name
1620          *
1621          * @param       $fieldName              Field name which we shall get
1622          * @return      $fieldValue             Field value from the user
1623          * @throws      NullPointerException    If the result instance is null
1624          */
1625         public final function getField ($fieldName) {
1626                 // Default field value
1627                 $fieldValue = NULL;
1628
1629                 // Get result instance
1630                 $resultInstance = $this->getResultInstance();
1631
1632                 // Is this instance null?
1633                 if (is_null($resultInstance)) {
1634                         // Then the user instance is no longer valid (expired cookies?)
1635                         throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1636                 } // END - if
1637
1638                 // Get current array
1639                 $fieldArray = $resultInstance->current();
1640                 //* DEBUG: */ $this->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
1641
1642                 // Convert dashes to underscore
1643                 $fieldName = $this->convertDashesToUnderscores($fieldName);
1644
1645                 // Does the field exist?
1646                 if (isset($fieldArray[$fieldName])) {
1647                         // Get it
1648                         $fieldValue = $fieldArray[$fieldName];
1649                 } else {
1650                         // Missing field entry, may require debugging
1651                         $this->debugOutput($this->__toString() . ':fieldname=' . $fieldName . ' not found!');
1652                 }
1653
1654                 // Return it
1655                 return $fieldValue;
1656         }
1657
1658         /**
1659          * Flushs all pending updates to the database layer
1660          *
1661          * @return      void
1662          */
1663         public function flushPendingUpdates () {
1664                 // Get result instance
1665                 $resultInstance = $this->getResultInstance();
1666
1667                 // Do we have data to update?
1668                 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
1669                         // Get wrapper class name config entry
1670                         $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
1671
1672                         // Create object instance
1673                         $wrapperInstance = ObjectFactory::createObjectByConfiguredName($configEntry);
1674
1675                         // Yes, then send the whole result to the database layer
1676                         $wrapperInstance->doUpdateByResult($this->getResultInstance());
1677                 } // END - if
1678         }
1679
1680         /**
1681          * Outputs a deprecation warning to the developer.
1682          *
1683          * @param       $message        The message we shall output to the developer
1684          * @return      void
1685          * @todo        Write a logging mechanism for productive mode
1686          */
1687         public function deprecationWarning ($message) {
1688                 // Is developer mode active?
1689                 if (defined('DEVELOPER')) {
1690                         // Debug instance is there?
1691                         if (!is_null($this->getDebugInstance())) {
1692                                 // Output stub message
1693                                 $this->debugOutput($message);
1694                         } else {
1695                                 // Trigger an error
1696                                 trigger_error($message . "<br />\n");
1697                         }
1698                 } else {
1699                         // @TODO Finish this part!
1700                         $this->partialStub('Developer mode inactive. Message:' . $message);
1701                 }
1702         }
1703
1704         /**
1705          * Checks whether the given PHP extension is loaded
1706          *
1707          * @param       $phpExtension   The PHP extension we shall check
1708          * @return      $isLoaded       Whether the PHP extension is loaded
1709          */
1710         public final function isPhpExtensionLoaded ($phpExtension) {
1711                 // Is it loaded?
1712                 $isLoaded = in_array($phpExtension, get_loaded_extensions());
1713
1714                 // Return result
1715                 return $isLoaded;
1716         }
1717
1718         /**
1719          * "Getter" as a time() replacement but with milliseconds. You should use this
1720          * method instead of the encapsulated getimeofday() function.
1721          *
1722          * @return      $milliTime      Timestamp with milliseconds
1723          */
1724         public function getMilliTime () {
1725                 // Get the time of day as float
1726                 $milliTime = gettimeofday(true);
1727
1728                 // Return it
1729                 return $milliTime;
1730         }
1731
1732         /**
1733          * Idles (sleeps) for given milliseconds
1734          *
1735          * @return      $hasSlept       Whether it goes fine
1736          */
1737         public function idle ($milliSeconds) {
1738                 // Sleep is fine by default
1739                 $hasSlept = true;
1740
1741                 // Idle so long with found function
1742                 if (function_exists('time_sleep_until')) {
1743                         // Get current time and add idle time
1744                         $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
1745
1746                         // New PHP 5.1.0 function found, ignore errors
1747                         $hasSlept = @time_sleep_until($sleepUntil);
1748                 } else {
1749                         /*
1750                          * My Sun station doesn't have that function even with latest PHP
1751                          * package. :(
1752                          */
1753                         usleep($milliSeconds * 1000);
1754                 }
1755
1756                 // Return result
1757                 return $hasSlept;
1758         }
1759         /**
1760          * Converts a hexadecimal string, even with negative sign as first string to
1761          * a decimal number using BC functions.
1762          *
1763          * This work is based on comment #86673 on php.net documentation page at:
1764          * <http://de.php.net/manual/en/function.dechex.php#86673>
1765          *
1766          * @param       $hex    Hexadecimal string
1767          * @return      $dec    Decimal number
1768          */
1769         protected function hex2dec ($hex) {
1770                 // Convert to all lower-case
1771                 $hex = strtolower($hex);
1772
1773                 // Detect sign (negative/positive numbers)
1774                 $sign = '';
1775                 if (substr($hex, 0, 1) == '-') {
1776                         $sign = '-';
1777                         $hex = substr($hex, 1);
1778                 } // END - if
1779
1780                 // Decode the hexadecimal string into a decimal number
1781                 $dec = 0;
1782                 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
1783                         $factor = self::$hexdec[substr($hex, $i, 1)];
1784                         $dec = bcadd($dec, bcmul($factor, $e));
1785                 } // END - for
1786
1787                 // Return the decimal number
1788                 return $sign . $dec;
1789         }
1790
1791         /**
1792          * Converts even very large decimal numbers, also with negative sign, to a
1793          * hexadecimal string.
1794          *
1795          * This work is based on comment #97756 on php.net documentation page at:
1796          * <http://de.php.net/manual/en/function.hexdec.php#97756>
1797          *
1798          * @param       $dec            Decimal number, even with negative sign
1799          * @param       $maxLength      Optional maximum length of the string
1800          * @return      $hex    Hexadecimal string
1801          */
1802         protected function dec2hex ($dec, $maxLength = 0) {
1803                 // maxLength can be zero or devideable by 2
1804                 assert(($maxLength == 0) || (($maxLength % 2) == 0));
1805
1806                 // Detect sign (negative/positive numbers)
1807                 $sign = '';
1808                 if ($dec < 0) {
1809                         $sign = '-';
1810                         $dec = abs($dec);
1811                 } // END - if
1812
1813                 // Encode the decimal number into a hexadecimal string
1814                 $hex = '';
1815                 do {
1816                         $hex = self::$dechex[($dec % 16)] . $hex;
1817                         $dec /= 16;
1818                 } while ($dec >= 1);
1819
1820                 /*
1821                  * We need hexadecimal strings with leading zeros if the length cannot
1822                  * be divided by 2
1823                  */
1824                 if ($maxLength > 0) {
1825                         // Prepend more zeros
1826                         $hex = $this->prependStringToString($hex, '0', $maxLength);
1827                 } elseif ((strlen($hex) % 2) != 0) {
1828                         $hex = '0' . $hex;
1829                 }
1830
1831                 // Return the hexadecimal string
1832                 return $sign . $hex;
1833         }
1834
1835         /**
1836          * Converts a ASCII string (0 to 255) into a decimal number.
1837          *
1838          * @param       $asc    The ASCII string to be converted
1839          * @return      $dec    Decimal number
1840          */
1841         protected function asc2dec ($asc) {
1842                 // Convert it into a hexadecimal number
1843                 $hex = bin2hex($asc);
1844
1845                 // And back into a decimal number
1846                 $dec = $this->hex2dec($hex);
1847
1848                 // Return it
1849                 return $dec;
1850         }
1851
1852         /**
1853          * Converts a decimal number into an ASCII string.
1854          *
1855          * @param       $dec            Decimal number
1856          * @return      $asc    An ASCII string
1857          */
1858         protected function dec2asc ($dec) {
1859                 // First convert the number into a hexadecimal string
1860                 $hex = $this->dec2hex($dec);
1861
1862                 // Then convert it into the ASCII string
1863                 $asc = $this->hex2asc($hex);
1864
1865                 // Return it
1866                 return $asc;
1867         }
1868
1869         /**
1870          * Converts a hexadecimal number into an ASCII string. Negative numbers
1871          * are not allowed.
1872          *
1873          * @param       $hex    Hexadecimal string
1874          * @return      $asc    An ASCII string
1875          */
1876         protected function hex2asc ($hex) {
1877                 // Check for length, it must be devideable by 2
1878                 //* DEBUG: */ $this->debugOutput('hex='.$hex);
1879                 assert((strlen($hex) % 2) == 0);
1880
1881                 // Walk the string
1882                 $asc = '';
1883                 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
1884                         // Get the decimal number of the chunk
1885                         $part = hexdec(substr($hex, $idx, 2));
1886
1887                         // Add it to the final string
1888                         $asc .= chr($part);
1889                 } // END - for
1890
1891                 // Return the final string
1892                 return $asc;
1893         }
1894
1895         /**
1896          * Prepends a given string $prepend to $str with a given total length
1897          *
1898          * @param       $str            Given original string which should be prepended
1899          * @param       $prepend        The string to prepend
1900          * @param       $length         Total length of the final string
1901          * @return      $strFinal       Final prepended string
1902          */
1903         protected function prependStringToString ($str, $prepend, $length) {
1904                 // Set final string to original string by default
1905                 $strFinal = $str;
1906
1907                 // Can it devided
1908                 if (strlen($str) < $length) {
1909                         // Difference between total length and length of original string
1910                         $diff = $length - strlen($str);
1911
1912                         // Prepend the string
1913                         $prepend = str_repeat($prepend, ($diff / strlen($prepend) + 1));
1914
1915                         // Make sure it will definedly fit
1916                         assert(strlen($prepend) >= $diff);
1917
1918                         // Cut it a little down
1919                         $prepend = substr($prepend, 0, $diff);
1920                         //* DEBUG: */ $this->debugOutput('prepend('.strlen($prepend).')='.$prepend.',diff='.$diff.',length='.$length);
1921
1922                         // Construct the final prepended string
1923                         $strFinal = $prepend . $str;
1924                 } // END - if
1925
1926                 // Return it
1927                 return $strFinal;
1928         }
1929
1930         /**
1931          * Checks whether the given encoded data was encoded with Base64
1932          *
1933          * @param       $encodedData    Encoded data we shall check
1934          * @return      $isBase64               Whether the encoded data is Base64
1935          */
1936         protected function isBase64Encoded ($encodedData) {
1937                 // Determine it
1938                 $isBase64 = (@base64_decode($encodedData, true) !== false);
1939
1940                 // Return it
1941                 return $isBase64;
1942         }
1943
1944         /**
1945          * "Getter" to get response/request type from analysis of the system.
1946          *
1947          * @return      $responseType   Analyzed response type
1948          */
1949         protected function getResponseTypeFromSystem () {
1950                 // Default is console
1951                 $responseType = 'console';
1952
1953                 // Is 'HTTP_HOST' set?
1954                 if (isset($_SERVER['HTTP_HOST'])) {
1955                         // Then it is a HTTP response/request
1956                         $responseType = 'http';
1957                 } // END - if
1958
1959                 // Return it
1960                 return $responseType;
1961         }
1962
1963         /**
1964          * Gets a cache key from Criteria instance
1965          *
1966          * @param       $criteriaInstance       An instance of a Criteria class
1967          * @param       $onlyKeys                       Only use these keys for a cache key
1968          * @return      $cacheKey                       A cache key suitable for lookup/storage purposes
1969          */
1970         protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
1971                 // Generate it
1972                 $cacheKey = sprintf("%s@%s",
1973                         $this->__toString(),
1974                         $criteriaInstance->getCacheKey($onlyKeys)
1975                 );
1976
1977                 // And return it
1978                 //* NOISY-DEBUG: */ $this->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
1979                 return $cacheKey;
1980         }
1981
1982         /**
1983          * Getter for startup time in miliseconds
1984          *
1985          * @return      $startupTime    Startup time in miliseconds
1986          */
1987         protected function getStartupTime () {
1988                 return self::$startupTime;
1989         }
1990
1991         /**
1992          * "Getter" for a printable currently execution time in nice braces
1993          *
1994          * @return      $executionTime  Current execution time in nice braces
1995          */
1996         protected function getPrintableExecutionTime () {
1997                 // Caculate the execution time
1998                 $executionTime = microtime(true) - $this->getStartupTime();
1999
2000                 // Pack it in nice braces
2001                 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2002
2003                 // And return it
2004                 return $executionTime;
2005         }
2006
2007         /**
2008          * Hashes a given string with a simple but stronger hash function (no salts)
2009          *
2010          * @param       $str    The string to be hashed
2011          * @return      $hash   The hash from string $str
2012          */
2013         public function hashString ($str) {
2014                 // Hash given string with (better secure) hasher
2015                 $hash = mhash(MHASH_SHA256, $str);
2016
2017                 // Return it
2018                 return $hash;
2019         }
2020
2021         /**
2022          * Checks whether the given number is really a number (only chars 0-9).
2023          *
2024          * @param       $num            A string consisting only chars between 0 and 9
2025          * @param       $castValue      Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2026          * @param       $assertMismatch         Whether to assert mismatches
2027          * @return      $ret            The (hopefully) secured numbered value
2028          */
2029         public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2030                 // Filter all numbers out
2031                 $ret = preg_replace('/[^0123456789]/', '', $num);
2032
2033                 // Shall we cast?
2034                 if ($castValue === true) {
2035                         // Cast to biggest numeric type
2036                         $ret = (double) $ret;
2037                 } // END - if
2038
2039                 // Assert only if requested
2040                 if ($assertMismatch === true) {
2041                         // Has the whole value changed?
2042                         assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2043                 } // END - if
2044
2045                 // Return result
2046                 return $ret;
2047         }
2048
2049         /**
2050          * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2051          *
2052          * @param       $num    A string consisting only chars between 0 and 9
2053          * @param       $assertMismatch         Whether to assert mismatches
2054          * @return      $ret    The (hopefully) secured hext-numbered value
2055          */
2056         public function hexval ($num, $assertMismatch = false) {
2057                 // Filter all numbers out
2058                 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2059
2060                 // Assert only if requested
2061                 if ($assertMismatch === true) {
2062                         // Has the whole value changed?
2063                         assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2064                 } // END - if
2065
2066                 // Return result
2067                 return $ret;
2068         }
2069 }
2070
2071 // [EOF]
2072 ?>