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