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