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