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