3 namespace Org\Mxchange\CoreFramework\Object;
5 // Import framework stuff
6 use Org\Mxchange\CoreFramework\Bootstrap\FrameworkBootstrap;
7 use Org\Mxchange\CoreFramework\Compressor\Compressor;
8 use Org\Mxchange\CoreFramework\Configuration\FrameworkConfiguration;
9 use Org\Mxchange\CoreFramework\Connection\Database\DatabaseConnection;
10 use Org\Mxchange\CoreFramework\Controller\Controller;
11 use Org\Mxchange\CoreFramework\Criteria\Criteria;
12 use Org\Mxchange\CoreFramework\Criteria\Local\LocalSearchCriteria;
13 use Org\Mxchange\CoreFramework\Criteria\Local\LocalUpdateCriteria;
14 use Org\Mxchange\CoreFramework\Crypto\Cryptable;
15 use Org\Mxchange\CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
16 use Org\Mxchange\CoreFramework\Database\Frontend\DatabaseWrapper;
17 use Org\Mxchange\CoreFramework\EntryPoint\ApplicationEntryPoint;
18 use Org\Mxchange\CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
19 use Org\Mxchange\CoreFramework\Factory\ObjectFactory;
20 use Org\Mxchange\CoreFramework\Filesystem\Block;
21 use Org\Mxchange\CoreFramework\Filesystem\FilePointer;
22 use Org\Mxchange\CoreFramework\Filesystem\FrameworkDirectory;
23 use Org\Mxchange\CoreFramework\Filesystem\PathWriteProtectedException;
24 use Org\Mxchange\CoreFramework\Generic\FrameworkInterface;
25 use Org\Mxchange\CoreFramework\Generic\NullPointerException;
26 use Org\Mxchange\CoreFramework\Generic\UnsupportedOperationException;
27 use Org\Mxchange\CoreFramework\Handler\Handleable;
28 use Org\Mxchange\CoreFramework\Handler\Stream\IoHandler;
29 use Org\Mxchange\CoreFramework\Helper\Helper;
30 use Org\Mxchange\CoreFramework\Index\Indexable;
31 use Org\Mxchange\CoreFramework\Lists\Listable;
32 use Org\Mxchange\CoreFramework\Loader\ClassLoader;
33 use Org\Mxchange\CoreFramework\Manager\ManageableApplication;
34 use Org\Mxchange\CoreFramework\Middleware\Compressor\CompressorChannel;
35 use Org\Mxchange\CoreFramework\Middleware\Debug\DebugMiddleware;
36 use Org\Mxchange\CoreFramework\Parser\Parseable;
37 use Org\Mxchange\CoreFramework\Registry\Register;
38 use Org\Mxchange\CoreFramework\Registry\Registry;
39 use Org\Mxchange\CoreFramework\Resolver\Resolver;
40 use Org\Mxchange\CoreFramework\Result\Database\CachedDatabaseResult;
41 use Org\Mxchange\CoreFramework\Result\Search\SearchableResult;
42 use Org\Mxchange\CoreFramework\Stacker\Stackable;
43 use Org\Mxchange\CoreFramework\State\Stateable;
44 use Org\Mxchange\CoreFramework\Stream\Input\InputStream;
45 use Org\Mxchange\CoreFramework\Stream\Output\OutputStreamer;
46 use Org\Mxchange\CoreFramework\Stream\Output\OutputStream;
47 use Org\Mxchange\CoreFramework\Template\CompileableTemplate;
48 use Org\Mxchange\CoreFramework\User\ManageableAccount;
49 use Org\Mxchange\CoreFramework\Visitor\Visitor;
53 use \InvalidArgumentException;
59 * The simulator system class is the super class of all other classes. This
60 * class handles saving of games etc.
62 * @author Roland Haeder <webmaster@shipsimu.org>
64 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
65 * @license GNU GPL 3.0 or any newer version
66 * @link http://www.shipsimu.org
68 * This program is free software: you can redistribute it and/or modify
69 * it under the terms of the GNU General Public License as published by
70 * the Free Software Foundation, either version 3 of the License, or
71 * (at your option) any later version.
73 * This program is distributed in the hope that it will be useful,
74 * but WITHOUT ANY WARRANTY; without even the implied warranty of
75 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
76 * GNU General Public License for more details.
78 * You should have received a copy of the GNU General Public License
79 * along with this program. If not, see <http://www.gnu.org/licenses/>.
81 abstract class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
83 * Length of output from hash()
85 private static $hashLength = NULL;
90 private $realClass = 'BaseFrameworkSystem';
93 * Search criteria instance
95 private $searchInstance = NULL;
98 * Update criteria instance
100 private $updateInstance = NULL;
103 * The file I/O instance for the template loader
105 private $fileIoInstance = NULL;
110 private $resolverInstance = NULL;
113 * Template engine instance
115 private $templateInstance = NULL;
118 * Database result instance
120 private $resultInstance = NULL;
123 * Instance for user class
125 private $userInstance = NULL;
128 * A controller instance
130 private $controllerInstance = NULL;
135 private $rngInstance = NULL;
138 * Instance of a crypto helper
140 private $cryptoInstance = NULL;
143 * Instance of an Iterator class
145 private $iteratorInstance = NULL;
148 * Instance of the list
150 private $listInstance = NULL;
155 private $menuInstance = NULL;
158 * Instance of the image
160 private $imageInstance = NULL;
163 * Instance of the stacker
165 private $stackInstance = NULL;
168 * A Compressor instance
170 private $compressorInstance = NULL;
173 * A Parseable instance
175 private $parserInstance = NULL;
178 * A database wrapper instance
180 private $databaseInstance = NULL;
183 * A helper instance for the form
185 private $helperInstance = NULL;
188 * An instance of a Source class
190 private $sourceInstance = NULL;
193 * An instance of a UrlSource class
195 private $urlSourceInstance = NULL;
198 * An instance of a InputStream class
200 private $inputStreamInstance = NULL;
203 * An instance of a OutputStream class
205 private $outputStreamInstance = NULL;
210 private $handlerInstance = NULL;
213 * Visitor handler instance
215 private $visitorInstance = NULL;
218 * An instance of a database wrapper class
220 private $wrapperInstance = NULL;
223 * An instance of a file I/O pointer class (not handler)
225 private $pointerInstance = NULL;
228 * An instance of an Indexable class
230 private $indexInstance = NULL;
233 * An instance of a Block class
235 private $blockInstance = NULL;
240 private $minableInstance = NULL;
243 * A FrameworkDirectory instance
245 private $directoryInstance = NULL;
248 * An instance of a communicator
250 private $communicatorInstance = NULL;
253 * The concrete output instance
255 private $outputInstance = NULL;
260 private $stateInstance = NULL;
263 * Registry instance (implementing Register)
265 private $registryInstance = NULL;
270 private $callbackInstance = NULL;
273 * Thousands separator
275 private $thousands = '.'; // German
280 private $decimals = ','; // German
285 private $socketResource = false;
288 * Regular expression to use for validation
290 private $regularExpression = '';
295 private $packageData = array();
300 private $genericArray = array();
305 private $commandName = '';
310 private $controllerName = '';
313 * Array with bitmasks and such for pack/unpack methods to support both
314 * 32-bit and 64-bit systems
316 private $packingData = array(
319 'left' => 0xffff0000,
320 'right' => 0x0000ffff,
326 'left' => 0xffffffff00000000,
327 'right' => 0x00000000ffffffff,
334 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
336 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
338 private $archArrayElement = false;
340 /***********************
341 * Exception codes.... *
342 ***********************/
344 // @todo Try to clean these constants up
345 const EXCEPTION_IS_NULL_POINTER = 0x001;
346 const EXCEPTION_IS_NO_OBJECT = 0x002;
347 const EXCEPTION_IS_NO_ARRAY = 0x003;
348 const EXCEPTION_MISSING_METHOD = 0x004;
349 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
350 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
351 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
352 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
353 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
354 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
355 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
356 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
357 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
358 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
359 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
360 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
361 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
362 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
363 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
364 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
365 const EXCEPTION_PATH_NOT_FOUND = 0x015;
366 const EXCEPTION_INVALID_PATH_NAME = 0x016;
367 const EXCEPTION_READ_PROTECED_PATH = 0x017;
368 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
369 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
370 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
371 const EXCEPTION_INVALID_RESOURCE = 0x01b;
372 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
373 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
374 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
375 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
376 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
377 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
378 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
379 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
380 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
381 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
382 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
383 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
384 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
385 const EXCEPTION_INVALID_STRING = 0x029;
386 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
387 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
388 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
389 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
390 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
391 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
392 const EXCEPTION_MISSING_ELEMENT = 0x030;
393 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
394 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
395 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
396 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
397 const EXCEPTION_FATAL_ERROR = 0x035;
398 const EXCEPTION_FILE_NOT_FOUND = 0x036;
399 const EXCEPTION_ASSERTION_FAILED = 0x037;
400 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
401 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
402 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
403 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
404 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
405 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
406 const EXCEPTION_INVALID_SOCKET = 0x03e;
409 * Hexadecimal->Decimal translation array
411 private static $hexdec = array(
431 * Decimal->hexadecimal translation array
433 private static $dechex = array(
453 * Startup time in miliseconds
455 private static $startupTime = 0;
458 * Protected super constructor
460 * @param $className Name of the class
463 protected function __construct ($className) {
465 $this->setRealClass($className);
467 // Set configuration instance if no registry ...
468 if (!$this instanceof Register) {
469 // ... because registries doesn't need to be configured
470 $this->setConfigInstance(FrameworkBootstrap::getConfigurationInstance());
473 // Is the startup time set? (0 cannot be true anymore)
474 if (self::$startupTime == 0) {
476 self::$startupTime = microtime(true);
480 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
484 * Destructor for all classes. You should not call this method on your own.
488 public function __destruct () {
489 // Flush any updated entries to the database
490 $this->flushPendingUpdates();
492 // Is this object already destroyed?
493 if ($this->__toString() != 'DestructedObject') {
494 // Destroy all informations about this class but keep some text about it alive
495 $this->setRealClass('DestructedObject');
496 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
497 // Already destructed object
498 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('The object <span class="object_name">%s</span> is already destroyed.',
502 // Do not call this twice
503 trigger_error(__METHOD__ . ': Called twice.');
509 * The __call() method where all non-implemented methods end up
511 * @param $methodName Name of the missing method
512 * @args $args Arguments passed to the method
515 public final function __call ($methodName, $args) {
516 return self::__callStatic($methodName, $args);
520 * The __callStatic() method where all non-implemented static methods end up
522 * @param $methodName Name of the missing method
523 * @args $args Arguments passed to the method
526 public static final function __callStatic ($methodName, $args) {
528 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
530 // Init argument string
533 // Is it NULL, empty or an array?
534 if (is_null($args)) {
536 $argsString = 'NULL';
537 } elseif (is_array($args)) {
541 // Some arguments are there
542 foreach ($args as $arg) {
543 // Add data about the argument
544 $argsString .= gettype($arg) . ':';
547 // Found a NULL argument
548 $argsString .= 'NULL';
549 } elseif (is_string($arg)) {
550 // Add length for strings
551 $argsString .= strlen($arg);
552 } elseif ((is_int($arg)) || (is_float($arg))) {
555 } elseif (is_array($arg)) {
556 // .. or size if array
557 $argsString .= count($arg);
558 } elseif (is_object($arg)) {
560 $reflection = new ReflectionClass($arg);
562 // Is an other object, maybe no __toString() available
563 $argsString .= $reflection->getName();
564 } elseif ($arg === true) {
565 // ... is boolean 'true'
566 $argsString .= 'true';
567 } elseif ($arg === false) {
568 // ... is boolean 'false'
569 $argsString .= 'false';
572 // Comma for next one
577 if (substr($argsString, -2, 1) == ',') {
578 $argsString = substr($argsString, 0, -2);
584 // Invalid arguments!
585 $argsString = '!INVALID:' . gettype($args) . '!';
588 // Output stub message
589 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
590 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s]: Stub! Args: %s',
600 * Getter for $realClass
602 * @return $realClass The name of the real class (not BaseFrameworkSystem)
604 public function __toString () {
605 return $this->realClass;
609 * Magic method to catch setting of missing but set class fields/attributes
611 * @param $name Name of the field/attribute
612 * @param $value Value to store
615 public final function __set ($name, $value) {
616 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
619 print_r($value, true)
624 * Magic method to catch getting of missing fields/attributes
626 * @param $name Name of the field/attribute
629 public final function __get ($name) {
630 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
636 * Magic method to catch unsetting of missing fields/attributes
638 * @param $name Name of the field/attribute
641 public final function __unset ($name) {
642 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
648 * Magic method to catch object serialization
650 * @return $unsupported Unsupported method
651 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
653 public final function __sleep () {
654 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
658 * Magic method to catch object deserialization
660 * @return $unsupported Unsupported method
661 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
663 public final function __wakeup () {
664 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
668 * Magic method to catch calls when an object instance is called
670 * @return $unsupported Unsupported method
671 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
673 public final function __invoke () {
674 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
678 * Setter for the real class name
680 * @param $realClass Class name (string)
683 public final function setRealClass ($realClass) {
685 $this->realClass = (string) $realClass;
689 * Setter for database result instance
691 * @param $resultInstance An instance of a database result class
693 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
695 protected final function setResultInstance (SearchableResult $resultInstance) {
696 $this->resultInstance = $resultInstance;
700 * Getter for database result instance
702 * @return $resultInstance An instance of a database result class
704 public final function getResultInstance () {
705 return $this->resultInstance;
709 * Setter for template engine instances
711 * @param $templateInstance An instance of a template engine class
714 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
715 $this->templateInstance = $templateInstance;
719 * Getter for template engine instances
721 * @return $templateInstance An instance of a template engine class
723 protected final function getTemplateInstance () {
724 return $this->templateInstance;
728 * Setter for search instance
730 * @param $searchInstance Searchable criteria instance
733 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
734 $this->searchInstance = $searchInstance;
738 * Getter for search instance
740 * @return $searchInstance Searchable criteria instance
742 public final function getSearchInstance () {
743 return $this->searchInstance;
747 * Setter for update instance
749 * @param $updateInstance An instance of a LocalUpdateCriteria clase
752 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
753 $this->updateInstance = $updateInstance;
757 * Getter for update instance
759 * @return $updateInstance Updateable criteria instance
761 public final function getUpdateInstance () {
762 return $this->updateInstance;
766 * Setter for resolver instance
768 * @param $resolverInstance Instance of a command resolver class
771 public final function setResolverInstance (Resolver $resolverInstance) {
772 $this->resolverInstance = $resolverInstance;
776 * Getter for resolver instance
778 * @return $resolverInstance Instance of a command resolver class
780 public final function getResolverInstance () {
781 return $this->resolverInstance;
785 * Setter for language instance
787 * @param $configInstance The configuration instance which shall
788 * be FrameworkConfiguration
791 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
792 Registry::getRegistry()->addInstance('config', $configInstance);
796 * Getter for configuration instance
798 * @return $configInstance Configuration instance
800 public final function getConfigInstance () {
801 $configInstance = Registry::getRegistry()->getInstance('config');
802 return $configInstance;
806 * Setter for debug instance
808 * @param $debugInstance The instance for debug output class
811 public final function setDebugInstance (DebugMiddleware $debugInstance) {
812 Registry::getRegistry()->addInstance('debug', $debugInstance);
816 * Getter for debug instance
818 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
820 public final function getDebugInstance () {
821 // Get debug instance
822 $debugInstance = Registry::getRegistry()->getInstance('debug');
825 return $debugInstance;
829 * Setter for web output instance
831 * @param $webInstance The instance for web output class
834 public final function setWebOutputInstance (OutputStreamer $webInstance) {
835 Registry::getRegistry()->addInstance('web_output', $webInstance);
839 * Getter for web output instance
841 * @return $webOutputInstance - Instance to class WebOutput
843 public final function getWebOutputInstance () {
844 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
845 return $webOutputInstance;
849 * Setter for database instance
851 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
854 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
855 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
859 * Getter for database layer
861 * @return $databaseInstance The database layer instance
863 public final function getDatabaseInstance () {
865 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
868 return $databaseInstance;
872 * Setter for compressor channel
874 * @param $compressorInstance An instance of CompressorChannel
877 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
878 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
882 * Getter for compressor channel
884 * @return $compressorInstance The compressor channel
886 public final function getCompressorChannel () {
887 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
888 return $compressorInstance;
892 * Protected getter for a manageable application helper class
894 * @return $applicationInstance An instance of a manageable application helper class
896 protected final function getApplicationInstance () {
897 $applicationInstance = Registry::getRegistry()->getInstance('app');
898 return $applicationInstance;
902 * Setter for a manageable application helper class
904 * @param $applicationInstance An instance of a manageable application helper class
907 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
908 Registry::getRegistry()->addInstance('application', $applicationInstance);
912 * Private getter for language instance
914 * @return $langInstance An instance to the language sub-system
916 protected final function getLanguageInstance () {
917 $langInstance = Registry::getRegistry()->getInstance('language');
918 return $langInstance;
922 * Setter for language instance
924 * @param $langInstance An instance to the language sub-system
926 * @see LanguageSystem
928 public final function setLanguageInstance (ManageableLanguage $langInstance) {
929 Registry::getRegistry()->addInstance('language', $langInstance);
933 * Private getter for file IO instance
935 * @return $fileIoInstance An instance to the file I/O sub-system
937 protected final function getFileIoInstance () {
938 return $this->fileIoInstance;
942 * Setter for file I/O instance
944 * @param $fileIoInstance An instance to the file I/O sub-system
947 public final function setFileIoInstance (IoHandler $fileIoInstance) {
948 $this->fileIoInstance = $fileIoInstance;
952 * Protected setter for user instance
954 * @param $userInstance An instance of a user class
957 protected final function setUserInstance (ManageableAccount $userInstance) {
958 $this->userInstance = $userInstance;
962 * Getter for user instance
964 * @return $userInstance An instance of a user class
966 public final function getUserInstance () {
967 return $this->userInstance;
971 * Setter for controller instance (this surely breaks a bit the MVC patterm)
973 * @param $controllerInstance An instance of the controller
976 public final function setControllerInstance (Controller $controllerInstance) {
977 $this->controllerInstance = $controllerInstance;
981 * Getter for controller instance (this surely breaks a bit the MVC patterm)
983 * @return $controllerInstance An instance of the controller
985 public final function getControllerInstance () {
986 return $this->controllerInstance;
990 * Setter for RNG instance
992 * @param $rngInstance An instance of a random number generator (RNG)
995 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
996 $this->rngInstance = $rngInstance;
1000 * Getter for RNG instance
1002 * @return $rngInstance An instance of a random number generator (RNG)
1004 public final function getRngInstance () {
1005 return $this->rngInstance;
1009 * Setter for Cryptable instance
1011 * @param $cryptoInstance An instance of a Cryptable class
1014 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1015 $this->cryptoInstance = $cryptoInstance;
1019 * Getter for Cryptable instance
1021 * @return $cryptoInstance An instance of a Cryptable class
1023 public final function getCryptoInstance () {
1024 return $this->cryptoInstance;
1028 * Setter for the list instance
1030 * @param $listInstance A list of Listable
1033 protected final function setListInstance (Listable $listInstance) {
1034 $this->listInstance = $listInstance;
1038 * Getter for the list instance
1040 * @return $listInstance A list of Listable
1042 protected final function getListInstance () {
1043 return $this->listInstance;
1047 * Setter for the menu instance
1049 * @param $menuInstance A RenderableMenu instance
1052 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1053 $this->menuInstance = $menuInstance;
1057 * Getter for the menu instance
1059 * @return $menuInstance A RenderableMenu instance
1061 protected final function getMenuInstance () {
1062 return $this->menuInstance;
1066 * Setter for image instance
1068 * @param $imageInstance An instance of an image
1071 public final function setImageInstance (BaseImage $imageInstance) {
1072 $this->imageInstance = $imageInstance;
1076 * Getter for image instance
1078 * @return $imageInstance An instance of an image
1080 public final function getImageInstance () {
1081 return $this->imageInstance;
1085 * Setter for stacker instance
1087 * @param $stackInstance An instance of an stacker
1090 public final function setStackInstance (Stackable $stackInstance) {
1091 $this->stackInstance = $stackInstance;
1095 * Getter for stacker instance
1097 * @return $stackInstance An instance of an stacker
1099 public final function getStackInstance () {
1100 return $this->stackInstance;
1104 * Setter for compressor instance
1106 * @param $compressorInstance An instance of an compressor
1109 public final function setCompressorInstance (Compressor $compressorInstance) {
1110 $this->compressorInstance = $compressorInstance;
1114 * Getter for compressor instance
1116 * @return $compressorInstance An instance of an compressor
1118 public final function getCompressorInstance () {
1119 return $this->compressorInstance;
1123 * Setter for Parseable instance
1125 * @param $parserInstance An instance of an Parseable
1128 public final function setParserInstance (Parseable $parserInstance) {
1129 $this->parserInstance = $parserInstance;
1133 * Getter for Parseable instance
1135 * @return $parserInstance An instance of an Parseable
1137 public final function getParserInstance () {
1138 return $this->parserInstance;
1142 * Setter for DatabaseWrapper instance
1144 * @param $wrapperInstance An instance of an DatabaseWrapper
1147 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1148 $this->wrapperInstance = $wrapperInstance;
1152 * Getter for DatabaseWrapper instance
1154 * @return $wrapperInstance An instance of an DatabaseWrapper
1156 public final function getWrapperInstance () {
1157 return $this->wrapperInstance;
1161 * Setter for socket resource
1163 * @param $socketResource A valid socket resource
1166 public final function setSocketResource ($socketResource) {
1167 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1168 $this->socketResource = $socketResource;
1172 * Getter for socket resource
1174 * @return $socketResource A valid socket resource
1176 public final function getSocketResource () {
1177 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1178 return $this->socketResource;
1182 * Setter for regular expression
1184 * @param $regularExpression A valid regular expression
1187 public final function setRegularExpression ($regularExpression) {
1188 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1189 $this->regularExpression = $regularExpression;
1193 * Getter for regular expression
1195 * @return $regularExpression A valid regular expression
1197 public final function getRegularExpression () {
1198 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1199 return $this->regularExpression;
1203 * Setter for helper instance
1205 * @param $helperInstance An instance of a helper class
1208 protected final function setHelperInstance (Helper $helperInstance) {
1209 $this->helperInstance = $helperInstance;
1213 * Getter for helper instance
1215 * @return $helperInstance An instance of a helper class
1217 public final function getHelperInstance () {
1218 return $this->helperInstance;
1222 * Setter for a Source instance
1224 * @param $sourceInstance An instance of a Source class
1227 protected final function setSourceInstance (Source $sourceInstance) {
1228 $this->sourceInstance = $sourceInstance;
1232 * Getter for a Source instance
1234 * @return $sourceInstance An instance of a Source class
1236 protected final function getSourceInstance () {
1237 return $this->sourceInstance;
1241 * Setter for a UrlSource instance
1243 * @param $sourceInstance An instance of a UrlSource class
1246 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1247 $this->urlSourceInstance = $urlSourceInstance;
1251 * Getter for a UrlSource instance
1253 * @return $urlSourceInstance An instance of a UrlSource class
1255 protected final function getUrlSourceInstance () {
1256 return $this->urlSourceInstance;
1260 * Getter for a InputStream instance
1262 * @param $inputStreamInstance The InputStream instance
1264 protected final function getInputStreamInstance () {
1265 return $this->inputStreamInstance;
1269 * Setter for a InputStream instance
1271 * @param $inputStreamInstance The InputStream instance
1274 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1275 $this->inputStreamInstance = $inputStreamInstance;
1279 * Getter for a OutputStream instance
1281 * @param $outputStreamInstance The OutputStream instance
1283 protected final function getOutputStreamInstance () {
1284 return $this->outputStreamInstance;
1288 * Setter for a OutputStream instance
1290 * @param $outputStreamInstance The OutputStream instance
1293 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1294 $this->outputStreamInstance = $outputStreamInstance;
1298 * Setter for handler instance
1300 * @param $handlerInstance An instance of a Handleable class
1303 protected final function setHandlerInstance (Handleable $handlerInstance) {
1304 $this->handlerInstance = $handlerInstance;
1308 * Getter for handler instance
1310 * @return $handlerInstance A Handleable instance
1312 protected final function getHandlerInstance () {
1313 return $this->handlerInstance;
1317 * Setter for visitor instance
1319 * @param $visitorInstance A Visitor instance
1322 protected final function setVisitorInstance (Visitor $visitorInstance) {
1323 $this->visitorInstance = $visitorInstance;
1327 * Getter for visitor instance
1329 * @return $visitorInstance A Visitor instance
1331 protected final function getVisitorInstance () {
1332 return $this->visitorInstance;
1336 * Setter for raw package Data
1338 * @param $packageData Raw package Data
1341 public final function setPackageData (array $packageData) {
1342 $this->packageData = $packageData;
1346 * Getter for raw package Data
1348 * @return $packageData Raw package Data
1350 public function getPackageData () {
1351 return $this->packageData;
1356 * Setter for Iterator instance
1358 * @param $iteratorInstance An instance of an Iterator
1361 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1362 $this->iteratorInstance = $iteratorInstance;
1366 * Getter for Iterator instance
1368 * @return $iteratorInstance An instance of an Iterator
1370 public final function getIteratorInstance () {
1371 return $this->iteratorInstance;
1375 * Setter for FilePointer instance
1377 * @param $pointerInstance An instance of an FilePointer class
1380 protected final function setPointerInstance (FilePointer $pointerInstance) {
1381 $this->pointerInstance = $pointerInstance;
1385 * Getter for FilePointer instance
1387 * @return $pointerInstance An instance of an FilePointer class
1389 public final function getPointerInstance () {
1390 return $this->pointerInstance;
1394 * Unsets pointer instance which triggers a call of __destruct() if the
1395 * instance is still there. This is surely not fatal on already "closed"
1396 * file pointer instances.
1398 * I don't want to mess around with above setter by giving it a default
1399 * value NULL as setter should always explicitly only set (existing) object
1400 * instances and NULL is NULL.
1404 protected final function unsetPointerInstance () {
1405 // Simply it to NULL
1406 $this->pointerInstance = NULL;
1410 * Setter for Indexable instance
1412 * @param $indexInstance An instance of an Indexable class
1415 protected final function setIndexInstance (Indexable $indexInstance) {
1416 $this->indexInstance = $indexInstance;
1420 * Getter for Indexable instance
1422 * @return $indexInstance An instance of an Indexable class
1424 public final function getIndexInstance () {
1425 return $this->indexInstance;
1429 * Setter for Block instance
1431 * @param $blockInstance An instance of an Block class
1434 protected final function setBlockInstance (Block $blockInstance) {
1435 $this->blockInstance = $blockInstance;
1439 * Getter for Block instance
1441 * @return $blockInstance An instance of an Block class
1443 public final function getBlockInstance () {
1444 return $this->blockInstance;
1448 * Setter for Minable instance
1450 * @param $minableInstance A Minable instance
1453 protected final function setMinableInstance (Minable $minableInstance) {
1454 $this->minableInstance = $minableInstance;
1458 * Getter for minable instance
1460 * @return $minableInstance A Minable instance
1462 protected final function getMinableInstance () {
1463 return $this->minableInstance;
1467 * Setter for FrameworkDirectory instance
1469 * @param $directoryInstance A FrameworkDirectory instance
1472 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1473 $this->directoryInstance = $directoryInstance;
1477 * Getter for FrameworkDirectory instance
1479 * @return $directoryInstance A FrameworkDirectory instance
1481 protected final function getDirectoryInstance () {
1482 return $this->directoryInstance;
1486 * Getter for communicator instance
1488 * @return $communicatorInstance An instance of a Communicator class
1490 public final function getCommunicatorInstance () {
1491 return $this->communicatorInstance;
1495 * Setter for communicator instance
1497 * @param $communicatorInstance An instance of a Communicator class
1500 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1501 $this->communicatorInstance = $communicatorInstance;
1505 * Setter for state instance
1507 * @param $stateInstance A Stateable instance
1510 public final function setStateInstance (Stateable $stateInstance) {
1511 $this->stateInstance = $stateInstance;
1515 * Getter for state instance
1517 * @return $stateInstance A Stateable instance
1519 public final function getStateInstance () {
1520 return $this->stateInstance;
1524 * Setter for output instance
1526 * @param $outputInstance The debug output instance
1529 public final function setOutputInstance (OutputStreamer $outputInstance) {
1530 $this->outputInstance = $outputInstance;
1534 * Getter for output instance
1536 * @return $outputInstance The debug output instance
1538 public final function getOutputInstance () {
1539 return $this->outputInstance;
1543 * Setter for registry instance
1545 * @param $registryInstance An instance of a Register class
1548 protected final function setRegistryInstance (Register $registryInstance) {
1549 $this->registryInstance = $registryInstance;
1553 * Getter for registry instance
1555 * @return $registryInstance The debug registry instance
1557 public final function getRegistryInstance () {
1558 return $this->registryInstance;
1562 * Setter for call-back instance
1564 * @param $callbackInstance An instance of a FrameworkInterface class
1567 public final function setCallbackInstance (FrameworkInterface $callbackInstance) {
1568 $this->callbackInstance = $callbackInstance;
1572 * Getter for call-back instance
1574 * @return $callbackInstance An instance of a FrameworkInterface class
1576 protected final function getCallbackInstance () {
1577 return $this->callbackInstance;
1581 * Setter for command name
1583 * @param $commandName Last validated command name
1586 protected final function setCommandName ($commandName) {
1587 $this->commandName = $commandName;
1591 * Getter for command name
1593 * @return $commandName Last validated command name
1595 protected final function getCommandName () {
1596 return $this->commandName;
1600 * Setter for controller name
1602 * @param $controllerName Last validated controller name
1605 protected final function setControllerName ($controllerName) {
1606 $this->controllerName = $controllerName;
1610 * Getter for controller name
1612 * @return $controllerName Last validated controller name
1614 protected final function getControllerName () {
1615 return $this->controllerName;
1619 * Checks whether an object equals this object. You should overwrite this
1620 * method to implement own equality checks
1622 * @param $objectInstance An instance of a FrameworkInterface object
1623 * @return $equals Whether both objects equals
1625 public function equals (FrameworkInterface $objectInstance) {
1628 $this->__toString() == $objectInstance->__toString()
1630 $this->hashCode() == $objectInstance->hashCode()
1633 // Return the result
1638 * Generates a generic hash code of this class. You should really overwrite
1639 * this method with your own hash code generator code. But keep KISS in mind.
1641 * @return $hashCode A generic hash code respresenting this whole class
1643 public function hashCode () {
1645 return crc32($this->__toString());
1649 * Formats computer generated price values into human-understandable formats
1650 * with thousand and decimal separators.
1652 * @param $value The in computer format value for a price
1653 * @param $currency The currency symbol (use HTML-valid characters!)
1654 * @param $decNum Number of decimals after commata
1655 * @return $price The for the current language formated price string
1656 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1657 * thousands separator
1660 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1661 // Are all required attriutes set?
1662 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1663 // Throw an exception
1664 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1668 $value = (float) $value;
1670 // Reformat the US number
1671 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1673 // Return as string...
1678 * Appends a trailing slash to a string
1680 * @param $str A string (maybe) without trailing slash
1681 * @return $str A string with an auto-appended trailing slash
1683 public final function addMissingTrailingSlash ($str) {
1684 // Is there a trailing slash?
1685 if (substr($str, -1, 1) != '/') {
1689 // Return string with trailing slash
1694 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1695 * application helper instance (ApplicationHelper by default).
1697 * @param $applicationInstance An application helper instance or
1698 * null if we shall use the default
1699 * @return $templateInstance The template engine instance
1700 * @throws NullPointerException If the discovered application
1701 * instance is still null
1703 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1704 // Is the application instance set?
1705 if (is_null($applicationInstance)) {
1706 // Get the current instance
1707 $applicationInstance = Registry::getRegistry()->getInstance('app');
1710 if (is_null($applicationInstance)) {
1711 // Thrown an exception
1712 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1716 // Initialize the template engine
1717 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1719 // Return the prepared instance
1720 return $templateInstance;
1724 * Debugs this instance by putting out it's full content
1726 * @param $message Optional message to show in debug output
1729 public final function debugInstance ($message = '') {
1730 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1731 restore_error_handler();
1736 // Is a message set?
1737 if (!empty($message)) {
1738 // Construct message
1739 $content = sprintf('<div class="debug_message">
1741 </div>' . PHP_EOL, $message);
1744 // Generate the output
1745 $content .= sprintf('<pre>%s</pre>',
1748 print_r($this, true)
1754 ApplicationEntryPoint::exitApplication(sprintf('<div class="debug_header">
1757 <div class="debug_content">
1761 <div class="debug_include_list">
1764 $this->__toString(),
1766 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1771 * Replaces control characters with printable output
1773 * @param $str String with control characters
1774 * @return $str Replaced string
1776 protected function replaceControlCharacters ($str) {
1779 chr(13), '[r]', str_replace(
1780 chr(10), '[n]', str_replace(
1790 * Output a partial stub message for the caller method
1792 * @param $message An optional message to display
1795 protected function partialStub ($message = '') {
1797 $stubMessage = 'Partial Stub!';
1799 // Is the extra message given?
1800 if (!empty($message)) {
1801 // Then add it as well
1802 $stubMessage .= ' Message: ' . $message;
1805 // Debug instance is there?
1806 if (!is_null($this->getDebugInstance())) {
1807 // Output stub message
1808 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1811 trigger_error($stubMessage);
1817 * Outputs a debug backtrace and stops further script execution
1819 * @param $message An optional message to output
1820 * @param $doExit Whether exit the program (true is default)
1823 public function debugBackTrace ($message = '', $doExit = true) {
1824 // Sorry, there is no other way getting this nice backtrace
1825 if (!empty($message)) {
1827 printf('Message: %s<br />' . PHP_EOL, $message);
1831 debug_print_backtrace();
1835 if ($doExit === true) {
1841 * Creates an instance of a debugger instance
1843 * @param $className Name of the class (currently unsupported)
1844 * @param $lineNumber Line number where the call was made
1845 * @return $debugInstance An instance of a debugger class
1846 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1848 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1849 // Is the instance set?
1850 if (!Registry::getRegistry()->instanceExists('debug')) {
1851 // Init debug instance
1852 $debugInstance = NULL;
1856 // Get a debugger instance
1857 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1858 } catch (NullPointerException $e) {
1859 // Didn't work, no instance there
1860 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1863 // Empty string should be ignored and used for testing the middleware
1864 DebugMiddleware::getSelfInstance()->output('');
1866 // Set it in registry
1867 Registry::getRegistry()->addInstance('debug', $debugInstance);
1869 // Get instance from registry
1870 $debugInstance = Registry::getRegistry()->getInstance('debug');
1874 return $debugInstance;
1878 * Simple output of a message with line-break
1880 * @param $message Message to output
1883 public function outputLine ($message) {
1885 print($message . PHP_EOL);
1889 * Outputs a debug message whether to debug instance (should be set!) or
1890 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1891 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1893 * @param $message Message we shall send out...
1894 * @param $doPrint Whether print or die here (default: print)
1895 * @paran $stripTags Whether to strip tags (default: false)
1898 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1899 // Set debug instance to NULL
1900 $debugInstance = NULL;
1903 $backtrace = debug_backtrace(!DEBUG_BACKTRACE_PROVIDE_OBJECT);
1905 // Is function partialStub/__callStatic ?
1906 if (in_array($backtrace[1]['function'], array('partialStub', '__call', '__callStatic'))) {
1907 // Prepend class::function:line from 3rd element
1908 $message = sprintf('[%s::%s:%d]: %s',
1909 $backtrace[2]['class'],
1910 $backtrace[2]['function'],
1911 (isset($backtrace[2]['line']) ? $backtrace[2]['line'] : '0'),
1915 // Prepend class::function:line from 2nd element
1916 $message = sprintf('[%s::%s:%d]: %s',
1917 $backtrace[1]['class'],
1918 $backtrace[1]['function'],
1919 (isset($backtrace[1]['line']) ? $backtrace[1]['line'] : '0'),
1926 // Get debug instance
1927 $debugInstance = $this->getDebugInstance();
1928 } catch (NullPointerException $e) {
1929 // The debug instance is not set (yet)
1932 // Is the debug instance there?
1933 if (is_object($debugInstance)) {
1934 // Use debug output handler
1935 $debugInstance->output($message, $stripTags);
1937 if ($doPrint === false) {
1938 // Die here if not printed
1942 // Are debug times enabled?
1943 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1945 $message = $this->getPrintableExecutionTime() . $message;
1949 if ($doPrint === true) {
1951 $this->outputLine($message);
1960 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1962 * @param $str The string, what ever it is needs to be converted
1963 * @return $className Generated class name
1965 public static final function convertToClassName ($str) {
1969 // Convert all dashes in underscores
1970 $str = self::convertDashesToUnderscores($str);
1972 // Now use that underscores to get classname parts for hungarian style
1973 foreach (explode('_', $str) as $strPart) {
1974 // Make the class name part lower case and first upper case
1975 $className .= ucfirst(strtolower($strPart));
1978 // Return class name
1983 * Converts dashes to underscores, e.g. useable for configuration entries
1985 * @param $str The string with maybe dashes inside
1986 * @return $str The converted string with no dashed, but underscores
1987 * @throws NullPointerException If $str is null
1988 * @throws InvalidArgumentException If $str is empty
1990 public static function convertDashesToUnderscores ($str) {
1992 if (is_null($str)) {
1994 throw new NullPointerException($this, BaseFrameworkSystem::EXCEPTION_IS_NULL_POINTER);
1995 } elseif (!is_string($str)) {
1997 throw new InvalidArgumentException(sprintf('str[]=%s is not a string', gettype($str)), self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
1998 } elseif ((is_string($str)) && (empty($str))) {
2000 throw new InvalidArgumentException('str is empty', self::EXCEPTION_CONFIG_KEY_IS_EMPTY);
2004 $str = str_replace('-', '_', $str);
2006 // Return converted string
2011 * Marks up the code by adding e.g. line numbers
2013 * @param $phpCode Unmarked PHP code
2014 * @return $markedCode Marked PHP code
2016 public function markupCode ($phpCode) {
2021 $errorArray = error_get_last();
2023 // Init the code with error message
2024 if (is_array($errorArray)) {
2026 $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>',
2027 basename($errorArray['file']),
2028 $errorArray['line'],
2029 $errorArray['message'],
2034 // Add line number to the code
2035 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2037 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2039 htmlentities($code, ENT_QUOTES)
2048 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2049 * beatiful for web-based front-ends. If null is given a message id
2050 * null_timestamp will be resolved and returned.
2052 * @param $timestamp Timestamp to prepare (filter) for display
2053 * @return $readable A readable timestamp
2055 public function doFilterFormatTimestamp ($timestamp) {
2056 // Default value to return
2059 // Is the timestamp null?
2060 if (is_null($timestamp)) {
2061 // Get a message string
2062 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2064 switch ($this->getLanguageInstance()->getLanguageCode()) {
2065 case 'de': // German format is a bit different to default
2066 // Split the GMT stamp up
2067 $dateTime = explode(' ', $timestamp );
2068 $dateArray = explode('-', $dateTime[0]);
2069 $timeArray = explode(':', $dateTime[1]);
2071 // Construct the timestamp
2072 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2082 default: // Default is pass-through
2083 $readable = $timestamp;
2093 * Filter a given number into a localized number
2095 * @param $value The raw value from e.g. database
2096 * @return $localized Localized value
2098 public function doFilterFormatNumber ($value) {
2099 // Generate it from config and localize dependencies
2100 switch ($this->getLanguageInstance()->getLanguageCode()) {
2101 case 'de': // German format is a bit different to default
2102 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2105 default: // US, etc.
2106 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2115 * "Getter" for databse entry
2117 * @return $entry An array with database entries
2118 * @throws NullPointerException If the database result is not found
2119 * @throws InvalidDatabaseResultException If the database result is invalid
2121 protected final function getDatabaseEntry () {
2122 // Is there an instance?
2123 if (!$this->getResultInstance() instanceof SearchableResult) {
2124 // Throw an exception here
2125 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2129 $this->getResultInstance()->rewind();
2131 // Do we have an entry?
2132 if ($this->getResultInstance()->valid() === false) {
2133 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2134 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2138 $this->getResultInstance()->next();
2141 $entry = $this->getResultInstance()->current();
2148 * Getter for field name
2150 * @param $fieldName Field name which we shall get
2151 * @return $fieldValue Field value from the user
2152 * @throws NullPointerException If the result instance is null
2154 public final function getField ($fieldName) {
2155 // Default field value
2158 // Get result instance
2159 $resultInstance = $this->getResultInstance();
2161 // Is this instance null?
2162 if (is_null($resultInstance)) {
2163 // Then the user instance is no longer valid (expired cookies?)
2164 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2167 // Get current array
2168 $fieldArray = $resultInstance->current();
2169 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2171 // Convert dashes to underscore
2172 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2174 // Does the field exist?
2175 if ($this->isFieldSet($fieldName)) {
2177 $fieldValue = $fieldArray[$fieldName2];
2178 } elseif (defined('DEVELOPER')) {
2179 // Missing field entry, may require debugging
2180 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2182 // Missing field entry, may require debugging
2183 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2191 * Checks if given field is set
2193 * @param $fieldName Field name to check
2194 * @return $isSet Whether the given field name is set
2195 * @throws NullPointerException If the result instance is null
2197 public function isFieldSet ($fieldName) {
2198 // Get result instance
2199 $resultInstance = $this->getResultInstance();
2201 // Is this instance null?
2202 if (is_null($resultInstance)) {
2203 // Then the user instance is no longer valid (expired cookies?)
2204 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2207 // Get current array
2208 $fieldArray = $resultInstance->current();
2209 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2211 // Convert dashes to underscore
2212 $fieldName = self::convertDashesToUnderscores($fieldName);
2215 $isSet = isset($fieldArray[$fieldName]);
2222 * Flushs all pending updates to the database layer
2226 public function flushPendingUpdates () {
2227 // Get result instance
2228 $resultInstance = $this->getResultInstance();
2230 // Do we have data to update?
2231 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2232 // Get wrapper class name config entry
2233 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2235 // Create object instance
2236 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2238 // Yes, then send the whole result to the database layer
2239 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2244 * Outputs a deprecation warning to the developer.
2246 * @param $message The message we shall output to the developer
2248 * @todo Write a logging mechanism for productive mode
2250 public function deprecationWarning ($message) {
2251 // Is developer mode active?
2252 if (defined('DEVELOPER')) {
2253 // Debug instance is there?
2254 if (!is_null($this->getDebugInstance())) {
2255 // Output stub message
2256 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2259 trigger_error($message . "<br />\n");
2263 // @TODO Finish this part!
2264 $this->partialStub('Developer mode inactive. Message:' . $message);
2269 * Checks whether the given PHP extension is loaded
2271 * @param $phpExtension The PHP extension we shall check
2272 * @return $isLoaded Whether the PHP extension is loaded
2274 public final function isPhpExtensionLoaded ($phpExtension) {
2276 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2283 * "Getter" as a time() replacement but with milliseconds. You should use this
2284 * method instead of the encapsulated getimeofday() function.
2286 * @return $milliTime Timestamp with milliseconds
2288 public function getMilliTime () {
2289 // Get the time of day as float
2290 $milliTime = gettimeofday(true);
2297 * Idles (sleeps) for given milliseconds
2299 * @return $hasSlept Whether it goes fine
2301 public function idle ($milliSeconds) {
2302 // Sleep is fine by default
2305 // Idle so long with found function
2306 if (function_exists('time_sleep_until')) {
2307 // Get current time and add idle time
2308 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2310 // New PHP 5.1.0 function found, ignore errors
2311 $hasSlept = @time_sleep_until($sleepUntil);
2314 * My Sun station doesn't have that function even with latest PHP
2317 usleep($milliSeconds * 1000);
2324 * Converts a hexadecimal string, even with negative sign as first string to
2325 * a decimal number using BC functions.
2327 * This work is based on comment #86673 on php.net documentation page at:
2328 * <http://de.php.net/manual/en/function.dechex.php#86673>
2330 * @param $hex Hexadecimal string
2331 * @return $dec Decimal number
2333 protected function hex2dec ($hex) {
2334 // Convert to all lower-case
2335 $hex = strtolower($hex);
2337 // Detect sign (negative/positive numbers)
2339 if (substr($hex, 0, 1) == '-') {
2341 $hex = substr($hex, 1);
2344 // Decode the hexadecimal string into a decimal number
2346 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2347 $factor = self::$hexdec[substr($hex, $i, 1)];
2348 $dec = bcadd($dec, bcmul($factor, $e));
2351 // Return the decimal number
2352 return $sign . $dec;
2356 * Converts even very large decimal numbers, also signed, to a hexadecimal
2359 * This work is based on comment #97756 on php.net documentation page at:
2360 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2362 * @param $dec Decimal number, even with negative sign
2363 * @param $maxLength Optional maximum length of the string
2364 * @return $hex Hexadecimal string
2366 protected function dec2hex ($dec, $maxLength = 0) {
2367 // maxLength can be zero or devideable by 2
2368 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2370 // Detect sign (negative/positive numbers)
2377 // Encode the decimal number into a hexadecimal string
2380 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2382 } while ($dec >= 1);
2385 * Leading zeros are required for hex-decimal "numbers". In some
2386 * situations more leading zeros are wanted, so check for both
2389 if ($maxLength > 0) {
2390 // Prepend more zeros
2391 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2392 } elseif ((strlen($hex) % 2) != 0) {
2393 // Only make string's length dividable by 2
2397 // Return the hexadecimal string
2398 return $sign . $hex;
2402 * Converts a ASCII string (0 to 255) into a decimal number.
2404 * @param $asc The ASCII string to be converted
2405 * @return $dec Decimal number
2407 protected function asc2dec ($asc) {
2408 // Convert it into a hexadecimal number
2409 $hex = bin2hex($asc);
2411 // And back into a decimal number
2412 $dec = $this->hex2dec($hex);
2419 * Converts a decimal number into an ASCII string.
2421 * @param $dec Decimal number
2422 * @return $asc An ASCII string
2424 protected function dec2asc ($dec) {
2425 // First convert the number into a hexadecimal string
2426 $hex = $this->dec2hex($dec);
2428 // Then convert it into the ASCII string
2429 $asc = $this->hex2asc($hex);
2436 * Converts a hexadecimal number into an ASCII string. Negative numbers
2439 * @param $hex Hexadecimal string
2440 * @return $asc An ASCII string
2442 protected function hex2asc ($hex) {
2443 // Check for length, it must be devideable by 2
2444 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2445 assert((strlen($hex) % 2) == 0);
2449 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2450 // Get the decimal number of the chunk
2451 $part = hexdec(substr($hex, $idx, 2));
2453 // Add it to the final string
2457 // Return the final string
2462 * Checks whether the given encoded data was encoded with Base64
2464 * @param $encodedData Encoded data we shall check
2465 * @return $isBase64 Whether the encoded data is Base64
2467 protected function isBase64Encoded ($encodedData) {
2469 $isBase64 = (@base64_decode($encodedData, true) !== false);
2476 * Gets a cache key from Criteria instance
2478 * @param $criteriaInstance An instance of a Criteria class
2479 * @param $onlyKeys Only use these keys for a cache key
2480 * @return $cacheKey A cache key suitable for lookup/storage purposes
2482 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2484 $cacheKey = sprintf('%s@%s',
2485 $this->__toString(),
2486 $criteriaInstance->getCacheKey($onlyKeys)
2490 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2495 * Getter for startup time in miliseconds
2497 * @return $startupTime Startup time in miliseconds
2499 protected function getStartupTime () {
2500 return self::$startupTime;
2504 * "Getter" for a printable currently execution time in nice braces
2506 * @return $executionTime Current execution time in nice braces
2508 protected function getPrintableExecutionTime () {
2509 // Caculate the execution time
2510 $executionTime = microtime(true) - $this->getStartupTime();
2512 // Pack it in nice braces
2513 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2516 return $executionTime;
2520 * Hashes a given string with a simple but stronger hash function (no salt)
2521 * and hex-encode it.
2523 * @param $str The string to be hashed
2524 * @return $hash The hash from string $str
2526 public static final function hash ($str) {
2527 // Hash given string with (better secure) hasher
2528 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2535 * "Getter" for length of hash() output. This will be "cached" to speed up
2538 * @return $length Length of hash() output
2540 public static final function getHashLength () {
2542 if (is_null(self::$hashLength)) {
2543 // No, then hash a string and save its length.
2544 self::$hashLength = strlen(self::hash('abc123'));
2548 return self::$hashLength;
2552 * Checks whether the given number is really a number (only chars 0-9).
2554 * @param $num A string consisting only chars between 0 and 9
2555 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2556 * @param $assertMismatch Whether to assert mismatches
2557 * @return $ret The (hopefully) secured numbered value
2559 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2560 // Filter all numbers out
2561 $ret = preg_replace('/[^0123456789]/', '', $num);
2564 if ($castValue === true) {
2565 // Cast to biggest numeric type
2566 $ret = (double) $ret;
2569 // Assert only if requested
2570 if ($assertMismatch === true) {
2571 // Has the whole value changed?
2572 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2580 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2582 * @param $num A string consisting only chars between 0 and 9
2583 * @param $assertMismatch Whether to assert mismatches
2584 * @return $ret The (hopefully) secured hext-numbered value
2586 public function hexval ($num, $assertMismatch = false) {
2587 // Filter all numbers out
2588 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2590 // Assert only if requested
2591 if ($assertMismatch === true) {
2592 // Has the whole value changed?
2593 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2601 * Determines if an element is set in the generic array
2603 * @param $keyGroup Main group for the key
2604 * @param $subGroup Sub group for the key
2605 * @param $key Key to check
2606 * @param $element Element to check
2607 * @return $isset Whether the given key is set
2609 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2611 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2614 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2620 * Determines if a key is set in the generic array
2622 * @param $keyGroup Main group for the key
2623 * @param $subGroup Sub group for the key
2624 * @param $key Key to check
2625 * @return $isset Whether the given key is set
2627 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2629 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2632 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2640 * Determines if a group is set in the generic array
2642 * @param $keyGroup Main group
2643 * @param $subGroup Sub group
2644 * @return $isset Whether the given group is set
2646 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2648 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2651 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2658 * Getter for sub key group
2660 * @param $keyGroup Main key group
2661 * @param $subGroup Sub key group
2662 * @return $array An array with all array elements
2664 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2666 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2667 // No, then abort here
2668 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2673 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2676 return $this->genericArray[$keyGroup][$subGroup];
2680 * Unsets a given key in generic array
2682 * @param $keyGroup Main group for the key
2683 * @param $subGroup Sub group for the key
2684 * @param $key Key to unset
2687 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2689 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2692 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2696 * Unsets a given element in generic array
2698 * @param $keyGroup Main group for the key
2699 * @param $subGroup Sub group for the key
2700 * @param $key Key to unset
2701 * @param $element Element to unset
2704 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2706 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2709 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2713 * Append a string to a given generic array key
2715 * @param $keyGroup Main group for the key
2716 * @param $subGroup Sub group for the key
2717 * @param $key Key to unset
2718 * @param $value Value to add/append
2721 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2723 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true) . ',appendGlue=' . $appendGlue);
2725 // Is it already there?
2726 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2728 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2731 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2736 * Append a string to a given generic array element
2738 * @param $keyGroup Main group for the key
2739 * @param $subGroup Sub group for the key
2740 * @param $key Key to unset
2741 * @param $element Element to check
2742 * @param $value Value to add/append
2745 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2747 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true) . ',appendGlue=' . $appendGlue);
2749 // Is it already there?
2750 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2752 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2755 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2760 * Sets a string in a given generic array element
2762 * @param $keyGroup Main group for the key
2763 * @param $subGroup Sub group for the key
2764 * @param $key Key to unset
2765 * @param $element Element to check
2766 * @param $value Value to add/append
2769 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2771 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true) . ',appendGlue=' . $appendGlue);
2774 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2778 * Initializes given generic array group
2780 * @param $keyGroup Main group for the key
2781 * @param $subGroup Sub group for the key
2782 * @param $key Key to use
2783 * @param $forceInit Optionally force initialization
2786 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2788 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2790 // Is it already set?
2791 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2792 // Already initialized
2793 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2798 $this->genericArray[$keyGroup][$subGroup] = array();
2802 * Initializes given generic array key
2804 * @param $keyGroup Main group for the key
2805 * @param $subGroup Sub group for the key
2806 * @param $key Key to use
2807 * @param $forceInit Optionally force initialization
2810 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2812 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2814 // Is it already set?
2815 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2816 // Already initialized
2817 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2822 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2826 * Initializes given generic array element
2828 * @param $keyGroup Main group for the key
2829 * @param $subGroup Sub group for the key
2830 * @param $key Key to use
2831 * @param $element Element to use
2832 * @param $forceInit Optionally force initialization
2835 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2837 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2839 // Is it already set?
2840 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2841 // Already initialized
2842 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2847 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2851 * Pushes an element to a generic key
2853 * @param $keyGroup Main group for the key
2854 * @param $subGroup Sub group for the key
2855 * @param $key Key to use
2856 * @param $value Value to add/append
2857 * @return $count Number of array elements
2859 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2861 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2864 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2866 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2870 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2873 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2874 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2879 * Pushes an element to a generic array element
2881 * @param $keyGroup Main group for the key
2882 * @param $subGroup Sub group for the key
2883 * @param $key Key to use
2884 * @param $element Element to check
2885 * @param $value Value to add/append
2886 * @return $count Number of array elements
2888 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2890 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true));
2893 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2895 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2899 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2902 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2903 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2908 * Pops an element from a generic group
2910 * @param $keyGroup Main group for the key
2911 * @param $subGroup Sub group for the key
2912 * @param $key Key to unset
2913 * @return $value Last "popped" value
2915 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2917 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2920 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2922 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2927 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2930 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2931 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2936 * Shifts an element from a generic group
2938 * @param $keyGroup Main group for the key
2939 * @param $subGroup Sub group for the key
2940 * @param $key Key to unset
2941 * @return $value Last "popped" value
2943 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2945 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2948 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2950 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2955 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2958 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2959 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2964 * Count generic array group
2966 * @param $keyGroup Main group for the key
2967 * @return $count Count of given group
2969 protected final function countGenericArray ($keyGroup) {
2971 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2974 if (!isset($this->genericArray[$keyGroup])) {
2976 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
2981 $count = count($this->genericArray[$keyGroup]);
2984 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
2991 * Count generic array sub group
2993 * @param $keyGroup Main group for the key
2994 * @param $subGroup Sub group for the key
2995 * @return $count Count of given group
2997 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
2999 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3002 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3004 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3009 $count = count($this->genericArray[$keyGroup][$subGroup]);
3012 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3019 * Count generic array elements
3021 * @param $keyGroup Main group for the key
3022 * @param $subGroup Sub group for the key
3023 * @para $key Key to count
3024 * @return $count Count of given key
3026 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3028 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3031 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3033 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3035 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3037 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3042 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3045 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3052 * Getter for whole generic group array
3054 * @param $keyGroup Key group to get
3055 * @return $array Whole generic array group
3057 protected final function getGenericArray ($keyGroup) {
3059 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3062 if (!isset($this->genericArray[$keyGroup])) {
3064 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3069 return $this->genericArray[$keyGroup];
3073 * Setter for generic array key
3075 * @param $keyGroup Key group to get
3076 * @param $subGroup Sub group for the key
3077 * @param $key Key to unset
3078 * @param $value Mixed value from generic array element
3081 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3083 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3086 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3090 * Getter for generic array key
3092 * @param $keyGroup Key group to get
3093 * @param $subGroup Sub group for the key
3094 * @param $key Key to unset
3095 * @return $value Mixed value from generic array element
3097 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3099 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3102 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3104 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3109 return $this->genericArray[$keyGroup][$subGroup][$key];
3113 * Sets a value in given generic array key/element
3115 * @param $keyGroup Main group for the key
3116 * @param $subGroup Sub group for the key
3117 * @param $key Key to set
3118 * @param $element Element to set
3119 * @param $value Value to set
3122 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3124 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',value[' . gettype($value) . ']=' . print_r($value, true));
3127 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3131 * Getter for generic array element
3133 * @param $keyGroup Key group to get
3134 * @param $subGroup Sub group for the key
3135 * @param $key Key to look for
3136 * @param $element Element to look for
3137 * @return $value Mixed value from generic array element
3139 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3141 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3144 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3146 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3151 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3155 * Checks if a given sub group is valid (array)
3157 * @param $keyGroup Key group to get
3158 * @param $subGroup Sub group for the key
3159 * @return $isValid Whether given sub group is valid
3161 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3163 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3166 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3173 * Checks if a given key is valid (array)
3175 * @param $keyGroup Key group to get
3176 * @param $subGroup Sub group for the key
3177 * @param $key Key to check
3178 * @return $isValid Whether given sub group is valid
3180 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3182 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3185 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3192 * Initializes the web output instance
3196 protected function initWebOutputInstance () {
3197 // Get application instance
3198 $applicationInstance = Registry::getRegistry()->getInstance('app');
3200 // Init web output instance
3201 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3204 $this->setWebOutputInstance($outputInstance);
3208 * Translates boolean true to 'Y' and false to 'N'
3210 * @param $boolean Boolean value
3211 * @return $translated Translated boolean value
3213 public static final function translateBooleanToYesNo ($boolean) {
3214 // Make sure it is really boolean
3215 assert(is_bool($boolean));
3218 $translated = ($boolean === true) ? 'Y' : 'N';
3220 // ... and return it
3225 * Encodes raw data (almost any type) by "serializing" it and then pack it
3226 * into a "binary format".
3228 * @param $rawData Raw data (almost any type)
3229 * @return $encoded Encoded data
3231 protected function encodeData ($rawData) {
3232 // Make sure no objects or resources pass through
3233 assert(!is_object($rawData));
3234 assert(!is_resource($rawData));
3236 // First "serialize" it (json_encode() is faster than serialize())
3237 $encoded = $this->packString(json_encode($rawData));
3244 * Pack a string into a "binary format". Please execuse me that this is
3245 * widely undocumented. :-(
3247 * @param $str Unpacked string
3248 * @return $packed Packed string
3249 * @todo Improve documentation
3251 protected function packString ($str) {
3253 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3255 // First compress the string (gzcompress is okay)
3256 $str = gzcompress($str);
3261 // And start the "encoding" loop
3262 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3264 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3265 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3267 if (($idx + $i) <= strlen($str)) {
3268 $ord = ord(substr($str, ($idx + $i), 1));
3270 $add = $ord * pow(256, $factor);
3274 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3278 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3279 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3281 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3282 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3288 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3293 * Creates a full-qualified file name (FQFN) for given file name by adding
3294 * a configured temporary file path to it.
3296 * @param $infoInstance An instance of a SplFileInfo class
3297 * @return $tempInstance An instance of a SplFileInfo class (temporary file)
3298 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3299 * @throws FileIoException If the file cannot be written
3301 protected static function createTempPathForFile (SplFileInfo $infoInstance) {
3303 $basePath = FrameworkBootstrap::getConfigurationInstance()->getConfigEntry('temp_file_path');
3305 // Is the path writeable?
3306 if (!is_writable($basePath)) {
3307 // Path is write-protected
3308 throw new PathWriteProtectedException($infoInstance, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3312 $tempInstance = new SplFileInfo($basePath . DIRECTORY_SEPARATOR . $infoInstance->getBasename());
3315 if (!FrameworkBootstrap::isReachableFilePath($tempInstance)) {
3317 throw new FileIoException($tempInstance, self::EXCEPTION_FILE_NOT_REACHABLE);
3321 return $tempInstance;
3325 * "Getter" for a printable state name
3327 * @return $stateName Name of the node's state in a printable format
3329 public final function getPrintableState () {
3330 // Default is 'null'
3331 $stateName = 'null';
3333 // Get the state instance
3334 $stateInstance = $this->getStateInstance();
3336 // Is it an instance of Stateable?
3337 if ($stateInstance instanceof Stateable) {
3338 // Then use that state name
3339 $stateName = $stateInstance->getStateName();