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