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