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