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