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