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