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