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