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