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