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