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