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