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