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