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