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