3 namespace CoreFramework\Object;
5 // Import framework stuff
6 use CoreFramework\Bootstrap\FrameworkBootstrap;
7 use CoreFramework\Compressor\Compressor;
8 use CoreFramework\Configuration\FrameworkConfiguration;
9 use CoreFramework\Connection\Database\DatabaseConnection;
10 use CoreFramework\Controller\Controller;
11 use CoreFramework\Criteria\Criteria;
12 use CoreFramework\Criteria\Local\LocalSearchCriteria;
13 use CoreFramework\Criteria\Local\LocalUpdateCriteria;
14 use CoreFramework\Crypto\Cryptable;
15 use CoreFramework\Crypto\RandomNumber\RandomNumberGenerator;
16 use CoreFramework\Database\Frontend\DatabaseWrapper;
17 use CoreFramework\Factory\Database\Wrapper\DatabaseWrapperFactory;
18 use CoreFramework\Factory\ObjectFactory;
19 use CoreFramework\Filesystem\Block;
20 use CoreFramework\Filesystem\FilePointer;
21 use CoreFramework\Filesystem\FrameworkDirectory;
22 use CoreFramework\Filesystem\PathWriteProtectedException;
23 use CoreFramework\Generic\FrameworkInterface;
24 use CoreFramework\Generic\NullPointerException;
25 use CoreFramework\Handler\Stream\IoHandler;
26 use CoreFramework\Index\Indexable;
27 use CoreFramework\Listener\Listenable;
28 use CoreFramework\Lists\Listable;
29 use CoreFramework\Loader\ClassLoader;
30 use CoreFramework\Manager\ManageableApplication;
31 use CoreFramework\Middleware\Compressor\CompressorChannel;
32 use CoreFramework\Middleware\Debug\DebugMiddleware;
33 use CoreFramework\Parser\Parseable;
34 use CoreFramework\Registry\Register;
35 use CoreFramework\Registry\Registry;
36 use CoreFramework\Resolver\Resolver;
37 use CoreFramework\Result\Database\CachedDatabaseResult;
38 use CoreFramework\Result\Search\SearchableResult;
39 use CoreFramework\Stacker\Stackable;
40 use CoreFramework\State\Stateable;
41 use CoreFramework\Stream\Output\OutputStreamer;
42 use CoreFramework\Template\CompileableTemplate;
43 use CoreFramework\User\ManageableAccount;
44 use CoreFramework\Visitor\Visitor;
52 * The simulator system class is the super class of all other classes. This
53 * class handles saving of games etc.
55 * @author Roland Haeder <webmaster@shipsimu.org>
57 * @copyright Copyright (c) 2007, 2008 Roland Haeder, 2009 - 2017 Core Developer Team
58 * @license GNU GPL 3.0 or any newer version
59 * @link http://www.shipsimu.org
61 * This program is free software: you can redistribute it and/or modify
62 * it under the terms of the GNU General Public License as published by
63 * the Free Software Foundation, either version 3 of the License, or
64 * (at your option) any later version.
66 * This program is distributed in the hope that it will be useful,
67 * but WITHOUT ANY WARRANTY; without even the implied warranty of
68 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
69 * GNU General Public License for more details.
71 * You should have received a copy of the GNU General Public License
72 * along with this program. If not, see <http://www.gnu.org/licenses/>.
74 class BaseFrameworkSystem extends stdClass implements FrameworkInterface {
76 * Length of output from hash()
78 private static $hashLength = NULL;
83 private $realClass = 'BaseFrameworkSystem';
86 * Search criteria instance
88 private $searchInstance = NULL;
91 * Update criteria instance
93 private $updateInstance = NULL;
96 * The file I/O instance for the template loader
98 private $fileIoInstance = NULL;
103 private $resolverInstance = NULL;
106 * Template engine instance
108 private $templateInstance = NULL;
111 * Database result instance
113 private $resultInstance = NULL;
116 * Instance for user class
118 private $userInstance = NULL;
121 * A controller instance
123 private $controllerInstance = NULL;
128 private $rngInstance = NULL;
131 * Instance of a crypto helper
133 private $cryptoInstance = NULL;
136 * Instance of an Iterator class
138 private $iteratorInstance = NULL;
141 * Instance of the list
143 private $listInstance = NULL;
148 private $menuInstance = NULL;
151 * Instance of the image
153 private $imageInstance = NULL;
156 * Instance of the stacker
158 private $stackInstance = NULL;
161 * A Compressor instance
163 private $compressorInstance = NULL;
166 * A Parseable instance
168 private $parserInstance = NULL;
171 * A HandleableProtocol instance
173 private $protocolInstance = NULL;
176 * A database wrapper instance
178 private $databaseInstance = NULL;
181 * A helper instance for the form
183 private $helperInstance = NULL;
186 * An instance of a Source class
188 private $sourceInstance = NULL;
191 * An instance of a UrlSource class
193 private $urlSourceInstance = NULL;
196 * An instance of a InputStream class
198 private $inputStreamInstance = NULL;
201 * An instance of a OutputStream class
203 private $outputStreamInstance = NULL;
206 * Networkable handler instance
208 private $handlerInstance = NULL;
211 * Visitor handler instance
213 private $visitorInstance = NULL;
218 private $dhtInstance = NULL;
221 * An instance of a database wrapper class
223 private $wrapperInstance = NULL;
226 * An instance of a file I/O pointer class (not handler)
228 private $pointerInstance = NULL;
231 * An instance of an Indexable class
233 private $indexInstance = NULL;
236 * An instance of a Block class
238 private $blockInstance = NULL;
243 private $minableInstance = NULL;
246 * A FrameworkDirectory instance
248 private $directoryInstance = NULL;
253 private $listenerInstance = NULL;
256 * An instance of a communicator
258 private $communicatorInstance = NULL;
261 * The concrete output instance
263 private $outputInstance = NULL;
268 private $stateInstance = NULL;
271 * Thousands separator
273 private $thousands = '.'; // German
278 private $decimals = ','; // German
283 private $socketResource = false;
286 * Regular expression to use for validation
288 private $regularExpression = '';
293 private $packageData = array();
298 private $genericArray = array();
303 private $commandName = '';
308 private $controllerName = '';
311 * Name of used protocol
313 private $protocolName = 'invalid';
316 * Array with bitmasks and such for pack/unpack methods to support both
317 * 32-bit and 64-bit systems
319 private $packingData = array(
322 'left' => 0xffff0000,
323 'right' => 0x0000ffff,
329 'left' => 0xffffffff00000000,
330 'right' => 0x00000000ffffffff,
337 * Simple 64-bit check, thanks to "Salman A" from stackoverflow.com:
339 * The integer size is 4 bytes on 32-bit and 8 bytes on a 64-bit system.
341 private $archArrayElement = false;
343 /***********************
344 * Exception codes.... *
345 ***********************/
347 // @todo Try to clean these constants up
348 const EXCEPTION_IS_NULL_POINTER = 0x001;
349 const EXCEPTION_IS_NO_OBJECT = 0x002;
350 const EXCEPTION_IS_NO_ARRAY = 0x003;
351 const EXCEPTION_MISSING_METHOD = 0x004;
352 const EXCEPTION_CLASSES_NOT_MATCHING = 0x005;
353 const EXCEPTION_INDEX_OUT_OF_BOUNDS = 0x006;
354 const EXCEPTION_DIMENSION_ARRAY_INVALID = 0x007;
355 const EXCEPTION_ITEM_NOT_TRADEABLE = 0x008;
356 const EXCEPTION_ITEM_NOT_IN_PRICE_LIST = 0x009;
357 const EXCEPTION_GENDER_IS_WRONG = 0x00a;
358 const EXCEPTION_BIRTH_DATE_IS_INVALID = 0x00b;
359 const EXCEPTION_EMPTY_STRUCTURES_ARRAY = 0x00c;
360 const EXCEPTION_HAS_ALREADY_PERSONELL_LIST = 0x00d;
361 const EXCEPTION_NOT_ENOUGTH_UNEMPLOYEES = 0x00e;
362 const EXCEPTION_TOTAL_PRICE_NOT_CALCULATED = 0x00f;
363 const EXCEPTION_HARBOR_HAS_NO_SHIPYARDS = 0x010;
364 const EXCEPTION_CONTRACT_PARTNER_INVALID = 0x011;
365 const EXCEPTION_CONTRACT_PARTNER_MISMATCH = 0x012;
366 const EXCEPTION_CONTRACT_ALREADY_SIGNED = 0x013;
367 const EXCEPTION_UNEXPECTED_EMPTY_STRING = 0x014;
368 const EXCEPTION_PATH_NOT_FOUND = 0x015;
369 const EXCEPTION_INVALID_PATH_NAME = 0x016;
370 const EXCEPTION_READ_PROTECED_PATH = 0x017;
371 const EXCEPTION_WRITE_PROTECED_PATH = 0x018;
372 const EXCEPTION_DIR_POINTER_INVALID = 0x019;
373 const EXCEPTION_FILE_POINTER_INVALID = 0x01a;
374 const EXCEPTION_INVALID_RESOURCE = 0x01b;
375 const EXCEPTION_UNEXPECTED_OBJECT = 0x01c;
376 const EXCEPTION_LIMIT_ELEMENT_IS_UNSUPPORTED = 0x01d;
377 const EXCEPTION_GETTER_IS_MISSING = 0x01e;
378 const EXCEPTION_ARRAY_EXPECTED = 0x01f;
379 const EXCEPTION_ARRAY_HAS_INVALID_COUNT = 0x020;
380 const EXCEPTION_ID_IS_INVALID_FORMAT = 0x021;
381 const EXCEPTION_MD5_CHECKSUMS_MISMATCH = 0x022;
382 const EXCEPTION_UNEXPECTED_STRING_SIZE = 0x023;
383 const EXCEPTION_SIMULATOR_ID_INVALID = 0x024;
384 const EXCEPTION_MISMATCHING_COMPRESSORS = 0x025;
385 const EXCEPTION_CONTAINER_ITEM_IS_NULL = 0x026;
386 const EXCEPTION_ITEM_IS_NO_ARRAY = 0x027;
387 const EXCEPTION_CONTAINER_MAYBE_DAMAGED = 0x028;
388 const EXCEPTION_INVALID_STRING = 0x029;
389 const EXCEPTION_VARIABLE_NOT_SET = 0x02a;
390 const EXCEPTION_ATTRIBUTES_ARE_MISSING = 0x02b;
391 const EXCEPTION_ARRAY_ELEMENTS_MISSING = 0x02c;
392 const EXCEPTION_TEMPLATE_ENGINE_UNSUPPORTED = 0x02d;
393 const EXCEPTION_UNSPPORTED_OPERATION = 0x02e;
394 const EXCEPTION_FACTORY_REQUIRE_PARAMETER = 0x02f;
395 const EXCEPTION_MISSING_ELEMENT = 0x030;
396 const EXCEPTION_HEADERS_ALREADY_SENT = 0x031;
397 const EXCEPTION_DEFAULT_CONTROLLER_GONE = 0x032;
398 const EXCEPTION_CLASS_NOT_FOUND = 0x033;
399 const EXCEPTION_REQUIRED_INTERFACE_MISSING = 0x034;
400 const EXCEPTION_FATAL_ERROR = 0x035;
401 const EXCEPTION_FILE_NOT_FOUND = 0x036;
402 const EXCEPTION_ASSERTION_FAILED = 0x037;
403 const EXCEPTION_FILE_NOT_REACHABLE = 0x038;
404 const EXCEPTION_FILE_CANNOT_BE_READ = 0x039;
405 const EXCEPTION_FILE_CANNOT_BE_WRITTEN = 0x03a;
406 const EXCEPTION_PATH_CANNOT_BE_WRITTEN = 0x03b;
407 const EXCEPTION_DATABASE_UPDATED_NOT_ALLOWED = 0x03c;
408 const EXCEPTION_FILTER_CHAIN_INTERCEPTED = 0x03d;
411 * Hexadecimal->Decimal translation array
413 private static $hexdec = array(
433 * Decimal->hexadecimal translation array
435 private static $dechex = array(
455 * Startup time in miliseconds
457 private static $startupTime = 0;
460 * Protected super constructor
462 * @param $className Name of the class
465 protected function __construct ($className) {
467 $this->setRealClass($className);
469 // Set configuration instance if no registry ...
470 if (!$this instanceof Register) {
471 // ... because registries doesn't need to be configured
472 $this->setConfigInstance(FrameworkConfiguration::getSelfInstance());
475 // Is the startup time set? (0 cannot be true anymore)
476 if (self::$startupTime == 0) {
478 self::$startupTime = microtime(true);
482 $this->archArrayElement = (PHP_INT_SIZE === 8 ? 64 : 32);
486 * Destructor for all classes. You should not call this method on your own.
490 public function __destruct () {
491 // Flush any updated entries to the database
492 $this->flushPendingUpdates();
494 // Is this object already destroyed?
495 if ($this->__toString() != 'DestructedObject') {
496 // Destroy all informations about this class but keep some text about it alive
497 $this->setRealClass('DestructedObject');
498 } elseif ((defined('DEBUG_DESTRUCTOR')) && (is_object($this->getDebugInstance()))) {
499 // Already destructed object
500 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[%s:] The object <span class="object_name">%s</span> is already destroyed.',
505 // Do not call this twice
506 trigger_error(__METHOD__ . ': Called twice.');
512 * The __call() method where all non-implemented methods end up
514 * @param $methodName Name of the missing method
515 * @args $args Arguments passed to the method
518 public final function __call ($methodName, $args) {
519 return self::__callStatic($methodName, $args);
523 * The __callStatic() method where all non-implemented static methods end up
525 * @param $methodName Name of the missing method
526 * @args $args Arguments passed to the method
529 public static final function __callStatic ($methodName, $args) {
531 //* PRINT-DEBUG: */ printf('[%s:%d]: methodName=%s,args[]=%s - CALLED!' . PHP_EOL, __METHOD__, __LINE__, $methodName, gettype($args));
533 // Init argument string
536 // Is it NULL, empty or an array?
537 if (is_null($args)) {
539 $argsString = 'NULL';
540 } elseif (is_array($args)) {
544 // Some arguments are there
545 foreach ($args as $arg) {
546 // Add data about the argument
547 $argsString .= gettype($arg) . ':';
550 // Found a NULL argument
551 $argsString .= 'NULL';
552 } elseif (is_string($arg)) {
553 // Add length for strings
554 $argsString .= strlen($arg);
555 } elseif ((is_int($arg)) || (is_float($arg))) {
558 } elseif (is_array($arg)) {
559 // .. or size if array
560 $argsString .= count($arg);
561 } elseif (is_object($arg)) {
563 $reflection = new ReflectionClass($arg);
565 // Is an other object, maybe no __toString() available
566 $argsString .= $reflection->getName();
567 } elseif ($arg === true) {
568 // ... is boolean 'true'
569 $argsString .= 'true';
570 } elseif ($arg === false) {
571 // ... is boolean 'false'
572 $argsString .= 'false';
575 // Comma for next one
580 if (substr($argsString, -2, 1) == ',') {
581 $argsString = substr($argsString, 0, -2);
587 // Invalid arguments!
588 $argsString = '!INVALID:' . gettype($args) . '!';
591 // Output stub message
592 // @TODO __CLASS__ does always return BaseFrameworkSystem but not the extending (=child) class
593 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput(sprintf('[unknown::%s:] Stub! Args: %s',
603 * Getter for $realClass
605 * @return $realClass The name of the real class (not BaseFrameworkSystem)
607 public function __toString () {
608 return $this->realClass;
612 * Magic method to catch setting of missing but set class fields/attributes
614 * @param $name Name of the field/attribute
615 * @param $value Value to store
618 public final function __set ($name, $value) {
619 $this->debugBackTrace(sprintf('Tried to set a missing field. name=%s, value[%s]=%s',
622 print_r($value, true)
627 * Magic method to catch getting of missing fields/attributes
629 * @param $name Name of the field/attribute
632 public final function __get ($name) {
633 $this->debugBackTrace(sprintf('Tried to get a missing field. name=%s',
639 * Magic method to catch unsetting of missing fields/attributes
641 * @param $name Name of the field/attribute
644 public final function __unset ($name) {
645 $this->debugBackTrace(sprintf('Tried to unset a missing field. name=%s',
651 * Magic method to catch object serialization
653 * @return $unsupported Unsupported method
654 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
656 public final function __sleep () {
657 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
661 * Magic method to catch object deserialization
663 * @return $unsupported Unsupported method
664 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
666 public final function __wakeup () {
667 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
671 * Magic method to catch calls when an object instance is called
673 * @return $unsupported Unsupported method
674 * @throws UnsupportedOperationException Objects of this framework cannot be serialized
676 public final function __invoke () {
677 throw new UnsupportedOperationException(array($this, __FUNCTION__), self::EXCEPTION_UNSPPORTED_OPERATION);
681 * Setter for the real class name
683 * @param $realClass Class name (string)
686 public final function setRealClass ($realClass) {
688 $this->realClass = (string) $realClass;
692 * Setter for database result instance
694 * @param $resultInstance An instance of a database result class
696 * @todo SearchableResult and UpdateableResult shall have a super interface to use here
698 protected final function setResultInstance (SearchableResult $resultInstance) {
699 $this->resultInstance = $resultInstance;
703 * Getter for database result instance
705 * @return $resultInstance An instance of a database result class
707 public final function getResultInstance () {
708 return $this->resultInstance;
712 * Setter for template engine instances
714 * @param $templateInstance An instance of a template engine class
717 protected final function setTemplateInstance (CompileableTemplate $templateInstance) {
718 $this->templateInstance = $templateInstance;
722 * Getter for template engine instances
724 * @return $templateInstance An instance of a template engine class
726 protected final function getTemplateInstance () {
727 return $this->templateInstance;
731 * Setter for search instance
733 * @param $searchInstance Searchable criteria instance
736 public final function setSearchInstance (LocalSearchCriteria $searchInstance) {
737 $this->searchInstance = $searchInstance;
741 * Getter for search instance
743 * @return $searchInstance Searchable criteria instance
745 public final function getSearchInstance () {
746 return $this->searchInstance;
750 * Setter for update instance
752 * @param $updateInstance An instance of a LocalUpdateCriteria clase
755 public final function setUpdateInstance (LocalUpdateCriteria $updateInstance) {
756 $this->updateInstance = $updateInstance;
760 * Getter for update instance
762 * @return $updateInstance Updateable criteria instance
764 public final function getUpdateInstance () {
765 return $this->updateInstance;
769 * Setter for resolver instance
771 * @param $resolverInstance Instance of a command resolver class
774 public final function setResolverInstance (Resolver $resolverInstance) {
775 $this->resolverInstance = $resolverInstance;
779 * Getter for resolver instance
781 * @return $resolverInstance Instance of a command resolver class
783 public final function getResolverInstance () {
784 return $this->resolverInstance;
788 * Setter for language instance
790 * @param $configInstance The configuration instance which shall
791 * be FrameworkConfiguration
794 public final function setConfigInstance (FrameworkConfiguration $configInstance) {
795 Registry::getRegistry()->addInstance('config', $configInstance);
799 * Getter for configuration instance
801 * @return $configInstance Configuration instance
803 public final function getConfigInstance () {
804 $configInstance = Registry::getRegistry()->getInstance('config');
805 return $configInstance;
809 * Setter for debug instance
811 * @param $debugInstance The instance for debug output class
814 public final function setDebugInstance (DebugMiddleware $debugInstance) {
815 Registry::getRegistry()->addInstance('debug', $debugInstance);
819 * Getter for debug instance
821 * @return $debugInstance Instance to class DebugConsoleOutput or DebugWebOutput
823 public final function getDebugInstance () {
824 // Get debug instance
825 $debugInstance = Registry::getRegistry()->getInstance('debug');
828 return $debugInstance;
832 * Setter for web output instance
834 * @param $webInstance The instance for web output class
837 public final function setWebOutputInstance (OutputStreamer $webInstance) {
838 Registry::getRegistry()->addInstance('web_output', $webInstance);
842 * Getter for web output instance
844 * @return $webOutputInstance - Instance to class WebOutput
846 public final function getWebOutputInstance () {
847 $webOutputInstance = Registry::getRegistry()->getInstance('web_output');
848 return $webOutputInstance;
852 * Setter for database instance
854 * @param $databaseInstance The instance for the database connection (forced DatabaseConnection)
857 public final function setDatabaseInstance (DatabaseConnection $databaseInstance) {
858 Registry::getRegistry()->addInstance('db_instance', $databaseInstance);
862 * Getter for database layer
864 * @return $databaseInstance The database layer instance
866 public final function getDatabaseInstance () {
868 $databaseInstance = Registry::getRegistry()->getInstance('db_instance');
871 return $databaseInstance;
875 * Setter for compressor channel
877 * @param $compressorInstance An instance of CompressorChannel
880 public final function setCompressorChannel (CompressorChannel $compressorInstance) {
881 Registry::getRegistry()->addInstance('compressor', $compressorInstance);
885 * Getter for compressor channel
887 * @return $compressorInstance The compressor channel
889 public final function getCompressorChannel () {
890 $compressorInstance = Registry::getRegistry()->getInstance('compressor');
891 return $compressorInstance;
895 * Protected getter for a manageable application helper class
897 * @return $applicationInstance An instance of a manageable application helper class
899 protected final function getApplicationInstance () {
900 $applicationInstance = Registry::getRegistry()->getInstance('app');
901 return $applicationInstance;
905 * Setter for a manageable application helper class
907 * @param $applicationInstance An instance of a manageable application helper class
910 public final function setApplicationInstance (ManageableApplication $applicationInstance) {
911 Registry::getRegistry()->addInstance('application', $applicationInstance);
915 * Private getter for language instance
917 * @return $langInstance An instance to the language sub-system
919 protected final function getLanguageInstance () {
920 $langInstance = Registry::getRegistry()->getInstance('language');
921 return $langInstance;
925 * Setter for language instance
927 * @param $langInstance An instance to the language sub-system
929 * @see LanguageSystem
931 public final function setLanguageInstance (ManageableLanguage $langInstance) {
932 Registry::getRegistry()->addInstance('language', $langInstance);
936 * Private getter for file IO instance
938 * @return $fileIoInstance An instance to the file I/O sub-system
940 protected final function getFileIoInstance () {
941 return $this->fileIoInstance;
945 * Setter for file I/O instance
947 * @param $fileIoInstance An instance to the file I/O sub-system
950 public final function setFileIoInstance (IoHandler $fileIoInstance) {
951 $this->fileIoInstance = $fileIoInstance;
955 * Protected setter for user instance
957 * @param $userInstance An instance of a user class
960 protected final function setUserInstance (ManageableAccount $userInstance) {
961 $this->userInstance = $userInstance;
965 * Getter for user instance
967 * @return $userInstance An instance of a user class
969 public final function getUserInstance () {
970 return $this->userInstance;
974 * Setter for controller instance (this surely breaks a bit the MVC patterm)
976 * @param $controllerInstance An instance of the controller
979 public final function setControllerInstance (Controller $controllerInstance) {
980 $this->controllerInstance = $controllerInstance;
984 * Getter for controller instance (this surely breaks a bit the MVC patterm)
986 * @return $controllerInstance An instance of the controller
988 public final function getControllerInstance () {
989 return $this->controllerInstance;
993 * Setter for RNG instance
995 * @param $rngInstance An instance of a random number generator (RNG)
998 protected final function setRngInstance (RandomNumberGenerator $rngInstance) {
999 $this->rngInstance = $rngInstance;
1003 * Getter for RNG instance
1005 * @return $rngInstance An instance of a random number generator (RNG)
1007 public final function getRngInstance () {
1008 return $this->rngInstance;
1012 * Setter for Cryptable instance
1014 * @param $cryptoInstance An instance of a Cryptable class
1017 protected final function setCryptoInstance (Cryptable $cryptoInstance) {
1018 $this->cryptoInstance = $cryptoInstance;
1022 * Getter for Cryptable instance
1024 * @return $cryptoInstance An instance of a Cryptable class
1026 public final function getCryptoInstance () {
1027 return $this->cryptoInstance;
1031 * Setter for the list instance
1033 * @param $listInstance A list of Listable
1036 protected final function setListInstance (Listable $listInstance) {
1037 $this->listInstance = $listInstance;
1041 * Getter for the list instance
1043 * @return $listInstance A list of Listable
1045 protected final function getListInstance () {
1046 return $this->listInstance;
1050 * Setter for the menu instance
1052 * @param $menuInstance A RenderableMenu instance
1055 protected final function setMenuInstance (RenderableMenu $menuInstance) {
1056 $this->menuInstance = $menuInstance;
1060 * Getter for the menu instance
1062 * @return $menuInstance A RenderableMenu instance
1064 protected final function getMenuInstance () {
1065 return $this->menuInstance;
1069 * Setter for image instance
1071 * @param $imageInstance An instance of an image
1074 public final function setImageInstance (BaseImage $imageInstance) {
1075 $this->imageInstance = $imageInstance;
1079 * Getter for image instance
1081 * @return $imageInstance An instance of an image
1083 public final function getImageInstance () {
1084 return $this->imageInstance;
1088 * Setter for stacker instance
1090 * @param $stackInstance An instance of an stacker
1093 public final function setStackInstance (Stackable $stackInstance) {
1094 $this->stackInstance = $stackInstance;
1098 * Getter for stacker instance
1100 * @return $stackInstance An instance of an stacker
1102 public final function getStackInstance () {
1103 return $this->stackInstance;
1107 * Setter for compressor instance
1109 * @param $compressorInstance An instance of an compressor
1112 public final function setCompressorInstance (Compressor $compressorInstance) {
1113 $this->compressorInstance = $compressorInstance;
1117 * Getter for compressor instance
1119 * @return $compressorInstance An instance of an compressor
1121 public final function getCompressorInstance () {
1122 return $this->compressorInstance;
1126 * Setter for Parseable instance
1128 * @param $parserInstance An instance of an Parseable
1131 public final function setParserInstance (Parseable $parserInstance) {
1132 $this->parserInstance = $parserInstance;
1136 * Getter for Parseable instance
1138 * @return $parserInstance An instance of an Parseable
1140 public final function getParserInstance () {
1141 return $this->parserInstance;
1145 * Setter for HandleableProtocol instance
1147 * @param $protocolInstance An instance of an HandleableProtocol
1150 public final function setProtocolInstance (HandleableProtocol $protocolInstance) {
1151 $this->protocolInstance = $protocolInstance;
1155 * Getter for HandleableProtocol instance
1157 * @return $protocolInstance An instance of an HandleableProtocol
1159 public final function getProtocolInstance () {
1160 return $this->protocolInstance;
1164 * Setter for DatabaseWrapper instance
1166 * @param $wrapperInstance An instance of an DatabaseWrapper
1169 public final function setWrapperInstance (DatabaseWrapper $wrapperInstance) {
1170 $this->wrapperInstance = $wrapperInstance;
1174 * Getter for DatabaseWrapper instance
1176 * @return $wrapperInstance An instance of an DatabaseWrapper
1178 public final function getWrapperInstance () {
1179 return $this->wrapperInstance;
1183 * Setter for socket resource
1185 * @param $socketResource A valid socket resource
1188 public final function setSocketResource ($socketResource) {
1189 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource=' . $socketResource . ',previous[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1190 $this->socketResource = $socketResource;
1194 * Getter for socket resource
1196 * @return $socketResource A valid socket resource
1198 public final function getSocketResource () {
1199 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': socketResource[' . gettype($this->socketResource) . ']=' . $this->socketResource);
1200 return $this->socketResource;
1204 * Setter for regular expression
1206 * @param $regularExpression A valid regular expression
1209 public final function setRegularExpression ($regularExpression) {
1210 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression=' . $regularExpression . ',previous[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1211 $this->regularExpression = $regularExpression;
1215 * Getter for regular expression
1217 * @return $regularExpression A valid regular expression
1219 public final function getRegularExpression () {
1220 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . '::' . __FUNCTION__ . ': regularExpression[' . gettype($this->regularExpression) . ']=' . $this->regularExpression);
1221 return $this->regularExpression;
1225 * Setter for helper instance
1227 * @param $helperInstance An instance of a helper class
1230 protected final function setHelperInstance (Helper $helperInstance) {
1231 $this->helperInstance = $helperInstance;
1235 * Getter for helper instance
1237 * @return $helperInstance An instance of a helper class
1239 public final function getHelperInstance () {
1240 return $this->helperInstance;
1244 * Setter for a Source instance
1246 * @param $sourceInstance An instance of a Source class
1249 protected final function setSourceInstance (Source $sourceInstance) {
1250 $this->sourceInstance = $sourceInstance;
1254 * Getter for a Source instance
1256 * @return $sourceInstance An instance of a Source class
1258 protected final function getSourceInstance () {
1259 return $this->sourceInstance;
1263 * Setter for a UrlSource instance
1265 * @param $sourceInstance An instance of a UrlSource class
1268 protected final function setUrlSourceInstance (UrlSource $urlSourceInstance) {
1269 $this->urlSourceInstance = $urlSourceInstance;
1273 * Getter for a UrlSource instance
1275 * @return $urlSourceInstance An instance of a UrlSource class
1277 protected final function getUrlSourceInstance () {
1278 return $this->urlSourceInstance;
1282 * Getter for a InputStream instance
1284 * @param $inputStreamInstance The InputStream instance
1286 protected final function getInputStreamInstance () {
1287 return $this->inputStreamInstance;
1291 * Setter for a InputStream instance
1293 * @param $inputStreamInstance The InputStream instance
1296 protected final function setInputStreamInstance (InputStream $inputStreamInstance) {
1297 $this->inputStreamInstance = $inputStreamInstance;
1301 * Getter for a OutputStream instance
1303 * @param $outputStreamInstance The OutputStream instance
1305 protected final function getOutputStreamInstance () {
1306 return $this->outputStreamInstance;
1310 * Setter for a OutputStream instance
1312 * @param $outputStreamInstance The OutputStream instance
1315 protected final function setOutputStreamInstance (OutputStream $outputStreamInstance) {
1316 $this->outputStreamInstance = $outputStreamInstance;
1320 * Setter for handler instance
1322 * @param $handlerInstance An instance of a Handleable class
1325 protected final function setHandlerInstance (Handleable $handlerInstance) {
1326 $this->handlerInstance = $handlerInstance;
1330 * Getter for handler instance
1332 * @return $handlerInstance A Networkable instance
1334 protected final function getHandlerInstance () {
1335 return $this->handlerInstance;
1339 * Setter for visitor instance
1341 * @param $visitorInstance A Visitor instance
1344 protected final function setVisitorInstance (Visitor $visitorInstance) {
1345 $this->visitorInstance = $visitorInstance;
1349 * Getter for visitor instance
1351 * @return $visitorInstance A Visitor instance
1353 protected final function getVisitorInstance () {
1354 return $this->visitorInstance;
1358 * Setter for DHT instance
1360 * @param $dhtInstance A Distributable instance
1363 protected final function setDhtInstance (Distributable $dhtInstance) {
1364 $this->dhtInstance = $dhtInstance;
1368 * Getter for DHT instance
1370 * @return $dhtInstance A Distributable instance
1372 protected final function getDhtInstance () {
1373 return $this->dhtInstance;
1377 * Setter for raw package Data
1379 * @param $packageData Raw package Data
1382 public final function setPackageData (array $packageData) {
1383 $this->packageData = $packageData;
1387 * Getter for raw package Data
1389 * @return $packageData Raw package Data
1391 public function getPackageData () {
1392 return $this->packageData;
1397 * Setter for Iterator instance
1399 * @param $iteratorInstance An instance of an Iterator
1402 protected final function setIteratorInstance (Iterator $iteratorInstance) {
1403 $this->iteratorInstance = $iteratorInstance;
1407 * Getter for Iterator instance
1409 * @return $iteratorInstance An instance of an Iterator
1411 public final function getIteratorInstance () {
1412 return $this->iteratorInstance;
1416 * Setter for FilePointer instance
1418 * @param $pointerInstance An instance of an FilePointer class
1421 protected final function setPointerInstance (FilePointer $pointerInstance) {
1422 $this->pointerInstance = $pointerInstance;
1426 * Getter for FilePointer instance
1428 * @return $pointerInstance An instance of an FilePointer class
1430 public final function getPointerInstance () {
1431 return $this->pointerInstance;
1435 * Unsets pointer instance which triggers a call of __destruct() if the
1436 * instance is still there. This is surely not fatal on already "closed"
1437 * file pointer instances.
1439 * I don't want to mess around with above setter by giving it a default
1440 * value NULL as setter should always explicitly only set (existing) object
1441 * instances and NULL is NULL.
1445 protected final function unsetPointerInstance () {
1446 // Simply it to NULL
1447 $this->pointerInstance = NULL;
1451 * Setter for Indexable instance
1453 * @param $indexInstance An instance of an Indexable class
1456 protected final function setIndexInstance (Indexable $indexInstance) {
1457 $this->indexInstance = $indexInstance;
1461 * Getter for Indexable instance
1463 * @return $indexInstance An instance of an Indexable class
1465 public final function getIndexInstance () {
1466 return $this->indexInstance;
1470 * Setter for Block instance
1472 * @param $blockInstance An instance of an Block class
1475 protected final function setBlockInstance (Block $blockInstance) {
1476 $this->blockInstance = $blockInstance;
1480 * Getter for Block instance
1482 * @return $blockInstance An instance of an Block class
1484 public final function getBlockInstance () {
1485 return $this->blockInstance;
1489 * Setter for Minable instance
1491 * @param $minableInstance A Minable instance
1494 protected final function setMinableInstance (Minable $minableInstance) {
1495 $this->minableInstance = $minableInstance;
1499 * Getter for minable instance
1501 * @return $minableInstance A Minable instance
1503 protected final function getMinableInstance () {
1504 return $this->minableInstance;
1508 * Setter for FrameworkDirectory instance
1510 * @param $directoryInstance A FrameworkDirectory instance
1513 protected final function setDirectoryInstance (FrameworkDirectory $directoryInstance) {
1514 $this->directoryInstance = $directoryInstance;
1518 * Getter for FrameworkDirectory instance
1520 * @return $directoryInstance A FrameworkDirectory instance
1522 protected final function getDirectoryInstance () {
1523 return $this->directoryInstance;
1527 * Setter for listener instance
1529 * @param $listenerInstance A Listenable instance
1532 protected final function setListenerInstance (Listenable $listenerInstance) {
1533 $this->listenerInstance = $listenerInstance;
1537 * Getter for listener instance
1539 * @return $listenerInstance A Listenable instance
1541 protected final function getListenerInstance () {
1542 return $this->listenerInstance;
1546 * Getter for communicator instance
1548 * @return $communicatorInstance An instance of a Communicator class
1550 public final function getCommunicatorInstance () {
1551 return $this->communicatorInstance;
1555 * Setter for communicator instance
1557 * @param $communicatorInstance An instance of a Communicator class
1560 protected final function setCommunicatorInstance (Communicator $communicatorInstance) {
1561 $this->communicatorInstance = $communicatorInstance;
1565 * Setter for state instance
1567 * @param $stateInstance A Stateable instance
1570 public final function setStateInstance (Stateable $stateInstance) {
1571 $this->stateInstance = $stateInstance;
1575 * Getter for state instance
1577 * @return $stateInstance A Stateable instance
1579 public final function getStateInstance () {
1580 return $this->stateInstance;
1584 * Setter for output instance
1586 * @param $outputInstance The debug output instance
1589 public final function setOutputInstance (OutputStreamer $outputInstance) {
1590 $this->outputInstance = $outputInstance;
1594 * Getter for output instance
1596 * @return $outputInstance The debug output instance
1598 public final function getOutputInstance () {
1599 return $this->outputInstance;
1603 * Setter for command name
1605 * @param $commandName Last validated command name
1608 protected final function setCommandName ($commandName) {
1609 $this->commandName = $commandName;
1613 * Getter for command name
1615 * @return $commandName Last validated command name
1617 protected final function getCommandName () {
1618 return $this->commandName;
1622 * Setter for controller name
1624 * @param $controllerName Last validated controller name
1627 protected final function setControllerName ($controllerName) {
1628 $this->controllerName = $controllerName;
1632 * Getter for controller name
1634 * @return $controllerName Last validated controller name
1636 protected final function getControllerName () {
1637 return $this->controllerName;
1641 * Getter for protocol name
1643 * @return $protocolName Name of used protocol
1645 public final function getProtocolName () {
1646 return $this->protocolName;
1650 * Setter for protocol name
1652 * @param $protocolName Name of used protocol
1655 protected final function setProtocolName ($protocolName) {
1656 $this->protocolName = $protocolName;
1660 * Checks whether an object equals this object. You should overwrite this
1661 * method to implement own equality checks
1663 * @param $objectInstance An instance of a FrameworkInterface object
1664 * @return $equals Whether both objects equals
1666 public function equals (FrameworkInterface $objectInstance) {
1669 $this->__toString() == $objectInstance->__toString()
1671 $this->hashCode() == $objectInstance->hashCode()
1674 // Return the result
1679 * Generates a generic hash code of this class. You should really overwrite
1680 * this method with your own hash code generator code. But keep KISS in mind.
1682 * @return $hashCode A generic hash code respresenting this whole class
1684 public function hashCode () {
1686 return crc32($this->__toString());
1690 * Formats computer generated price values into human-understandable formats
1691 * with thousand and decimal separators.
1693 * @param $value The in computer format value for a price
1694 * @param $currency The currency symbol (use HTML-valid characters!)
1695 * @param $decNum Number of decimals after commata
1696 * @return $price The for the current language formated price string
1697 * @throws MissingDecimalsThousandsSeparatorException If decimals or
1698 * thousands separator
1701 public function formatCurrency ($value, $currency = '€', $decNum = 2) {
1702 // Are all required attriutes set?
1703 if ((!isset($this->decimals)) || (!isset($this->thousands))) {
1704 // Throw an exception
1705 throw new MissingDecimalsThousandsSeparatorException($this, self::EXCEPTION_ATTRIBUTES_ARE_MISSING);
1709 $value = (float) $value;
1711 // Reformat the US number
1712 $price = number_format($value, $decNum, $this->decimals, $this->thousands) . $currency;
1714 // Return as string...
1719 * Appends a trailing slash to a string
1721 * @param $str A string (maybe) without trailing slash
1722 * @return $str A string with an auto-appended trailing slash
1724 public final function addMissingTrailingSlash ($str) {
1725 // Is there a trailing slash?
1726 if (substr($str, -1, 1) != '/') {
1730 // Return string with trailing slash
1735 * Prepare the template engine (HtmlTemplateEngine by default) for a given
1736 * application helper instance (ApplicationHelper by default).
1738 * @param $applicationInstance An application helper instance or
1739 * null if we shall use the default
1740 * @return $templateInstance The template engine instance
1741 * @throws NullPointerException If the discovered application
1742 * instance is still null
1744 protected function prepareTemplateInstance (ManageableApplication $applicationInstance = NULL) {
1745 // Is the application instance set?
1746 if (is_null($applicationInstance)) {
1747 // Get the current instance
1748 $applicationInstance = Registry::getRegistry()->getInstance('app');
1751 if (is_null($applicationInstance)) {
1752 // Thrown an exception
1753 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
1757 // Initialize the template engine
1758 $templateInstance = ObjectFactory::createObjectByConfiguredName('html_template_class');
1760 // Return the prepared instance
1761 return $templateInstance;
1765 * Debugs this instance by putting out it's full content
1767 * @param $message Optional message to show in debug output
1770 public final function debugInstance ($message = '') {
1771 // Restore the error handler to avoid trouble with missing array elements or undeclared variables
1772 restore_error_handler();
1777 // Is a message set?
1778 if (!empty($message)) {
1779 // Construct message
1780 $content = sprintf('<div class="debug_message">Message: %s</div>' . PHP_EOL, $message);
1783 // Generate the output
1784 $content .= sprintf('<pre>%s</pre>',
1787 print_r($this, true)
1793 ApplicationEntryPoint::app_exit(sprintf('<div class="debug_header">%s debug output:</div><div class="debug_content">%s</div>Loaded includes: <div class="debug_include_list">%s</div>',
1794 $this->__toString(),
1796 ClassLoader::getSelfInstance()->getPrintableIncludeList()
1801 * Replaces control characters with printable output
1803 * @param $str String with control characters
1804 * @return $str Replaced string
1806 protected function replaceControlCharacters ($str) {
1809 chr(13), '[r]', str_replace(
1810 chr(10), '[n]', str_replace(
1820 * Output a partial stub message for the caller method
1822 * @param $message An optional message to display
1825 protected function partialStub ($message = '') {
1826 // Get the backtrace
1827 $backtrace = debug_backtrace();
1829 // Generate the class::method string
1830 $methodName = 'UnknownClass->unknownMethod';
1831 if ((isset($backtrace[1]['class'])) && (isset($backtrace[1]['function']))) {
1832 $methodName = $backtrace[1]['class'] . '->' . $backtrace[1]['function'];
1835 // Construct the full message
1836 $stubMessage = sprintf('[%s:] Partial stub!',
1840 // Is the extra message given?
1841 if (!empty($message)) {
1842 // Then add it as well
1843 $stubMessage .= ' Message: ' . $message;
1846 // Debug instance is there?
1847 if (!is_null($this->getDebugInstance())) {
1848 // Output stub message
1849 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($stubMessage);
1852 trigger_error($stubMessage);
1858 * Outputs a debug backtrace and stops further script execution
1860 * @param $message An optional message to output
1861 * @param $doExit Whether exit the program (true is default)
1864 public function debugBackTrace ($message = '', $doExit = true) {
1865 // Sorry, there is no other way getting this nice backtrace
1866 if (!empty($message)) {
1868 printf('Message: %s<br />' . PHP_EOL, $message);
1872 debug_print_backtrace();
1876 if ($doExit === true) {
1882 * Creates an instance of a debugger instance
1884 * @param $className Name of the class (currently unsupported)
1885 * @param $lineNumber Line number where the call was made
1886 * @return $debugInstance An instance of a debugger class
1887 * @deprecated Not fully, as the new Logger facilities are not finished yet.
1889 public final static function createDebugInstance ($className, $lineNumber = NULL) {
1890 // Is the instance set?
1891 if (!Registry::getRegistry()->instanceExists('debug')) {
1892 // Init debug instance
1893 $debugInstance = NULL;
1897 // Get a debugger instance
1898 $debugInstance = DebugMiddleware::createDebugMiddleware(FrameworkConfiguration::getSelfInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_class'), $className);
1899 } catch (NullPointerException $e) {
1900 // Didn't work, no instance there
1901 exit(sprintf('Cannot create debugInstance! Exception=%s,message=%s,className=%s,lineNumber=%d' . PHP_EOL, $e->__toString(), $e->getMessage(), $className, $lineNumber));
1904 // Empty string should be ignored and used for testing the middleware
1905 DebugMiddleware::getSelfInstance()->output('');
1907 // Set it in its own class. This will set it in the registry
1908 $debugInstance->setDebugInstance($debugInstance);
1910 // Get instance from registry
1911 $debugInstance = Registry::getRegistry()->getDebugInstance();
1915 return $debugInstance;
1919 * Simple output of a message with line-break
1921 * @param $message Message to output
1924 public function outputLine ($message) {
1926 print($message . PHP_EOL);
1930 * Outputs a debug message whether to debug instance (should be set!) or
1931 * dies with or ptints the message. Do NEVER EVER rewrite the exit() call to
1932 * ApplicationEntryPoint::app_exit(), this would cause an endless loop.
1934 * @param $message Message we shall send out...
1935 * @param $doPrint Whether print or die here (default: print)
1936 * @paran $stripTags Whether to strip tags (default: false)
1939 public function debugOutput ($message, $doPrint = true, $stripTags = false) {
1940 // Set debug instance to NULL
1941 $debugInstance = NULL;
1945 // Get debug instance
1946 $debugInstance = $this->getDebugInstance();
1947 } catch (NullPointerException $e) {
1948 // The debug instance is not set (yet)
1951 // Is the debug instance there?
1952 if (is_object($debugInstance)) {
1953 // Use debug output handler
1954 $debugInstance->output($message, $stripTags);
1956 if ($doPrint === false) {
1957 // Die here if not printed
1961 // Are debug times enabled?
1962 if ($this->getConfigInstance()->getConfigEntry('debug_' . FrameworkBootstrap::getRequestTypeFromSystem() . '_output_timings') == 'Y') {
1964 $message = $this->getPrintableExecutionTime() . $message;
1968 if ($doPrint === true) {
1970 $this->outputLine($message);
1979 * Converts e.g. a command from URL to a valid class by keeping out bad characters
1981 * @param $str The string, what ever it is needs to be converted
1982 * @return $className Generated class name
1984 public static final function convertToClassName ($str) {
1988 // Convert all dashes in underscores
1989 $str = self::convertDashesToUnderscores($str);
1991 // Now use that underscores to get classname parts for hungarian style
1992 foreach (explode('_', $str) as $strPart) {
1993 // Make the class name part lower case and first upper case
1994 $className .= ucfirst(strtolower($strPart));
1997 // Return class name
2002 * Converts dashes to underscores, e.g. useable for configuration entries
2004 * @param $str The string with maybe dashes inside
2005 * @return $str The converted string with no dashed, but underscores
2007 public static final function convertDashesToUnderscores ($str) {
2009 $str = str_replace('-', '_', $str);
2011 // Return converted string
2016 * Marks up the code by adding e.g. line numbers
2018 * @param $phpCode Unmarked PHP code
2019 * @return $markedCode Marked PHP code
2021 public function markupCode ($phpCode) {
2026 $errorArray = error_get_last();
2028 // Init the code with error message
2029 if (is_array($errorArray)) {
2031 $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>',
2032 basename($errorArray['file']),
2033 $errorArray['line'],
2034 $errorArray['message'],
2039 // Add line number to the code
2040 foreach (explode(chr(10), $phpCode) as $lineNo => $code) {
2042 $markedCode .= sprintf('<span id="code_line">%s</span>: %s' . PHP_EOL,
2044 htmlentities($code, ENT_QUOTES)
2053 * Filter a given GMT timestamp (non Uni* stamp!) to make it look more
2054 * beatiful for web-based front-ends. If null is given a message id
2055 * null_timestamp will be resolved and returned.
2057 * @param $timestamp Timestamp to prepare (filter) for display
2058 * @return $readable A readable timestamp
2060 public function doFilterFormatTimestamp ($timestamp) {
2061 // Default value to return
2064 // Is the timestamp null?
2065 if (is_null($timestamp)) {
2066 // Get a message string
2067 $readable = $this->getLanguageInstance()->getMessage('null_timestamp');
2069 switch ($this->getLanguageInstance()->getLanguageCode()) {
2070 case 'de': // German format is a bit different to default
2071 // Split the GMT stamp up
2072 $dateTime = explode(' ', $timestamp );
2073 $dateArray = explode('-', $dateTime[0]);
2074 $timeArray = explode(':', $dateTime[1]);
2076 // Construct the timestamp
2077 $readable = sprintf($this->getConfigInstance()->getConfigEntry('german_date_time'),
2087 default: // Default is pass-through
2088 $readable = $timestamp;
2098 * Filter a given number into a localized number
2100 * @param $value The raw value from e.g. database
2101 * @return $localized Localized value
2103 public function doFilterFormatNumber ($value) {
2104 // Generate it from config and localize dependencies
2105 switch ($this->getLanguageInstance()->getLanguageCode()) {
2106 case 'de': // German format is a bit different to default
2107 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), ',', '.');
2110 default: // US, etc.
2111 $localized = number_format($value, $this->getConfigInstance()->getConfigEntry('decimals'), '.', ',');
2120 * "Getter" for databse entry
2122 * @return $entry An array with database entries
2123 * @throws NullPointerException If the database result is not found
2124 * @throws InvalidDatabaseResultException If the database result is invalid
2126 protected final function getDatabaseEntry () {
2127 // Is there an instance?
2128 if (!$this->getResultInstance() instanceof SearchableResult) {
2129 // Throw an exception here
2130 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2134 $this->getResultInstance()->rewind();
2136 // Do we have an entry?
2137 if ($this->getResultInstance()->valid() === false) {
2138 // @TODO Move the constant to e.g. BaseDatabaseResult when there is a non-cached database result available
2139 throw new InvalidDatabaseResultException(array($this, $this->getResultInstance()), CachedDatabaseResult::EXCEPTION_INVALID_DATABASE_RESULT);
2143 $this->getResultInstance()->next();
2146 $entry = $this->getResultInstance()->current();
2153 * Getter for field name
2155 * @param $fieldName Field name which we shall get
2156 * @return $fieldValue Field value from the user
2157 * @throws NullPointerException If the result instance is null
2159 public final function getField ($fieldName) {
2160 // Default field value
2163 // Get result instance
2164 $resultInstance = $this->getResultInstance();
2166 // Is this instance null?
2167 if (is_null($resultInstance)) {
2168 // Then the user instance is no longer valid (expired cookies?)
2169 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2172 // Get current array
2173 $fieldArray = $resultInstance->current();
2174 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($fieldName.':<pre>'.print_r($fieldArray, true).'</pre>');
2176 // Convert dashes to underscore
2177 $fieldName2 = self::convertDashesToUnderscores($fieldName);
2179 // Does the field exist?
2180 if ($this->isFieldSet($fieldName)) {
2182 $fieldValue = $fieldArray[$fieldName2];
2183 } elseif (defined('DEVELOPER')) {
2184 // Missing field entry, may require debugging
2185 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldArray<pre>=' . print_r($fieldArray, true) . '</pre>,fieldName=' . $fieldName . ' not found!');
2187 // Missing field entry, may require debugging
2188 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . __METHOD__ . ':' . __LINE__ . ']:fieldName=' . $fieldName . ' not found!');
2196 * Checks if given field is set
2198 * @param $fieldName Field name to check
2199 * @return $isSet Whether the given field name is set
2200 * @throws NullPointerException If the result instance is null
2202 public function isFieldSet ($fieldName) {
2203 // Get result instance
2204 $resultInstance = $this->getResultInstance();
2206 // Is this instance null?
2207 if (is_null($resultInstance)) {
2208 // Then the user instance is no longer valid (expired cookies?)
2209 throw new NullPointerException($this, self::EXCEPTION_IS_NULL_POINTER);
2212 // Get current array
2213 $fieldArray = $resultInstance->current();
2214 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('[' . $this->__toString() . ':' . __LINE__ . '] fieldName=' . $fieldName . ',fieldArray=<pre>'.print_r($fieldArray, true).'</pre>');
2216 // Convert dashes to underscore
2217 $fieldName = self::convertDashesToUnderscores($fieldName);
2220 $isSet = isset($fieldArray[$fieldName]);
2227 * Flushs all pending updates to the database layer
2231 public function flushPendingUpdates () {
2232 // Get result instance
2233 $resultInstance = $this->getResultInstance();
2235 // Do we have data to update?
2236 if ((is_object($resultInstance)) && ($resultInstance->ifDataNeedsFlush())) {
2237 // Get wrapper class name config entry
2238 $configEntry = $resultInstance->getUpdateInstance()->getWrapperConfigEntry();
2240 // Create object instance
2241 $wrapperInstance = DatabaseWrapperFactory::createWrapperByConfiguredName($configEntry);
2243 // Yes, then send the whole result to the database layer
2244 $wrapperInstance->doUpdateByResult($this->getResultInstance());
2249 * Outputs a deprecation warning to the developer.
2251 * @param $message The message we shall output to the developer
2253 * @todo Write a logging mechanism for productive mode
2255 public function deprecationWarning ($message) {
2256 // Is developer mode active?
2257 if (defined('DEVELOPER')) {
2258 // Debug instance is there?
2259 if (!is_null($this->getDebugInstance())) {
2260 // Output stub message
2261 self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($message);
2264 trigger_error($message . "<br />\n");
2268 // @TODO Finish this part!
2269 $this->partialStub('Developer mode inactive. Message:' . $message);
2274 * Checks whether the given PHP extension is loaded
2276 * @param $phpExtension The PHP extension we shall check
2277 * @return $isLoaded Whether the PHP extension is loaded
2279 public final function isPhpExtensionLoaded ($phpExtension) {
2281 $isLoaded = in_array($phpExtension, get_loaded_extensions());
2288 * "Getter" as a time() replacement but with milliseconds. You should use this
2289 * method instead of the encapsulated getimeofday() function.
2291 * @return $milliTime Timestamp with milliseconds
2293 public function getMilliTime () {
2294 // Get the time of day as float
2295 $milliTime = gettimeofday(true);
2302 * Idles (sleeps) for given milliseconds
2304 * @return $hasSlept Whether it goes fine
2306 public function idle ($milliSeconds) {
2307 // Sleep is fine by default
2310 // Idle so long with found function
2311 if (function_exists('time_sleep_until')) {
2312 // Get current time and add idle time
2313 $sleepUntil = $this->getMilliTime() + abs($milliSeconds) / 1000;
2315 // New PHP 5.1.0 function found, ignore errors
2316 $hasSlept = @time_sleep_until($sleepUntil);
2319 * My Sun station doesn't have that function even with latest PHP
2322 usleep($milliSeconds * 1000);
2329 * Converts a hexadecimal string, even with negative sign as first string to
2330 * a decimal number using BC functions.
2332 * This work is based on comment #86673 on php.net documentation page at:
2333 * <http://de.php.net/manual/en/function.dechex.php#86673>
2335 * @param $hex Hexadecimal string
2336 * @return $dec Decimal number
2338 protected function hex2dec ($hex) {
2339 // Convert to all lower-case
2340 $hex = strtolower($hex);
2342 // Detect sign (negative/positive numbers)
2344 if (substr($hex, 0, 1) == '-') {
2346 $hex = substr($hex, 1);
2349 // Decode the hexadecimal string into a decimal number
2351 for ($i = strlen($hex) - 1, $e = 1; $i >= 0; $i--, $e = bcmul($e, 16)) {
2352 $factor = self::$hexdec[substr($hex, $i, 1)];
2353 $dec = bcadd($dec, bcmul($factor, $e));
2356 // Return the decimal number
2357 return $sign . $dec;
2361 * Converts even very large decimal numbers, also signed, to a hexadecimal
2364 * This work is based on comment #97756 on php.net documentation page at:
2365 * <http://de.php.net/manual/en/function.hexdec.php#97756>
2367 * @param $dec Decimal number, even with negative sign
2368 * @param $maxLength Optional maximum length of the string
2369 * @return $hex Hexadecimal string
2371 protected function dec2hex ($dec, $maxLength = 0) {
2372 // maxLength can be zero or devideable by 2
2373 assert(($maxLength == 0) || (($maxLength % 2) == 0));
2375 // Detect sign (negative/positive numbers)
2382 // Encode the decimal number into a hexadecimal string
2385 $hex = self::$dechex[($dec % (2 ^ 4))] . $hex;
2387 } while ($dec >= 1);
2390 * Leading zeros are required for hex-decimal "numbers". In some
2391 * situations more leading zeros are wanted, so check for both
2394 if ($maxLength > 0) {
2395 // Prepend more zeros
2396 $hex = str_pad($hex, $maxLength, '0', STR_PAD_LEFT);
2397 } elseif ((strlen($hex) % 2) != 0) {
2398 // Only make string's length dividable by 2
2402 // Return the hexadecimal string
2403 return $sign . $hex;
2407 * Converts a ASCII string (0 to 255) into a decimal number.
2409 * @param $asc The ASCII string to be converted
2410 * @return $dec Decimal number
2412 protected function asc2dec ($asc) {
2413 // Convert it into a hexadecimal number
2414 $hex = bin2hex($asc);
2416 // And back into a decimal number
2417 $dec = $this->hex2dec($hex);
2424 * Converts a decimal number into an ASCII string.
2426 * @param $dec Decimal number
2427 * @return $asc An ASCII string
2429 protected function dec2asc ($dec) {
2430 // First convert the number into a hexadecimal string
2431 $hex = $this->dec2hex($dec);
2433 // Then convert it into the ASCII string
2434 $asc = $this->hex2asc($hex);
2441 * Converts a hexadecimal number into an ASCII string. Negative numbers
2444 * @param $hex Hexadecimal string
2445 * @return $asc An ASCII string
2447 protected function hex2asc ($hex) {
2448 // Check for length, it must be devideable by 2
2449 //* DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('hex='.$hex);
2450 assert((strlen($hex) % 2) == 0);
2454 for ($idx = 0; $idx < strlen($hex); $idx+=2) {
2455 // Get the decimal number of the chunk
2456 $part = hexdec(substr($hex, $idx, 2));
2458 // Add it to the final string
2462 // Return the final string
2467 * Checks whether the given encoded data was encoded with Base64
2469 * @param $encodedData Encoded data we shall check
2470 * @return $isBase64 Whether the encoded data is Base64
2472 protected function isBase64Encoded ($encodedData) {
2474 $isBase64 = (@base64_decode($encodedData, true) !== false);
2481 * Gets a cache key from Criteria instance
2483 * @param $criteriaInstance An instance of a Criteria class
2484 * @param $onlyKeys Only use these keys for a cache key
2485 * @return $cacheKey A cache key suitable for lookup/storage purposes
2487 protected function getCacheKeyByCriteria (Criteria $criteriaInstance, array $onlyKeys = array()) {
2489 $cacheKey = sprintf('%s@%s',
2490 $this->__toString(),
2491 $criteriaInstance->getCacheKey($onlyKeys)
2495 //* NOISY-DEBUG: */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput($this->__toString() . ': cacheKey=' . $cacheKey);
2500 * Getter for startup time in miliseconds
2502 * @return $startupTime Startup time in miliseconds
2504 protected function getStartupTime () {
2505 return self::$startupTime;
2509 * "Getter" for a printable currently execution time in nice braces
2511 * @return $executionTime Current execution time in nice braces
2513 protected function getPrintableExecutionTime () {
2514 // Caculate the execution time
2515 $executionTime = microtime(true) - $this->getStartupTime();
2517 // Pack it in nice braces
2518 $executionTime = sprintf('[ %01.5f ] ', $executionTime);
2521 return $executionTime;
2525 * Hashes a given string with a simple but stronger hash function (no salt)
2526 * and hex-encode it.
2528 * @param $str The string to be hashed
2529 * @return $hash The hash from string $str
2531 public static final function hash ($str) {
2532 // Hash given string with (better secure) hasher
2533 $hash = bin2hex(mhash(MHASH_SHA256, $str));
2540 * "Getter" for length of hash() output. This will be "cached" to speed up
2543 * @return $length Length of hash() output
2545 public static final function getHashLength () {
2547 if (is_null(self::$hashLength)) {
2548 // No, then hash a string and save its length.
2549 self::$hashLength = strlen(self::hash('abc123'));
2553 return self::$hashLength;
2557 * Checks whether the given number is really a number (only chars 0-9).
2559 * @param $num A string consisting only chars between 0 and 9
2560 * @param $castValue Whether to cast the value to double. Do only use this to secure numbers from Requestable classes.
2561 * @param $assertMismatch Whether to assert mismatches
2562 * @return $ret The (hopefully) secured numbered value
2564 public function bigintval ($num, $castValue = true, $assertMismatch = false) {
2565 // Filter all numbers out
2566 $ret = preg_replace('/[^0123456789]/', '', $num);
2569 if ($castValue === true) {
2570 // Cast to biggest numeric type
2571 $ret = (double) $ret;
2574 // Assert only if requested
2575 if ($assertMismatch === true) {
2576 // Has the whole value changed?
2577 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2585 * Checks whether the given hexadecimal number is really a hex-number (only chars 0-9,a-f).
2587 * @param $num A string consisting only chars between 0 and 9
2588 * @param $assertMismatch Whether to assert mismatches
2589 * @return $ret The (hopefully) secured hext-numbered value
2591 public function hexval ($num, $assertMismatch = false) {
2592 // Filter all numbers out
2593 $ret = preg_replace('/[^0123456789abcdefABCDEF]/', '', $num);
2595 // Assert only if requested
2596 if ($assertMismatch === true) {
2597 // Has the whole value changed?
2598 assert(('' . $ret . '' != '' . $num . '') && (!is_null($num)));
2606 * Checks whether start/end marker are set
2608 * @param $data Data to be checked
2609 * @return $isset Whether start/end marker are set
2611 public final function ifStartEndMarkersSet ($data) {
2613 $isset = ((substr($data, 0, strlen(BaseRawDataHandler::STREAM_START_MARKER)) == BaseRawDataHandler::STREAM_START_MARKER) && (substr($data, -1 * strlen(BaseRawDataHandler::STREAM_END_MARKER), strlen(BaseRawDataHandler::STREAM_END_MARKER)) == BaseRawDataHandler::STREAM_END_MARKER));
2615 // ... and return it
2620 * Determines if an element 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 * @param $element Element to check
2626 * @return $isset Whether the given key is set
2628 protected final function isGenericArrayElementSet ($keyGroup, $subGroup, $key, $element) {
2630 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2633 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2639 * Determines if a key is set in the generic array
2641 * @param $keyGroup Main group for the key
2642 * @param $subGroup Sub group for the key
2643 * @param $key Key to check
2644 * @return $isset Whether the given key is set
2646 protected final function isGenericArrayKeySet ($keyGroup, $subGroup, $key) {
2648 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2651 $isset = isset($this->genericArray[$keyGroup][$subGroup][$key]);
2659 * Determines if a group is set in the generic array
2661 * @param $keyGroup Main group
2662 * @param $subGroup Sub group
2663 * @return $isset Whether the given group is set
2665 protected final function isGenericArrayGroupSet ($keyGroup, $subGroup) {
2667 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
2670 $isset = isset($this->genericArray[$keyGroup][$subGroup]);
2677 * Getter for sub key group
2679 * @param $keyGroup Main key group
2680 * @param $subGroup Sub key group
2681 * @return $array An array with all array elements
2683 protected final function getGenericSubArray ($keyGroup, $subGroup) {
2685 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
2686 // No, then abort here
2687 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
2692 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',value=' . print_r($this->genericArray[$keyGroup][$subGroup], true));
2695 return $this->genericArray[$keyGroup][$subGroup];
2699 * Unsets a given key in generic array
2701 * @param $keyGroup Main group for the key
2702 * @param $subGroup Sub group for the key
2703 * @param $key Key to unset
2706 protected final function unsetGenericArrayKey ($keyGroup, $subGroup, $key) {
2708 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2711 unset($this->genericArray[$keyGroup][$subGroup][$key]);
2715 * Unsets a given element in generic array
2717 * @param $keyGroup Main group for the key
2718 * @param $subGroup Sub group for the key
2719 * @param $key Key to unset
2720 * @param $element Element to unset
2723 protected final function unsetGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
2725 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
2728 unset($this->genericArray[$keyGroup][$subGroup][$key][$element]);
2732 * Append a string to a given generic array key
2734 * @param $keyGroup Main group for the key
2735 * @param $subGroup Sub group for the key
2736 * @param $key Key to unset
2737 * @param $value Value to add/append
2740 protected final function appendStringToGenericArrayKey ($keyGroup, $subGroup, $key, $value, $appendGlue = '') {
2742 //* 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);
2744 // Is it already there?
2745 if ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2747 $this->genericArray[$keyGroup][$subGroup][$key] .= $appendGlue . (string) $value;
2750 $this->genericArray[$keyGroup][$subGroup][$key] = (string) $value;
2755 * Append a string to a given generic array element
2757 * @param $keyGroup Main group for the key
2758 * @param $subGroup Sub group for the key
2759 * @param $key Key to unset
2760 * @param $element Element to check
2761 * @param $value Value to add/append
2764 protected final function appendStringToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2766 //* 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);
2768 // Is it already there?
2769 if ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2771 $this->genericArray[$keyGroup][$subGroup][$key][$element] .= $appendGlue . (string) $value;
2774 $this->setStringGenericArrayElement($keyGroup, $subGroup, $key, $element, $value);
2779 * Sets a string in a given generic array element
2781 * @param $keyGroup Main group for the key
2782 * @param $subGroup Sub group for the key
2783 * @param $key Key to unset
2784 * @param $element Element to check
2785 * @param $value Value to add/append
2788 protected final function setStringGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value, $appendGlue = '') {
2790 //* 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);
2793 $this->genericArray[$keyGroup][$subGroup][$key][$element] = (string) $value;
2797 * Initializes given generic array group
2799 * @param $keyGroup Main group for the key
2800 * @param $subGroup Sub group for the key
2801 * @param $key Key to use
2802 * @param $forceInit Optionally force initialization
2805 protected final function initGenericArrayGroup ($keyGroup, $subGroup, $forceInit = false) {
2807 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',forceInit=' . intval($forceInit));
2809 // Is it already set?
2810 if (($forceInit === false) && ($this->isGenericArrayGroupSet($keyGroup, $subGroup))) {
2811 // Already initialized
2812 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' already initialized.');
2817 $this->genericArray[$keyGroup][$subGroup] = array();
2821 * Initializes given generic array key
2823 * @param $keyGroup Main group for the key
2824 * @param $subGroup Sub group for the key
2825 * @param $key Key to use
2826 * @param $forceInit Optionally force initialization
2829 protected final function initGenericArrayKey ($keyGroup, $subGroup, $key, $forceInit = false) {
2831 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',forceInit=' . intval($forceInit));
2833 // Is it already set?
2834 if (($forceInit === false) && ($this->isGenericArrayKeySet($keyGroup, $subGroup, $key))) {
2835 // Already initialized
2836 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' already initialized.');
2841 $this->genericArray[$keyGroup][$subGroup][$key] = array();
2845 * Initializes given generic array element
2847 * @param $keyGroup Main group for the key
2848 * @param $subGroup Sub group for the key
2849 * @param $key Key to use
2850 * @param $element Element to use
2851 * @param $forceInit Optionally force initialization
2854 protected final function initGenericArrayElement ($keyGroup, $subGroup, $key, $element, $forceInit = false) {
2856 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ',forceInit=' . intval($forceInit));
2858 // Is it already set?
2859 if (($forceInit === false) && ($this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element))) {
2860 // Already initialized
2861 trigger_error(__METHOD__ . ':keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' already initialized.');
2866 $this->genericArray[$keyGroup][$subGroup][$key][$element] = array();
2870 * Pushes an element to a generic key
2872 * @param $keyGroup Main group for the key
2873 * @param $subGroup Sub group for the key
2874 * @param $key Key to use
2875 * @param $value Value to add/append
2876 * @return $count Number of array elements
2878 protected final function pushValueToGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
2880 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
2883 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2885 $this->initGenericArrayKey($keyGroup, $subGroup, $key);
2889 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key], $value);
2892 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2893 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2898 * Pushes an element to a generic array element
2900 * @param $keyGroup Main group for the key
2901 * @param $subGroup Sub group for the key
2902 * @param $key Key to use
2903 * @param $element Element to check
2904 * @param $value Value to add/append
2905 * @return $count Number of array elements
2907 protected final function pushValueToGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
2909 //* 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));
2912 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
2914 $this->initGenericArrayElement($keyGroup, $subGroup, $key, $element);
2918 $count = array_push($this->genericArray[$keyGroup][$subGroup][$key][$element], $value);
2921 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2922 //* DEBUG: */ print(__METHOD__ . ': count=' . $count . PHP_EOL);
2927 * Pops an element from a generic group
2929 * @param $keyGroup Main group for the key
2930 * @param $subGroup Sub group for the key
2931 * @param $key Key to unset
2932 * @return $value Last "popped" value
2934 protected final function popGenericArrayElement ($keyGroup, $subGroup, $key) {
2936 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2939 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2941 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2946 $value = array_pop($this->genericArray[$keyGroup][$subGroup][$key]);
2949 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2950 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2955 * Shifts an element from a generic group
2957 * @param $keyGroup Main group for the key
2958 * @param $subGroup Sub group for the key
2959 * @param $key Key to unset
2960 * @return $value Last "popped" value
2962 protected final function shiftGenericArrayElement ($keyGroup, $subGroup, $key) {
2964 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
2967 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
2969 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' not found.');
2974 $value = array_shift($this->genericArray[$keyGroup][$subGroup][$key]);
2977 //* DEBUG: */ print(__METHOD__ . ': genericArray=' . print_r($this->genericArray[$keyGroup][$subGroup][$key], true));
2978 //* DEBUG: */ print(__METHOD__ . ': value[' . gettype($value) . ']=' . print_r($value, true) . PHP_EOL);
2983 * Count generic array group
2985 * @param $keyGroup Main group for the key
2986 * @return $count Count of given group
2988 protected final function countGenericArray ($keyGroup) {
2990 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
2993 if (!isset($this->genericArray[$keyGroup])) {
2995 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' not found.');
3000 $count = count($this->genericArray[$keyGroup]);
3003 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',count=' . $count);
3010 * Count generic array sub group
3012 * @param $keyGroup Main group for the key
3013 * @param $subGroup Sub group for the key
3014 * @return $count Count of given group
3016 protected final function countGenericArrayGroup ($keyGroup, $subGroup) {
3018 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3021 if (!$this->isGenericArrayGroupSet($keyGroup, $subGroup)) {
3023 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3028 $count = count($this->genericArray[$keyGroup][$subGroup]);
3031 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',count=' . $count);
3038 * Count generic array elements
3040 * @param $keyGroup Main group for the key
3041 * @param $subGroup Sub group for the key
3042 * @para $key Key to count
3043 * @return $count Count of given key
3045 protected final function countGenericArrayElements ($keyGroup, $subGroup, $key) {
3047 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3050 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3052 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' not found.');
3054 } elseif (!$this->isValidGenericArrayGroup($keyGroup, $subGroup)) {
3056 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ' is not an array.');
3061 $count = count($this->genericArray[$keyGroup][$subGroup][$key]);
3064 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',count=' . $count);
3071 * Getter for whole generic group array
3073 * @param $keyGroup Key group to get
3074 * @return $array Whole generic array group
3076 protected final function getGenericArray ($keyGroup) {
3078 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup);
3081 if (!isset($this->genericArray[$keyGroup])) {
3083 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ' does not exist.');
3088 return $this->genericArray[$keyGroup];
3092 * Setter for generic array key
3094 * @param $keyGroup Key group to get
3095 * @param $subGroup Sub group for the key
3096 * @param $key Key to unset
3097 * @param $value Mixed value from generic array element
3100 protected final function setGenericArrayKey ($keyGroup, $subGroup, $key, $value) {
3102 //* NOISY-DEBUG: */ if (!is_object($value)) $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',value[' . gettype($value) . ']=' . print_r($value, true));
3105 $this->genericArray[$keyGroup][$subGroup][$key] = $value;
3109 * Getter for generic array key
3111 * @param $keyGroup Key group to get
3112 * @param $subGroup Sub group for the key
3113 * @param $key Key to unset
3114 * @return $value Mixed value from generic array element
3116 protected final function getGenericArrayKey ($keyGroup, $subGroup, $key) {
3118 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3121 if (!$this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) {
3123 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ' does not exist.');
3128 return $this->genericArray[$keyGroup][$subGroup][$key];
3132 * Sets a value in given generic array key/element
3134 * @param $keyGroup Main group for the key
3135 * @param $subGroup Sub group for the key
3136 * @param $key Key to set
3137 * @param $element Element to set
3138 * @param $value Value to set
3141 protected final function setGenericArrayElement ($keyGroup, $subGroup, $key, $element, $value) {
3143 //* 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));
3146 $this->genericArray[$keyGroup][$subGroup][$key][$element] = $value;
3150 * Getter for generic array element
3152 * @param $keyGroup Key group to get
3153 * @param $subGroup Sub group for the key
3154 * @param $key Key to look for
3155 * @param $element Element to look for
3156 * @return $value Mixed value from generic array element
3158 protected final function getGenericArrayElement ($keyGroup, $subGroup, $key, $element) {
3160 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element);
3163 if (!$this->isGenericArrayElementSet($keyGroup, $subGroup, $key, $element)) {
3165 trigger_error(__METHOD__ . ': keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key . ',element=' . $element . ' does not exist.');
3170 return $this->genericArray[$keyGroup][$subGroup][$key][$element];
3174 * Checks if a given sub group is valid (array)
3176 * @param $keyGroup Key group to get
3177 * @param $subGroup Sub group for the key
3178 * @return $isValid Whether given sub group is valid
3180 protected final function isValidGenericArrayGroup ($keyGroup, $subGroup) {
3182 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup);
3185 $isValid = (($this->isGenericArrayGroupSet($keyGroup, $subGroup)) && (is_array($this->getGenericSubArray($keyGroup, $subGroup))));
3192 * Checks if a given key is valid (array)
3194 * @param $keyGroup Key group to get
3195 * @param $subGroup Sub group for the key
3196 * @param $key Key to check
3197 * @return $isValid Whether given sub group is valid
3199 protected final function isValidGenericArrayKey ($keyGroup, $subGroup, $key) {
3201 //* NOISY-DEBUG: */ $this->outputLine('[' . __METHOD__ . ':' . __LINE__ . '] keyGroup=' . $keyGroup . ',subGroup=' . $subGroup . ',key=' . $key);
3204 $isValid = (($this->isGenericArrayKeySet($keyGroup, $subGroup, $key)) && (is_array($this->getGenericArrayKey($keyGroup, $subGroup, $key))));
3211 * Initializes the web output instance
3215 protected function initWebOutputInstance () {
3216 // Get application instance
3217 $applicationInstance = Registry::getRegistry()->getInstance('app');
3219 // Init web output instance
3220 $outputInstance = ObjectFactory::createObjectByConfiguredName('output_class', array($applicationInstance));
3223 $this->setWebOutputInstance($outputInstance);
3227 * Translates boolean true to 'Y' and false to 'N'
3229 * @param $boolean Boolean value
3230 * @return $translated Translated boolean value
3232 public static final function translateBooleanToYesNo ($boolean) {
3233 // Make sure it is really boolean
3234 assert(is_bool($boolean));
3237 $translated = ($boolean === true) ? 'Y' : 'N';
3239 // ... and return it
3244 * Encodes raw data (almost any type) by "serializing" it and then pack it
3245 * into a "binary format".
3247 * @param $rawData Raw data (almost any type)
3248 * @return $encoded Encoded data
3250 protected function encodeData ($rawData) {
3251 // Make sure no objects or resources pass through
3252 assert(!is_object($rawData));
3253 assert(!is_resource($rawData));
3255 // First "serialize" it (json_encode() is faster than serialize())
3256 $encoded = $this->packString(json_encode($rawData));
3263 * Pack a string into a "binary format". Please execuse me that this is
3264 * widely undocumented. :-(
3266 * @param $str Unpacked string
3267 * @return $packed Packed string
3268 * @todo Improve documentation
3270 protected function packString ($str) {
3272 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('str=' . $str . ' - CALLED!');
3274 // First compress the string (gzcompress is okay)
3275 $str = gzcompress($str);
3280 // And start the "encoding" loop
3281 for ($idx = 0; $idx < strlen($str); $idx += $this->packingData[$this->archArrayElement]['step']) {
3283 for ($i = 0; $i < $this->packingData[$this->archArrayElement]['step']; $i++) {
3284 $factor = ($this->packingData[$this->archArrayElement]['step'] - 1 - $i);
3286 if (($idx + $i) <= strlen($str)) {
3287 $ord = ord(substr($str, ($idx + $i), 1));
3289 $add = $ord * pow(256, $factor);
3293 //print 'idx=' . $idx . ',i=' . $i . ',ord=' . $ord . ',factor=' . $factor . ',add=' . $add . ',big=' . $big . PHP_EOL;
3297 $l = ($big & $this->packingData[$this->archArrayElement]['left']) >>$this->packingData[$this->archArrayElement]['factor'];
3298 $r = $big & $this->packingData[$this->archArrayElement]['right'];
3300 $chunk = str_pad(pack($this->packingData[$this->archArrayElement]['format'], $l, $r), 8, '0', STR_PAD_LEFT);
3301 //* NOISY-DEBUG */ print 'big=' . $big . ',chunk('.strlen($chunk) . ')='.md5($chunk).PHP_EOL;
3307 //* NOISY-DEBUG */ self::createDebugInstance(__CLASS__, __LINE__)->debugOutput('packed=' . $packed . ' - EXIT!');
3312 * Creates a full-qualified file name (FQFN) for given file name by adding
3313 * a configured temporary file path to it.
3315 * @param $fileName Name for temporary file
3316 * @return $fqfn Full-qualified file name
3317 * @throw PathWriteProtectedException If the path in 'temp_file_path' is write-protected
3318 * @throws FileIoException If the file cannot be written
3320 protected static function createTempPathForFile ($fileName) {
3322 $basePath = FrameworkConfiguration::getSelfInstance()->getConfigEntry('temp_file_path');
3324 // Is the path writeable?
3325 if (!is_writable($basePath)) {
3326 // Path is write-protected
3327 throw new PathWriteProtectedException($fileName, self::EXCEPTION_PATH_CANNOT_BE_WRITTEN);
3331 $fqfn = $basePath . '/' . $fileName;
3334 if (!FrameworkBootstrap::isReachableFilePath($fqfn)) {
3336 throw new FileIoException($fqfn, self::EXCEPTION_FILE_NOT_REACHABLE);
3344 * "Getter" for a printable state name
3346 * @return $stateName Name of the node's state in a printable format
3348 public final function getPrintableState () {
3349 // Default is 'null'
3350 $stateName = 'null';
3352 // Get the state instance
3353 $stateInstance = $this->getStateInstance();
3355 // Is it an instance of Stateable?
3356 if ($stateInstance instanceof Stateable) {
3357 // Then use that state name
3358 $stateName = $stateInstance->getStateName();
3366 * Handles socket error for given socket resource and peer data. This method
3367 * validates $socketResource if it is a valid resource (see is_resource())
3368 * but assumes valid data in array $recipientData, except that
3369 * count($recipientData) is always 2.
3371 * @param $method Value of __METHOD__ from calling method
3372 * @param $line Value of __LINE__ from calling method
3373 * @param $socketResource A valid socket resource
3374 * @param $socketData A valid socket data array (0 = IP/file name, 1 = port)
3376 * @throws InvalidSocketException If $socketResource is no socket resource
3377 * @throws NoSocketErrorDetectedException If socket_last_error() gives zero back
3378 * @todo Move all this socket-related stuff into own class, most of it resides in BaseListener
3380 protected final function handleSocketError ($method, $line, $socketResource, array $socketData) {
3381 // This method handles only socket resources
3382 if (!is_resource($socketResource)) {
3383 // No resource, abort here
3384 throw new InvalidSocketException(array($this, $socketResource), BaseListener::EXCEPTION_INVALID_SOCKET);
3387 // Check socket array, 1st element is mostly IP address (or file name), 2nd is port number
3388 //* DEBUG-DIE: */ die(__METHOD__ . ':socketData=' . print_r($socketData, true));
3389 assert(isset($socketData[0]));
3390 assert(isset($socketData[1]));
3392 // Get error code for first validation (0 is not an error)
3393 $errorCode = socket_last_error($socketResource);
3395 // If the error code is zero, someone called this method without an error
3396 if ($errorCode == 0) {
3397 // No error detected (or previously cleared outside this method)
3398 throw new NoSocketErrorDetectedException(array($this, $socketResource), BaseListener::EXCEPTION_NO_SOCKET_ERROR);
3401 // Get handler (method) name
3402 $handlerName = $this->getSocketErrorHandlerFromCode($errorCode);
3404 // Call-back the error handler method
3405 call_user_func_array(array($this, $handlerName), array($socketResource, $socketData));
3407 // Finally clear the error because it has been handled
3408 socket_clear_error($socketResource);