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