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