public function options($options = null)
    {
        if (is_array($options)) {
            if ($this->options && $this->options instanceof Options) {
                $options = array_merge($this->options->toArray(), $options);
            }
            if (! Arr::has($options, 'priority')) {
                $options['priority'] = OptionsPriorities::normal;
            }
            $builder = new OptionsBuilder();
            $options = static::populateBuilder($builder, static::OPTIONS_MAP, $options);
        }
        if ($options instanceof Options) {
            $this->options = $options;
        } elseif ($options instanceof OptionsBuilder) {
            $this->options = $options->build();
        } elseif (! is_null($options)) {
            throw static::makeInvalidArgumentException(
                $options,
                'options',
                Options::class,
                OptionsBuilder::class
            );
        }

        return $this;
    }

public function options ( $ options = null ) { if ( is_array ( $ options ) ) { if ( $ this -> options && $ this -> options instanceof Options ) { $ options = array_merge ( $ this -> options -> toArray ( ) , $ options ) ; } if ( ! Arr :: has ( $ options , 'priority' ) ) { $ options [ 'priority' ] = OptionsPriorities :: normal ; } $ builder = new OptionsBuilder ( ) ; $ options = static :: populateBuilder ( $ builder , static :: OPTIONS_MAP , $ options ) ; } if ( $ options instanceof Options ) { $ this -> options = $ options ; } elseif ( $ options instanceof OptionsBuilder ) { $ this -> options = $ options -> build ( ) ; } elseif ( ! is_null ( $ options ) ) { throw static :: makeInvalidArgumentException ( $ options , 'options' , Options :: class , OptionsBuilder :: class ) ; } return $ this ; }

Set Options.

@param mixed $options
@return


public function notification($notification = null)
    {
        if (is_array($notification)) {
            if ($this->notification && $this->notification instanceof PayloadNotification) {
                $notification = array_merge($this->notification->toArray(), $notification);
            }
            $builder = new PayloadNotificationBuilder();
            $notification = static::populateBuilder($builder, static::NOTIFICATION_MAP, $notification);
        }
        if ($notification instanceof PayloadNotification) {
            $this->notification = $notification;
        } elseif ($notification instanceof PayloadNotificationBuilder) {
            $this->notification = $notification->build();
        } elseif (! is_null($notification)) {
            throw static::makeInvalidArgumentException(
                $notification,
                'notification',
                PayloadNotification::class,
                PayloadNotificationBuilder::class
            );
        }

        return $this;
    }

public function notification ( $ notification = null ) { if ( is_array ( $ notification ) ) { if ( $ this -> notification && $ this -> notification instanceof PayloadNotification ) { $ notification = array_merge ( $ this -> notification -> toArray ( ) , $ notification ) ; } $ builder = new PayloadNotificationBuilder ( ) ; $ notification = static :: populateBuilder ( $ builder , static :: NOTIFICATION_MAP , $ notification ) ; } if ( $ notification instanceof PayloadNotification ) { $ this -> notification = $ notification ; } elseif ( $ notification instanceof PayloadNotificationBuilder ) { $ this -> notification = $ notification -> build ( ) ; } elseif ( ! is_null ( $ notification ) ) { throw static :: makeInvalidArgumentException ( $ notification , 'notification' , PayloadNotification :: class , PayloadNotificationBuilder :: class ) ; } return $ this ; }

Set Notification.

@param  mixed $notification
@return $this


public function data($data = null)
    {
        if (is_array($data)) {
            if ($this->data && $this->data instanceof PayloadData) {
                $data = array_merge($this->data->toArray(), $data);
            }
            $data = (new PayloadDataBuilder())->setData($data);
        }

        if ($data instanceof PayloadData) {
            $this->data = $data;
        } elseif ($data instanceof PayloadDataBuilder) {
            $this->data = $data->build();
        } elseif (! is_null($data)) {
            throw static::makeInvalidArgumentException(
                $data,
                'data',
                PayloadData::class,
                PayloadDataBuilder::class
            );
        }

        return $this;
    }

public function data ( $ data = null ) { if ( is_array ( $ data ) ) { if ( $ this -> data && $ this -> data instanceof PayloadData ) { $ data = array_merge ( $ this -> data -> toArray ( ) , $ data ) ; } $ data = ( new PayloadDataBuilder ( ) ) -> setData ( $ data ) ; } if ( $ data instanceof PayloadData ) { $ this -> data = $ data ; } elseif ( $ data instanceof PayloadDataBuilder ) { $ this -> data = $ data -> build ( ) ; } elseif ( ! is_null ( $ data ) ) { throw static :: makeInvalidArgumentException ( $ data , 'data' , PayloadData :: class , PayloadDataBuilder :: class ) ; } return $ this ; }

Set Data.

@param mixed $data
@return $this


private function encodeCDATA($string) {
		$string = str_replace(self::CDATA_END, self::CDATA_EMBEDDED_END, $string);
		return self::CDATA_START . $string . self::CDATA_END;
	}

private function encodeCDATA ( $ string ) { $ string = str_replace ( self :: CDATA_END , self :: CDATA_EMBEDDED_END , $ string ) ; return self :: CDATA_START . $ string . self :: CDATA_END ; }

Encases a string in CDATA tags, and escapes any existing CDATA end
tags already present in the string.
@param string $string

Encases a string in CDATA tags and escapes any existing CDATA end tags already present in the string .


public function getNonAuthenticationUrl(
        $action,
        \FACTFinder\Util\Parameters $parameters
    ) {
        $configuration = $this->configuration;

        $this->ensureChannelParameter($parameters);

        $url = $this->buildAddress($action)
             . (count($parameters) ? '?' : '') . $parameters->toJavaQueryString();

        return $url;
    }

public function getNonAuthenticationUrl ( $ action , \ FACTFinder \ Util \ Parameters $ parameters ) { $ configuration = $ this -> configuration ; $ this -> ensureChannelParameter ( $ parameters ) ; $ url = $ this -> buildAddress ( $ action ) . ( count ( $ parameters ) ? '?' : '' ) . $ parameters -> toJavaQueryString ( ) ; return $ url ; }

Get URL without authentication data.
Note that this method may set a channel parameter if there is none
already.

@param string $action The action to be targeted on the FACT-Finder
server.
@param FACTFinder\Util\Parameters $parameters The parameters object from
which to build the URL.

@return string The full URL.

Get URL without authentication data . Note that this method may set a channel parameter if there is none already .


public function getAuthenticationUrl(
        $action,
        \FACTFinder\Util\Parameters $parameters
    ) {
        $this->ensureChannelParameter($parameters);

        $c = $this->configuration;
        if ($c->isAdvancedAuthenticationType())
            return $this->getAdvancedAuthenticationUrl($action, $parameters);
        else if ($c->isSimpleAuthenticationType())
            return $this->getSimpleAuthenticationUrl($action, $parameters);
        else if ($c->isHttpAuthenticationType())
            return $this->getHttpAuthenticationUrl($action, $parameters);
        else
            throw new \Exception('Invalid authentication type configured.');
    }

Returns a full URL with authentication data. The type of authentication
is determined from the configuration.
Note that this method may set a channel parameter if there is none
already.

@param string $action The action to be targeted on the FACT-Finder
server.
@param FACTFinder\Util\Parameters $parameters The parameters object from
which to build the URL.

@return string The full URL.

@throws Exception if no valid authentication type was configured.

Returns a full URL with authentication data . The type of authentication is determined from the configuration . Note that this method may set a channel parameter if there is none already .


protected function getAdvancedAuthenticationUrl(
        $action,
        \FACTFinder\Util\Parameters $parameters
    ) {
        $configuration = $this->configuration;

        $ts         = time() . '000'; //milliseconds needed
        $prefix     = $configuration->getAuthenticationPrefix();
        $postfix    = $configuration->getAuthenticationPostfix();
        $hashedPW   = md5($prefix
                    . $ts
                    . md5($configuration->getPassword())
                    . $postfix);
        $authenticationParameters = 'timestamp=' . $ts
                                  . '&username=' . $configuration->getUserName()
                                  . '&password=' . $hashedPW;

        $url = $this->buildAddress($action)
             . '?' . $parameters->toJavaQueryString()
             . (count($parameters) ? '&' : '') . $authenticationParameters;

        $this->log->info("Request Url: " . $url);
        return $url;
    }

protected
function
getAdvancedAuthenticationUrl
(
$
action
,
\
FACTFinder
\
Util
\
Parameters
$
parameters
)
{
$
configuration
=
$
this
->
configuration
;
$
ts
=
time
(
)
.
'000'
;
//milliseconds needed
$
prefix
=
$
configuration
->
getAuthenticationPrefix
(
)
;
$
postfix
=
$
configuration
->
getAuthenticationPostfix
(
)
;
$
hashedPW
=
md5
(
$
prefix
.
$
ts
.
md5
(
$
configuration
->
getPassword
(
)
)
.
$
postfix
)
;
$
authenticationParameters
=
'timestamp='
.
$
ts
.
'&username='
.
$
configuration
->
getUserName
(
)
.
'&password='
.
$
hashedPW
;
$
url
=
$
this
->
buildAddress
(
$
action
)
.
'?'
.
$
parameters
->
toJavaQueryString
(
)
.
(
count
(
$
parameters
)
'&'
:
''
)
.
$
authenticationParameters
;
$
this
->
log
->
info
(
"Request Url: "
.
$
url
)
;
return
$
url
;
}

Get URL with advanced authentication encryption.

@param string $action The action to be targeted on the FACT-Finder
server.
@param FACTFinder\Util\Parameters $parameters The parameters object from
which to build the URL.

@return string The full URL.

Get URL with advanced authentication encryption .


protected function getSimpleAuthenticationUrl(
        $action,
        \FACTFinder\Util\Parameters $parameters
    ) {
        $configuration = $this->configuration;

        $ts = time() . '000'; //milliseconds needed but won't be considered
        $authenticationParameters = "timestamp=" . $ts
                        . '&username=' . $configuration->getUserName()
                        . '&password=' . md5($configuration->getPassword());

        $url = $this->buildAddress($action)
             . '?' . $parameters->toJavaQueryString()
             . (count($parameters) ? '&' : '') . $authenticationParameters;

        $this->log->info("Request Url: " . $url);
        return $url;
    }

Get URL with simple authentication encryption.

@param string $action The action to be targeted on the FACT-Finder
server.
@param FACTFinder\Util\Parameters $parameters The parameters object from
which to build the URL.

@return string The full URL.

Get URL with simple authentication encryption .


protected function getHttpAuthenticationUrl(
        $action,
        \FACTFinder\Util\Parameters $parameters
    ) {
        $configuration = $this->configuration;

        $authentication = sprintf(
            '%s:%s@',
            $configuration->getUserName(),
            $configuration->getPassword()
        );
        if ($authentication == ':@') $authentication = '';

        $url = $this->buildAddress($action, true)
             . (count($parameters) ? '?' : '') . $parameters->toJavaQueryString();

        $this->log->info("Request Url: " . $url);
        return $url;
    }

protected
function
getHttpAuthenticationUrl
(
$
action
,
\
FACTFinder
\
Util
\
Parameters
$
parameters
)
{
$
configuration
=
$
this
->
configuration
;
$
authentication
=
sprintf
(
'%s:%s@'
,
$
configuration
->
getUserName
(
)
,
$
configuration
->
getPassword
(
)
)
;
if
(
$
authentication
==
':@'
)
$
authentication
=
''
;
$
url
=
$
this
->
buildAddress
(
$
action
,
true
)
.
(
count
(
$
parameters
)
'?'
:
''
)
.
$
parameters
->
toJavaQueryString
(
)
;
$
this
->
log
->
info
(
"Request Url: "
.
$
url
)
;
return
$
url
;
}

Get URL with HTTP authentication.

@param string $action The action to be targeted on the FACT-Finder
server.
@param FACTFinder\Util\Parameters $parameters The parameters object from
which to build the URL.

@return string The full URL.


protected function ensureChannelParameter($parameters) {
        if ((!isset($parameters['channel'])
            || $parameters['channel'] == '')
            && $this->configuration->getChannel() != ''
        ) {
            $parameters['channel'] = $this->configuration->getChannel();
        }
    }

protected function ensureChannelParameter ( $ parameters ) { if ( ( ! isset ( $ parameters [ 'channel' ] ) || $ parameters [ 'channel' ] == '' ) && $ this -> configuration -> getChannel ( ) != '' ) { $ parameters [ 'channel' ] = $ this -> configuration -> getChannel ( ) ; } }

If no channel is set, try to fill it from configuration data.

@param FACTFinder\Util\Parameters $parameters The parameters object to
check.

If no channel is set try to fill it from configuration data .


public function setProductID($productID)
    {
        $parameters = $this->request->getParameters();
        $parameters['id'] = $productID;
        $this->upToDate = false;
    }

public function setProductID ( $ productID ) { $ parameters = $ this -> request -> getParameters ( ) ; $ parameters [ 'id' ] = $ productID ; $ this -> upToDate = false ; }

Set one product IDs to get similar records for.

@param string $productID

Set one product IDs to get similar records for .


public function getSimilarAttributes()
    {
        if (is_null($this->similarAttributes)
            || !$this->upToDate
        ) {
            $this->similarAttributes = $this->createSimilarAttributes();
            $this->upToDate = true;
        }

        return $this->similarAttributes;
    }

public function getSimilarAttributes ( ) { if ( is_null ( $ this -> similarAttributes ) || ! $ this -> upToDate ) { $ this -> similarAttributes = $ this -> createSimilarAttributes ( ) ; $ this -> upToDate = true ; } return $ this -> similarAttributes ; }

Returns the attributes based on which similar records are determined as
well as the source product's values of those attributes. If no ID has
been set, there will be a warning raised and an empty array will be
returned.

@return mixed[] Attribute names as keys and attribute values as values.

Returns the attributes based on which similar records are determined as well as the source product s values of those attributes . If no ID has been set there will be a warning raised and an empty array will be returned .


public function getSimilarRecords()
    {
        if (is_null($this->similarRecords)
            || !$this->upToDate
        ) {
            $this->request->resetLoaded();
            $this->similarRecords = $this->createSimilarRecords();
            $this->upToDate = true;
        }

        return $this->similarRecords;
    }

public function getSimilarRecords ( ) { if ( is_null ( $ this -> similarRecords ) || ! $ this -> upToDate ) { $ this -> request -> resetLoaded ( ) ; $ this -> similarRecords = $ this -> createSimilarRecords ( ) ; $ this -> upToDate = true ; } return $ this -> similarRecords ; }

Returns similar records for the ID previously specified. If no ID has
been set, there will be a warning raised and an empty result will be
returned.

@return \FACTFinder\Data\Result

Returns similar records for the ID previously specified . If no ID has been set there will be a warning raised and an empty result will be returned .


protected function write($string) {
		// Lazy file open
		if(!isset($this->fp)) {
			if ($this->openFile() === false) {
				return; // Do not write if file open failed.
			}
		}

		if ($this->locking) {
			$this->writeWithLocking($string);
		} else {
			$this->writeWithoutLocking($string);
		}
	}

protected
function
write
(
$
string
)
{
// Lazy file open
if
(
!
isset
(
$
this
->
fp
)
)
{
if
(
$
this
->
openFile
(
)
===
false
)
{
return
;
// Do not write if file open failed.
}
}
if
(
$
this
->
locking
)
{
$
this
->
writeWithLocking
(
$
string
)
;
}
else
{
$
this
->
writeWithoutLocking
(
$
string
)
;
}
}

Writes a string to the target file. Opens file if not already open.
@param string $string Data to write.

Writes a string to the target file . Opens file if not already open .


public static function autoload($className) {
		if(isset(self::$classes[$className])) {
			include dirname(__FILE__) . self::$classes[$className];
		}
	}

public static function autoload ( $ className ) { if ( isset ( self :: $ classes [ $ className ] ) ) { include dirname ( __FILE__ ) . self :: $ classes [ $ className ] ; } }

Loads a class.
@param string $className The name of the class to load.


public function setTarget($target) {
		$value = trim($target);
		if ($value == self::STDOUT || strtoupper($value) == 'STDOUT') {
			$this->target = self::STDOUT;
		} elseif ($value == self::STDERR || strtoupper($value) == 'STDERR') {
			$this->target = self::STDERR;
		} else {
			$target = var_export($target);
			$this->warn("Invalid value given for 'target' property: [$target]. Property not set.");
		}
	}

Sets the 'target' parameter.
@param string $target


public function triggerDataImport($download = false)
    {
        //this function changes parameters, action, ... so reload of response is neccessary
        $this->request->resetLoaded();

        $this->request->setAction('Import.ff');

        $this->parameters['download'] = $download ? 'true' : 'false';

        // TODO: Parse the response XML into some nice domain object.
        return $this->getResponseContent();
    }

Trigger a search data import.

@param bool $download If true, update import files prior to import.


public function triggerSuggestImport($download = false)
    {
        //this function changes parameters, action, ... so reload of response is neccessary
        $this->request->resetLoaded();

        $this->request->setAction('Import.ff');

        $this->parameters['download'] = $download ? 'true' : 'false';
        $this->parameters['type'] = 'suggest';

        $report = $this->getResponseContent();

        // Clean up for next import
        unset($this->parameters['type']);

        // TODO: Parse the response XML into some nice domain object.
        return $report;
    }

Trigger a suggest data import.

@param bool $download If true, update import files prior to import.


protected function applyParameterMappings($parameters, $mappingRules)
    {
        foreach ($mappingRules as $k => $v)
        {
            if ($k != $v && isset($parameters[$k]))
            {
                $parameters[$v] = $parameters[$k];
                unset($parameters[$k]);
            }
        }
    }

protected function applyParameterMappings ( $ parameters , $ mappingRules ) { foreach ( $ mappingRules as $ k => $ v ) { if ( $ k != $ v && isset ( $ parameters [ $ k ] ) ) { $ parameters [ $ v ] = $ parameters [ $ k ] ; unset ( $ parameters [ $ k ] ) ; } } }

Changes the keys in a Parameters object according to the given mapping
rules.
@param Parameters $parameters Parameters to be modified.
@param string[] $mappingRules Associative array of mapping rules.
Parameter names will be mapped from keys to values of this array.

Changes the keys in a Parameters object according to the given mapping rules .


protected function ensureChannelParameter($parameters)
    {
        if (!isset($parameters['channel']) || strlen($parameters['channel']) == 0)
            $parameters['channel'] = $this->configuration->getChannel();
    }

protected function ensureChannelParameter ( $ parameters ) { if ( ! isset ( $ parameters [ 'channel' ] ) || strlen ( $ parameters [ 'channel' ] ) == 0 ) $ parameters [ 'channel' ] = $ this -> configuration -> getChannel ( ) ; }

Ensures that the passed parameters object has a "channel" parameter by
adding one if necessary.
@param Parameters $parameters Parameters to be modifier.

Ensures that the passed parameters object has a channel parameter by adding one if necessary .


protected function addRequiredParameters($parameters, $requireRules)
    {
        foreach ($requireRules as $k => $v)
            if (!isset($parameters[$k]))
                $parameters[$k] = $v;
    }

protected function addRequiredParameters ( $ parameters , $ requireRules ) { foreach ( $ requireRules as $ k => $ v ) if ( ! isset ( $ parameters [ $ k ] ) ) $ parameters [ $ k ] = $ v ; }

Adds keys to an array of parameters according to the given require rules.
@param Parameters $parameters Parameters to be modified.
@param string[] $ignoreRules Array of required parameters. The keys are
the names of the required parameter, the values are default values
to be used if the parameter is not present.

Adds keys to an array of parameters according to the given require rules .


public static function add(LoggerAppender $appender) {
		$name = $appender->getName();

		if(empty($name)) {
			trigger_error('log4php: Cannot add unnamed appender to pool.', E_USER_WARNING);
			return;
		}

		if (isset(self::$appenders[$name])) {
			trigger_error("log4php: Appender [$name] already exists in pool. Overwriting existing appender.", E_USER_WARNING);
		}

		self::$appenders[$name] = $appender;
	}

Adds an appender to the pool.
The appender must be named for this operation.
@param LoggerAppender $appender

Adds an appender to the pool . The appender must be named for this operation .


public static function get($name) {
		return isset(self::$appenders[$name]) ? self::$appenders[$name] : null;
	}

public static function get ( $ name ) { return isset ( self :: $ appenders [ $ name ] ) ? self :: $ appenders [ $ name ] : null ; }

Retrieves an appender from the pool by name.
@param string $name Name of the appender to retrieve.
@return LoggerAppender The named appender or NULL if no such appender
exists in the pool.

Retrieves an appender from the pool by name .


public function trace($message, $throwable = null) {
		$this->log(LoggerLevel::getLevelTrace(), $message, $throwable);
	}

public function trace ( $ message , $ throwable = null ) { $ this -> log ( LoggerLevel :: getLevelTrace ( ) , $ message , $ throwable ) ; }

Log a message object with the TRACE level.

@param mixed $message message
@param Exception $throwable Optional throwable information to include
in the logging event.

Log a message object with the TRACE level .


public function debug($message, $throwable = null) {
		$this->log(LoggerLevel::getLevelDebug(), $message, $throwable);
	}

public function debug ( $ message , $ throwable = null ) { $ this -> log ( LoggerLevel :: getLevelDebug ( ) , $ message , $ throwable ) ; }

Log a message object with the DEBUG level.

@param mixed $message message
@param Exception $throwable Optional throwable information to include
in the logging event.

Log a message object with the DEBUG level .


public function warn($message, $throwable = null) {
		$this->log(LoggerLevel::getLevelWarn(), $message, $throwable);
	}

public function warn ( $ message , $ throwable = null ) { $ this -> log ( LoggerLevel :: getLevelWarn ( ) , $ message , $ throwable ) ; }

Log a message with the WARN level.

@param mixed $message message
@param Exception $throwable Optional throwable information to include
in the logging event.


public function log(LoggerLevel $level, $message, $throwable = null) {
		if($this->isEnabledFor($level)) {
			$event = new LoggerLoggingEvent($this->fqcn, $this, $level, $message, null, $throwable);
			$this->callAppenders($event);
		}

		// Forward the event upstream if additivity is turned on
		if(isset($this->parent) && $this->getAdditivity()) {

			// Use the event if already created
			if (isset($event)) {
				$this->parent->logEvent($event);
			} else {
				$this->parent->log($level, $message, $throwable);
			}
		}
	}

Log a message using the provided logging level.

@param LoggerLevel $level The logging level.
@param mixed $message Message to log.
@param Exception $throwable Optional throwable information to include
in the logging event.

Log a message using the provided logging level .


public function logEvent(LoggerLoggingEvent $event) {
		if($this->isEnabledFor($event->getLevel())) {
			$this->callAppenders($event);
		}

		// Forward the event upstream if additivity is turned on
		if(isset($this->parent) && $this->getAdditivity()) {
			$this->parent->logEvent($event);
		}
	}

Logs an already prepared logging event object.
@param LoggerLoggingEvent $event

Logs an already prepared logging event object .


public function forcedLog($fqcn, $throwable, LoggerLevel $level, $message) {
		$event = new LoggerLoggingEvent($fqcn, $this, $level, $message, null, $throwable);
		$this->callAppenders($event);

		// Forward the event upstream if additivity is turned on
		if(isset($this->parent) && $this->getAdditivity()) {
			$this->parent->logEvent($event);
		}
	}

This method creates a new logging event and logs the event without
further checks.

It should not be called directly. Use {@link trace()}, {@link debug()},
{@link info()}, {@link warn()}, {@link error()} and {@link fatal()}
wrappers.

@param string $fqcn Fully qualified class name of the Logger
@param Exception $throwable Optional throwable information to include
in the logging event.
@param LoggerLevel $level log level
@param mixed $message message to log

This method creates a new logging event and logs the event without further checks .


public function removeAppender($appender) {
		if($appender instanceof LoggerAppender) {
			$appender->close();
			unset($this->appenders[$appender->getName()]);
		} else if (is_string($appender) and isset($this->appenders[$appender])) {
			$this->appenders[$appender]->close();
			unset($this->appenders[$appender]);
		}
	}

public function removeAppender ( $ appender ) { if ( $ appender instanceof LoggerAppender ) { $ appender -> close ( ) ; unset ( $ this -> appenders [ $ appender -> getName ( ) ] ) ; } else if ( is_string ( $ appender ) and isset ( $ this -> appenders [ $ appender ] ) ) { $ this -> appenders [ $ appender ] -> close ( ) ; unset ( $ this -> appenders [ $ appender ] ) ; } }

Remove the appender passed as parameter form the Logger.
@param mixed $appender an appender name or a {@link LoggerAppender} instance.

Remove the appender passed as parameter form the Logger .


public function getEffectiveLevel() {
		for($logger = $this; $logger !== null; $logger = $logger->getParent()) {
			if($logger->getLevel() !== null) {
				return $logger->getLevel();
			}
		}
	}

public function getEffectiveLevel ( ) { for ( $ logger = $ this ; $ logger !== null ; $ logger = $ logger -> getParent ( ) ) { if ( $ logger -> getLevel ( ) !== null ) { return $ logger -> getLevel ( ) ; } } }

Starting from this Logger, search the Logger hierarchy for a non-null level and return it.
@see LoggerLevel
@return LoggerLevel or null

Starting from this Logger search the Logger hierarchy for a non - null level and return it .


public static function getHierarchy() {
		if(!isset(self::$hierarchy)) {
			self::$hierarchy = new LoggerHierarchy(new LoggerRoot());
		}
		return self::$hierarchy;
	}

public static function getHierarchy ( ) { if ( ! isset ( self :: $ hierarchy ) ) { self :: $ hierarchy = new LoggerHierarchy ( new LoggerRoot ( ) ) ; } return self :: $ hierarchy ; }

Returns the hierarchy used by this Logger.

Caution: do not use this hierarchy unless you have called initialize().
To get Loggers, use the Logger::getLogger and Logger::getRootLogger
methods instead of operating on on the hierarchy directly.

@return LoggerHierarchy

Returns the hierarchy used by this Logger .


public static function getLogger($name) {
		if(!self::isInitialized()) {
			self::configure();
		}
		return self::getHierarchy()->getLogger($name);
	}

public static function getLogger ( $ name ) { if ( ! self :: isInitialized ( ) ) { self :: configure ( ) ; } return self :: getHierarchy ( ) -> getLogger ( $ name ) ; }

Returns a Logger by name. If it does not exist, it will be created.

@param string $name The logger name
@return Logger

Returns a Logger by name . If it does not exist it will be created .


public static function resetConfiguration() {
		self::getHierarchy()->resetConfiguration();
		self::getHierarchy()->clear(); // TODO: clear or not?
		self::$initialized = false;
	}

public
static
function
resetConfiguration
(
)
{
self
::
getHierarchy
(
)
->
resetConfiguration
(
)
;
self
::
getHierarchy
(
)
->
clear
(
)
;
// TODO: clear or not?
self
::
$
initialized
=
false
;
}

Destroy configurations for logger definitions


public static function configure($configuration = null, $configurator = null) {
		self::resetConfiguration();
		$configurator = self::getConfigurator($configurator);
		$configurator->configure(self::getHierarchy(), $configuration);
		self::$initialized = true;
	}

public static function configure ( $ configuration = null , $ configurator = null ) { self :: resetConfiguration ( ) ; $ configurator = self :: getConfigurator ( $ configurator ) ; $ configurator -> configure ( self :: getHierarchy ( ) , $ configuration ) ; self :: $ initialized = true ; }

Configures log4php.

This method needs to be called before the first logging event has
occured. If this method is not called before then the default
configuration will be used.

@param string|array $configuration Either a path to the configuration
file, or a configuration array.

@param string|LoggerConfigurator $configurator A custom
configurator class: either a class name (string), or an object which
implements the LoggerConfigurator interface. If left empty, the default
configurator implementation will be used.


private static function getConfigurator($configurator = null) {
		if ($configurator === null) {
			return new LoggerConfiguratorDefault();
		}

		if (is_object($configurator)) {
			if ($configurator instanceof LoggerConfigurator) {
				return $configurator;
			} else {
				trigger_error("log4php: Given configurator object [$configurator] does not implement the LoggerConfigurator interface. Reverting to default configurator.", E_USER_WARNING);
				return new LoggerConfiguratorDefault();
			}
		}

		if (is_string($configurator)) {
			if (!class_exists($configurator)) {
				trigger_error("log4php: Specified configurator class [$configurator] does not exist. Reverting to default configurator.", E_USER_WARNING);
				return new LoggerConfiguratorDefault();
			}

			$instance = new $configurator();

			if (!($instance instanceof LoggerConfigurator)) {
				trigger_error("log4php: Specified configurator class [$configurator] does not implement the LoggerConfigurator interface. Reverting to default configurator.", E_USER_WARNING);
				return new LoggerConfiguratorDefault();
			}

			return $instance;
		}

		trigger_error("log4php: Invalid configurator specified. Expected either a string or a LoggerConfigurator instance. Reverting to default configurator.", E_USER_WARNING);
		return new LoggerConfiguratorDefault();
	}

Creates a logger configurator instance based on the provided
configurator class. If no class is given, returns an instance of
the default configurator.

@param string|LoggerConfigurator $configurator The configurator class
or LoggerConfigurator instance.

Creates a logger configurator instance based on the provided configurator class . If no class is given returns an instance of the default configurator .


public function setRecordCount($recordCount)
    {
        $parameters = $this->request->getParameters();
        if (is_numeric($recordCount)
            && (int)$recordCount == (float)$recordCount // Is integer?
            && $recordCount > 0
        ) {
            $parameters['maxResults'] = $recordCount;
        }
        else
        {
            unset($parameters['maxResults']);
        }
        // Make sure that the recommendations are fetched again. In theory,
        // we only have to do this when recordCount increases.
        $this->upToDate = false;
    }

Set the maximum amount of recommendations to be fetched.

@param int $recordCount The number of records to be fetched. Something
else than a positive integer is passed, the record count will be
unlimited (or determined by FACT-Finder).

Set the maximum amount of recommendations to be fetched .


public function addProductIDs($productIDs)
    {
        $parameters = $this->request->getParameters();
        $parameters->add('id', $productIDs);
        $this->upToDate = false;
    }

public function addProductIDs ( $ productIDs ) { $ parameters = $ this -> request -> getParameters ( ) ; $ parameters -> add ( 'id' , $ productIDs ) ; $ this -> upToDate = false ; }

Add one or multiple product IDs to base recommendation on, in addition to
any IDs previously set.

@param string|string[] $productIDs One or more product IDs.

Add one or multiple product IDs to base recommendation on in addition to any IDs previously set .


public function getRecommendations()
    {
        if (is_null($this->recommendations)
            || !$this->upToDate
        ) {
            $this->request->resetLoaded();
            $this->recommendations = $this->createRecommendations();
            $this->upToDate = true;
        }

        return $this->recommendations;
    }

public function getRecommendations ( ) { if ( is_null ( $ this -> recommendations ) || ! $ this -> upToDate ) { $ this -> request -> resetLoaded ( ) ; $ this -> recommendations = $ this -> createRecommendations ( ) ; $ this -> upToDate = true ; } return $ this -> recommendations ; }

Returns recommendations for IDs previously specified. If no IDs have been
set, there will be a warning raised and an empty result will be returned.

@return \FACTFinder\Data\Result

Returns recommendations for IDs previously specified . If no IDs have been set there will be a warning raised and an empty result will be returned .


public function trackClick(
        $id,
        $query,
        $pos,
        $masterId = null,
        $sid = null,
        $cookieId = null,
        $origPos = -1,
        $page = 1,
        $simi = 100.0,
        $title = '',
        $pageSize = 12,
        $origPageSize = -1,
        $userId = null,
        $campaign = null,
        $instoreAds = false
    ) {
        $this->setupClickTracking($id, $query, $pos, $masterId, $sid, $cookieId, $origPos, $page,
                                  $simi, $title, $pageSize, $origPageSize, $userId, $campaign, $instoreAds);
        return $this->applyTracking();
    }

public function trackClick ( $ id , $ query , $ pos , $ masterId = null , $ sid = null , $ cookieId = null , $ origPos = - 1 , $ page = 1 , $ simi = 100.0 , $ title = '' , $ pageSize = 12 , $ origPageSize = - 1 , $ userId = null , $ campaign = null , $ instoreAds = false ) { $ this -> setupClickTracking ( $ id , $ query , $ pos , $ masterId , $ sid , $ cookieId , $ origPos , $ page , $ simi , $ title , $ pageSize , $ origPageSize , $ userId , $ campaign , $ instoreAds ) ; return $ this -> applyTracking ( ) ; }

Track a detail click on a product.

@param string $id tracking id of product (see field with the role "Product number for tracking")
@param string $sid session id (if empty, then try to set using the function session_id() )
@param string $query query which led to the product
@param int $pos position of product in the search result
@param string $masterId master id of the product (see field with the role "Master article number")
@param string $cookieId cookie id (optional)
@param int $origPos original position of product in the search result. this data is delivered by FACT-Finder (optional - is set equals to $position by default)
@param int $page page number where the product was clicked (optional - is 1 by default)
@param float $simi similiarity of the product (optional - is 100.00 by default)
@param string $title title of product (optional - is empty by default)
@param int $pageSize size of the page where the product was found (optional - is 12 by default)
@param int $origPageSize original size of the page before the user could have changed it (optional - is set equals to $page by default)
@param string $userId id of user (optional if modul personalisation is not used)
@param string $campaign campaign name (optional)
@param boolean $instoreAds determines whether it's a sponsered product (optional)
@return boolean $success


public function trackCart(
        $id,
        $masterId = null,
        $title = '',
        $query = null,
        $sid = null,
        $cookieId = null,
        $count = 1,
        $price = null,
        $userId = null,
        $campaign = null,
        $instoreAds = false
    ) {
        $this->setupCartTracking($id, $masterId, $title, $query, $sid, $cookieId, $count, $price, $userId, $campaign, $instoreAds);
        return $this->applyTracking();
    }

public function trackCart ( $ id , $ masterId = null , $ title = '' , $ query = null , $ sid = null , $ cookieId = null , $ count = 1 , $ price = null , $ userId = null , $ campaign = null , $ instoreAds = false ) { $ this -> setupCartTracking ( $ id , $ masterId , $ title , $ query , $ sid , $ cookieId , $ count , $ price , $ userId , $ campaign , $ instoreAds ) ; return $ this -> applyTracking ( ) ; }

Track a product which was added to the cart.

@param string $id tracking id of product (see field with the role "Product number for tracking")
@param string $masterId master id of the product (see field with the role "Master article number")
@param string $tile title of product (optional - is empty by default)
@param string $query query which led to the product (only if module Semantic Enhancer is used)
@param string $sid session id (if empty, then try to set using the function session_id() )
@param string $cookieId cookie id (optional)
@param int $count number of items purchased for each product (optional - default 1)
@param float $price this is the single unit price (optional)
@param string $userId id of user (optional if modul personalisation is not used)
@param string $campaign campaign name (optional)
@param boolean $instoreAds determines whether it's a sponsered product (optional)
@return boolean $success

Track a product which was added to the cart .


public function trackCheckout(
        $id,
        $masterId = null,
        $title = '',
        $query = null,
        $sid = null,
        $cookieId = null,
        $count = 1,
        $price = null,
        $userId = null,
        $campaign = null,
        $instoreAds = false
    ) {
        $this->setupCheckoutTracking($id, $masterId, $title, $query, $sid, $cookieId, $count, $price, $userId, $campaign, $instoreAds);
        return $this->applyTracking();
    }

public function trackCheckout ( $ id , $ masterId = null , $ title = '' , $ query = null , $ sid = null , $ cookieId = null , $ count = 1 , $ price = null , $ userId = null , $ campaign = null , $ instoreAds = false ) { $ this -> setupCheckoutTracking ( $ id , $ masterId , $ title , $ query , $ sid , $ cookieId , $ count , $ price , $ userId , $ campaign , $ instoreAds ) ; return $ this -> applyTracking ( ) ; }

Track a product which was purchased.

@param string $id tracking id of product (see field with the role "Product number for tracking")
@param string $masterId master id of the product (see field with the role "Master article number")
@param string $tile title of product (optional - is empty by default)
@param string $query query which led to the product (only if module Semantic Enhancer is used)
@param string $sid session id (if empty, then try to set using the function session_id() )
@param string $cookieId cookie id (optional)
@param int $count number of items purchased for each product (optional - default 1)
@param float $price this is the single unit price (optional)
@param string $userId id of user (optional if modul personalisation is not used)
@param string $campaign campaign name (optional)
@param boolean $instoreAds determines whether it's a sponsered product (optional)
@return boolean $success


public function trackRecommendationClick(
        $id,
        $mainId,
        $masterId = null,
        $sid = null,
        $cookieId = null,
        $userId = null
    ) {
        $this->setupRecommendationClickTracking($id, $mainId, $masterId, $sid, $cookieId, $userId);
        return $this->applyTracking();
    }

public function trackRecommendationClick ( $ id , $ mainId , $ masterId = null , $ sid = null , $ cookieId = null , $ userId = null ) { $ this -> setupRecommendationClickTracking ( $ id , $ mainId , $ masterId , $ sid , $ cookieId , $ userId ) ; return $ this -> applyTracking ( ) ; }

Track a click on a recommended product.

@param string $id tracking id of product (see field with the role "Product number for tracking")
@param int $mainId ID of the product for which the clicked-upon item was recommended
@param string $masterId master id of the product (see field with the role "Master article number")
@param string $sid session id (if empty, then try to set using the function session_id() )
@param string $cookieId cookie id (optional)
@param string $userId id of user (optional if modul personalisation is not used)
@return boolean $success

Track a click on a recommended product .


public function trackLogin(
        $sid = null,
        $cookieId = null,
        $userId = null
    ) {
        $this->setupLoginTracking($sid, $cookieId, $userId);
        return $this->applyTracking();
    }

public function trackLogin ( $ sid = null , $ cookieId = null , $ userId = null ) { $ this -> setupLoginTracking ( $ sid , $ cookieId , $ userId ) ; return $ this -> applyTracking ( ) ; }

Track login of a user

@param string $sid session id (if empty, then try to set using the function session_id() )
@param string $cookieId cookie id (optional)
@param string $userId id of user who logged in
@return boolean $success


public function setProductIDs($productIDs)
    {
        $parameters = $this->request->getParameters();
        $parameters['ids'] = implode(';', $productIDs);
        $this->upToDate = false;
    }

public function setProductIDs ( $ productIDs ) { $ parameters = $ this -> request -> getParameters ( ) ; $ parameters [ 'ids' ] = implode ( ';' , $ productIDs ) ; $ this -> upToDate = false ; }

Set a list-like array of product IDs to compare.

@param string[] $productIDs

Set a list - like array of product IDs to compare .


public function getComparableAttributes()
    {
        if (is_null($this->comparableAttributes)
            || !$this->upToDate
        ) {
            $this->comparableAttributes = $this->createComparableAttributes();
            $this->upToDate = true;
        }

        return $this->comparableAttributes;
    }

public function getComparableAttributes ( ) { if ( is_null ( $ this -> comparableAttributes ) || ! $ this -> upToDate ) { $ this -> comparableAttributes = $ this -> createComparableAttributes ( ) ; $ this -> upToDate = true ; } return $ this -> comparableAttributes ; }

Returns the attributes which can be compared and whether the products in
question differ in each of those attributes. If no IDs have been set,
there will be a warning raised and an empty array will be returned.

@return bool[] Attribute names as keys, boolean value indicates whether
products have different values for this attribute.

Returns the attributes which can be compared and whether the products in question differ in each of those attributes . If no IDs have been set there will be a warning raised and an empty array will be returned .


public function getComparedRecords()
    {
        if (is_null($this->comparedRecords)
            || !$this->upToDate
        ) {
            $this->comparedRecords = $this->createComparedRecords();
            $this->upToDate = true;
        }

        return $this->comparedRecords;
    }

public function getComparedRecords ( ) { if ( is_null ( $ this -> comparedRecords ) || ! $ this -> upToDate ) { $ this -> comparedRecords = $ this -> createComparedRecords ( ) ; $ this -> upToDate = true ; } return $ this -> comparedRecords ; }

Returns the records corresponding to the IDs previously specified. If no
IDs have been set, there will be a warning raised and an empty result
will be returned.

@return \FACTFinder\Data\Result

Returns the records corresponding to the IDs previously specified . If no IDs have been set there will be a warning raised and an empty result will be returned .


public function format(&$sbuf, $event) {
		$string = $this->convert($event);

		if (!isset($this->formattingInfo)) {
			$sbuf .= $string;
			return;
		}

		$fi = $this->formattingInfo;

		// Empty string
		if($string === '' || is_null($string)) {
			if($fi->min > 0) {
				$sbuf .= str_repeat(' ', $fi->min);
			}
			return;
		}

		$len = strlen($string);

		// Trim the string if needed
		if($len > $fi->max) {
			if ($fi->trimLeft) {
				$sbuf .= substr($string, $len - $fi->max, $fi->max);
			} else {
				$sbuf .= substr($string , 0, $fi->max);
			}
		}

		// Add padding if needed
		else if($len < $fi->min) {
			if($fi->padLeft) {
				$sbuf .= str_repeat(' ', $fi->min - $len);
				$sbuf .= $string;
			} else {
				$sbuf .= $string;
				$sbuf .= str_repeat(' ', $fi->min - $len);
			}
		}

		// No action needed
		else {
			$sbuf .= $string;
		}
	}

public
function
format
(
&
$
sbuf
,
$
event
)
{
$
string
=
$
this
->
convert
(
$
event
)
;
if
(
!
isset
(
$
this
->
formattingInfo
)
)
{
$
sbuf
.=
$
string
;
return
;
}
$
fi
=
$
this
->
formattingInfo
;
// Empty string
if
(
$
string
===
''
||
is_null
(
$
string
)
)
{
if
(
$
fi
->
min
>
0
)
{
$
sbuf
.=
str_repeat
(
' '
,
$
fi
->
min
)
;
}
return
;
}
$
len
=
strlen
(
$
string
)
;
// Trim the string if needed
if
(
$
len
>
$
fi
->
max
)
{
if
(
$
fi
->
trimLeft
)
{
$
sbuf
.=
substr
(
$
string
,
$
len
$
fi
->
max
,
$
fi
->
max
)
;
}
else
{
$
sbuf
.=
substr
(
$
string
,
0
,
$
fi
->
max
)
;
}
}
// Add padding if needed
else
if
(
$
len
<
$
fi
->
min
)
{
if
(
$
fi
->
padLeft
)
{
$
sbuf
.=
str_repeat
(
' '
,
$
fi
->
min
$
len
)
;
$
sbuf
.=
$
string
;
}
else
{
$
sbuf
.=
$
string
;
$
sbuf
.=
str_repeat
(
' '
,
$
fi
->
min
$
len
)
;
}
}
// No action needed
else
{
$
sbuf
.=
$
string
;
}
}

Converts the event and formats it according to setting in the
Formatting information object.

@param string &$sbuf string buffer to write to
@param LoggerLoggingEvent $event Event to be formatted.

Converts the event and formats it according to setting in the Formatting information object .


protected function setBoolean($property, $value) {
		try {
			$this->$property = LoggerOptionConverter::toBooleanEx($value);
		} catch (Exception $ex) {
			$value = var_export($value, true);
			$this->warn("Invalid value given for '$property' property: [$value]. Expected a boolean value. Property not changed.");
		}
	}


protected function setLevel($property, $value) {
		try {
			$this->$property = LoggerOptionConverter::toLevelEx($value);
		} catch (Exception $ex) {
			$value = var_export($value, true);
			$this->warn("Invalid value given for '$property' property: [$value]. Expected a level value. Property not changed.");
		}
	}

Setter function for LoggerLevel values .


protected function setFileSize($property, $value) {
		try {
			$this->$property = LoggerOptionConverter::toFileSizeEx($value);
		} catch (Exception $ex) {
			$value = var_export($value, true);
			$this->warn("Invalid value given for '$property' property: [$value]. Expected a file size value.  Property not changed.");
		}
	}


protected function setNumeric($property, $value) {
		try {
			$this->$property = LoggerOptionConverter::toNumericEx($value);
		} catch (Exception $ex) {
			$value = var_export($value, true);
			$this->warn("Invalid value given for '$property' property: [$value]. Expected a number. Property not changed.");
		}
	}


protected function setString($property, $value, $nullable = false) {
		if ($value === null) {
			if($nullable) {
				$this->$property= null;
			} else {
				$this->warn("Null value given for '$property' property. Expected a string. Property not changed.");
			}
		} else {
			try {
				$value = LoggerOptionConverter::toStringEx($value);
				$this->$property = LoggerOptionConverter::substConstants($value);
			} catch (Exception $ex) {
				$value = var_export($value, true);
				$this->warn("Invalid value given for '$property' property: [$value]. Expected a string. Property not changed.");
			}
		}
	}


public function getLocationInformation() {
		if($this->locationInfo === null) {

			$locationInfo = array();
			$trace = debug_backtrace();
			$prevHop = null;
			// make a downsearch to identify the caller
			$hop = array_pop($trace);
			while($hop !== null) {
				if(isset($hop['class'])) {
					// we are sometimes in functions = no class available: avoid php warning here
					$className = strtolower($hop['class']);
					if(!empty($className) and ($className == 'logger' or
						strtolower(get_parent_class($className)) == 'logger')) {
						$locationInfo['line'] = $hop['line'];
						$locationInfo['file'] = $hop['file'];
						break;
					}
				}
				$prevHop = $hop;
				$hop = array_pop($trace);
			}
			$locationInfo['class'] = isset($prevHop['class']) ? $prevHop['class'] : 'main';
			if(isset($prevHop['function']) and
				$prevHop['function'] !== 'include' and
				$prevHop['function'] !== 'include_once' and
				$prevHop['function'] !== 'require' and
				$prevHop['function'] !== 'require_once') {

				$locationInfo['function'] = $prevHop['function'];
			} else {
				$locationInfo['function'] = 'main';
			}

			$this->locationInfo = new LoggerLocationInfo($locationInfo, $this->fqcn);
		}
		return $this->locationInfo;
	}

Set the location information for this logging event. The collected
information is cached for future use.

This method uses {@link PHP_MANUAL#debug_backtrace debug_backtrace()} function (if exists)
to collect informations about caller.

It only recognize informations generated by {@link Logger} and its subclasses.

@return LoggerLocationInfo

Set the location information for this logging event . The collected information is cached for future use .


public static function getStartTime() {
		if(!isset(self::$startTime)) {
			self::$startTime = microtime(true);
		}
		return self::$startTime;
	}

public static function getStartTime ( ) { if ( ! isset ( self :: $ startTime ) ) { self :: $ startTime = microtime ( true ) ; } return self :: $ startTime ; }

Returns the time when the application started, as a UNIX timestamp
with microseconds.
@return float

Returns the time when the application started as a UNIX timestamp with microseconds .


public function getTime() {
		$eventTime = $this->getTimeStamp();
		$eventStartTime = LoggerLoggingEvent::getStartTime();
		return number_format(($eventTime - $eventStartTime) * 1000, 0, '', '');
	}

public function getTime ( ) { $ eventTime = $ this -> getTimeStamp ( ) ; $ eventStartTime = LoggerLoggingEvent :: getStartTime ( ) ; return number_format ( ( $ eventTime - $ eventStartTime ) * 1000 , 0 , '' , '' ) ; }

Returns the time in milliseconds passed from the beginning of execution
to the time the event was constructed.

@deprecated This method has been replaced by getRelativeTime which
does not perform unneccesary multiplication and formatting.

@return integer

Returns the time in milliseconds passed from the beginning of execution to the time the event was constructed .


public function getRequest()
    {
        $connectionData = FF::getInstance(
            'Core\Server\ConnectionData',
            clone $this->requestParameters
        );
        return FF::getInstance('Core\Server\Request',
            $this->loggerClass,
            $connectionData,
            $this->dataProvider
        );
    }

public function getRequest ( ) { $ connectionData = FF :: getInstance ( 'Core\Server\ConnectionData' , clone $ this -> requestParameters ) ; return FF :: getInstance ( 'Core\Server\Request' , $ this -> loggerClass , $ connectionData , $ this -> dataProvider ) ; }

Returns a request object all wired up and ready for use.
@return Request

Returns a request object all wired up and ready for use .


public function getTagCloud($requestQuery = null)
    {
        if (is_null($this->tagCloud)
            || $requestQuery != $this->lastRequestQuery
        ) {
            $this->tagCloud = $this->createTagCloud($requestQuery);
            $this->lastRequestQuery = $requestQuery;
        }

        return $this->tagCloud;
    }

public function getTagCloud ( $ requestQuery = null ) { if ( is_null ( $ this -> tagCloud ) || $ requestQuery != $ this -> lastRequestQuery ) { $ this -> tagCloud = $ this -> createTagCloud ( $ requestQuery ) ; $ this -> lastRequestQuery = $ requestQuery ; } return $ this -> tagCloud ; }

Get the tag cloud from FACT-Finder as an array of TagQuery's.

@param

@return FACTFinder\Data\TagQuery[]

Get the tag cloud from FACT - Finder as an array of TagQuery s .


public function setWordCount($wordCount)
    {
        $parameters = $this->request->getParameters();
        if (is_numeric($wordCount)
            && (int)$wordCount == (float)$wordCount // Is integer?
            && $wordCount > 0
        ) {
            $parameters['wordCount'] = $wordCount;
        }
        else
        {
            unset($parameters['wordCount']);
        }
        // Make sure that the tag cloud is fetched again. In theory, we only
        // have to do this when wordCount increases.
        $this->tagCloud = null;
    }

Set the maximum amount of tag queries to be fetched.

@param int $wordCount The number of tag queries to be fetched. Something
else than a positive integer is passed, the word count will be
unlimited (or determined by FACT-Finder).

Set the maximum amount of tag queries to be fetched .


public function addFeedback(array $feedback)
    {
        foreach($feedback as $label => $text)
            $this->feedback[$label] = (string)$text;
    }

public function addFeedback ( array $ feedback ) { foreach ( $ feedback as $ label => $ text ) $ this -> feedback [ $ label ] = ( string ) $ text ; }

In case of a collision of keys, the existing feedback string will be
overwritten.

@param string[]

In case of a collision of keys the existing feedback string will be overwritten .


public function setProductNumbers($productNumbers)
    {
        $parameters = $this->request->getParameters();
        $parameters['productNumber'] = $productNumbers;
        $this->upToDate = false;
    }

public function setProductNumbers ( $ productNumbers ) { $ parameters = $ this -> request -> getParameters ( ) ; $ parameters [ 'productNumber' ] = $ productNumbers ; $ this -> upToDate = false ; }

Set one or multiple product numbers to get campaigns for, overwriting any
numbers previously set. Note that multiple numbers will only be considered for
shopping cart campaigns. For product detail campaigns only the first number
will be used.

@param string|string[] $productNumbers One or more product numbers.

Set one or multiple product numbers to get campaigns for overwriting any numbers previously set . Note that multiple numbers will only be considered for shopping cart campaigns . For product detail campaigns only the first number will be used .


public function addProductNumbers($productNumbers)
    {
        $parameters = $this->request->getParameters();
        $parameters->add('productNumber', $productNumbers);
        $this->upToDate = false;
    }

public function addProductNumbers ( $ productNumbers ) { $ parameters = $ this -> request -> getParameters ( ) ; $ parameters -> add ( 'productNumber' , $ productNumbers ) ; $ this -> upToDate = false ; }

Add one or multiple product numbser to get campaigns for, in addition to any
numbers previously set.

@param string|string[] $productNumbers One or more product numbers.

Add one or multiple product numbser to get campaigns for in addition to any numbers previously set .


public function setPageId($pageId)
    {
        $parameters = $this->request->getParameters();
        $parameters->add('pageId', $pageId);
        $this->upToDate = false;
    }

public function setPageId ( $ pageId ) { $ parameters = $ this -> request -> getParameters ( ) ; $ parameters -> add ( 'pageId' , $ pageId ) ; $ this -> upToDate = false ; }

Set the page id to get landing page campaigns.

@param string $pageId The id which determines the campaigns for a page.

Set the page id to get landing page campaigns .


public function makeProductCampaign()
    {
        $this->isShoppingCartCampaign = false;
        $this->isLandingPageCampaign = false;
        $this->upToDate = false;
        $this->parameters['do'] = 'getProductCampaigns';
    }

public function makeProductCampaign ( ) { $ this -> isShoppingCartCampaign = false ; $ this -> isLandingPageCampaign = false ; $ this -> upToDate = false ; $ this -> parameters [ 'do' ] = 'getProductCampaigns' ; }

Sets the adapter up for fetching campaigns on product detail pages


public function makeShoppingCartCampaign()
    {
        $this->isShoppingCartCampaign = true;
        $this->isLandingPageCampaign = false;
        $this->upToDate = false;
        $this->parameters['do'] = 'getShoppingCartCampaigns';
    }

public function makeShoppingCartCampaign ( ) { $ this -> isShoppingCartCampaign = true ; $ this -> isLandingPageCampaign = false ; $ this -> upToDate = false ; $ this -> parameters [ 'do' ] = 'getShoppingCartCampaigns' ; }

Sets the adapter up for fetching campaigns on shopping cart pages


public function getCampaigns()
    {
        if (is_null($this->campaigns)
            || !$this->upToDate
        ) {
            $this->request->resetLoaded();
            $this->campaigns = $this->createCampaigns();
            $this->upToDate = true;
        }

        return $this->campaigns;
    }

public function getCampaigns ( ) { if ( is_null ( $ this -> campaigns ) || ! $ this -> upToDate ) { $ this -> request -> resetLoaded ( ) ; $ this -> campaigns = $ this -> createCampaigns ( ) ; $ this -> upToDate = true ; } return $ this -> campaigns ; }

Returns campaigns for IDs previously specified. If no IDs have been
set, there will be a warning raised and an empty result will be returned.

@return \FACTFinder\Data\Result

Returns campaigns for IDs previously specified . If no IDs have been set there will be a warning raised and an empty result will be returned .


public function getRawProductCampaigns($format = null, $callback = null)
    {
        $this->usePassthroughResponseContentProcessor();

        if (!is_null($format))
            $this->parameters['format'] = $format;
        if (!is_null($callback))
            $this->parameters['callback'] = $callback;

        return $this->getResponseContent();
    }

public function getRawProductCampaigns ( $ format = null , $ callback = null ) { $ this -> usePassthroughResponseContentProcessor ( ) ; if ( ! is_null ( $ format ) ) $ this -> parameters [ 'format' ] = $ format ; if ( ! is_null ( $ callback ) ) $ this -> parameters [ 'callback' ] = $ callback ; return $ this -> getResponseContent ( ) ; }

Get the product campaigns from FACT-Finder as the string returned by the
server.

@param string $format Optional. Either 'json' or 'jsonp'. Use to
overwrite the 'format' parameter.
@param string $callback Optional name to overwrite the 'callback'
parameter, which determines the name of the
callback the response is wrapped in.

@return string

Get the product campaigns from FACT - Finder as the string returned by the server .


private function addConverter($word, $modifiers, $option) {
 		$formattingInfo = $this->parseModifiers($modifiers);
		$option = trim($option, "{} ");

		if (isset($this->converterMap[$word])) {
			$converter = $this->getConverter($word, $formattingInfo, $option);
			$this->addToChain($converter);
		} else {
			trigger_error("log4php: Invalid keyword '%$word' in converison pattern. Ignoring keyword.", E_USER_WARNING);
		}
	}

Adds a non-literal converter to the converter chain.

@param string $word The conversion word, used to determine which
converter will be used.
@param string $modifiers Formatting modifiers.
@param string $option Option to pass to the converter.

Adds a non - literal converter to the converter chain .


private function getConverter($word, $info, $option) {
		if (!isset($this->converterMap[$word])) {
			throw new LoggerException("Invalid keyword '%$word' in converison pattern. Ignoring keyword.");
		}

		$converterClass = $this->converterMap[$word];
		if(!class_exists($converterClass)) {
			throw new LoggerException("Class '$converterClass' does not exist.");
		}

		$converter = new $converterClass($info, $option);
		if(!($converter instanceof LoggerPatternConverter)) {
			throw new LoggerException("Class '$converterClass' is not an instance of LoggerPatternConverter.");
		}

		return $converter;
	}

Determines which converter to use based on the conversion word. Creates
an instance of the converter using the provided formatting info and
option and returns it.

@param string $word The conversion word.
@param LoggerFormattingInfo $info Formatting info.
@param string $option Converter option.

@throws LoggerException

@return LoggerPatternConverter

Determines which converter to use based on the conversion word . Creates an instance of the converter using the provided formatting info and option and returns it .


private function parseModifiers($modifiers) {
		$info = new LoggerFormattingInfo();

		// If no modifiers are given, return default values
		if (empty($modifiers)) {
			return $info;
		}

		// Validate
		$pattern = '/^(-?[0-9]+)?\.?-?[0-9]+$/';
		if (!preg_match($pattern, $modifiers)) {
			trigger_error("log4php: Invalid modifier in conversion pattern: [$modifiers]. Ignoring modifier.", E_USER_WARNING);
			return $info;
		}

		$parts = explode('.', $modifiers);

		if (!empty($parts[0])) {
			$minPart = (integer) $parts[0];
			$info->min = abs($minPart);
			$info->padLeft = ($minPart > 0);
		}

		if (!empty($parts[1])) {
			$maxPart = (integer) $parts[1];
			$info->max = abs($maxPart);
			$info->trimLeft = ($maxPart < 0);
		}

		return $info;
	}

Parses the formatting modifiers and produces the corresponding
LoggerFormattingInfo object.

@param string $modifier
@return LoggerFormattingInfo
@throws LoggerException

Parses the formatting modifiers and produces the corresponding LoggerFormattingInfo object .


public function setLevel(LoggerLevel $level = null) {
		if (isset($level)) {
			parent::setLevel($level);
		} else {
			trigger_error("log4php: Cannot set LoggerRoot level to null.", E_USER_WARNING);
		}
	}

Override level setter to prevent setting the root logger's level to
null. Root logger must always have a level.

@param LoggerLevel $level

Override level setter to prevent setting the root logger s level to null . Root logger must always have a level .


public function addRenderer($renderedClass, $renderingClass) {
		// Check the rendering class exists
		if (!class_exists($renderingClass)) {
			trigger_error("log4php: Failed adding renderer. Rendering class [$renderingClass] not found.");
			return;
		}

		// Create the instance
		$renderer = new $renderingClass();

		// Check the class implements the right interface
		if (!($renderer instanceof LoggerRenderer)) {
			trigger_error("log4php: Failed adding renderer. Rendering class [$renderingClass] does not implement the LoggerRenderer interface.");
			return;
		}

		// Convert to lowercase since class names in PHP are not case sensitive
		$renderedClass = strtolower($renderedClass);

		$this->map[$renderedClass] = $renderer;
	}

Adds a renderer to the map.

If a renderer already exists for the given <var>$renderedClass</var> it
will be overwritten without warning.

@param string $renderedClass The name of the class which will be
rendered by the renderer.
@param string $renderingClass The name of the class which will
perform the rendering.


public function setDefaultRenderer($renderingClass) {
		// Check the class exists
		if (!class_exists($renderingClass)) {
			trigger_error("log4php: Failed setting default renderer. Rendering class [$renderingClass] not found.");
			return;
		}

		// Create the instance
		$renderer = new $renderingClass();

		// Check the class implements the right interface
		if (!($renderer instanceof LoggerRenderer)) {
			trigger_error("log4php: Failed setting default renderer. Rendering class [$renderingClass] does not implement the LoggerRenderer interface.");
			return;
		}

		$this->defaultRenderer = $renderer;
	}

Sets a custom default renderer class.

TODO: there's code duplication here. This method is almost identical to
addRenderer(). However, it has custom error messages so let it sit for
now.

@param string $renderingClass The name of the class which will
perform the rendering.


public function getByClassName($class) {
		for(; !empty($class); $class = get_parent_class($class)) {
			$class = strtolower($class);
			if(isset($this->map[$class])) {
				return $this->map[$class];
			}
		}
		return null;
	}

public function getByClassName ( $ class ) { for ( ; ! empty ( $ class ) ; $ class = get_parent_class ( $ class ) ) { $ class = strtolower ( $ class ) ; if ( isset ( $ this -> map [ $ class ] ) ) { return $ this -> map [ $ class ] ; } } return null ; }

Returns the appropriate renderer for a given class name.

If no renderer could be found, returns NULL.

@param string $class
@return LoggerRendererObject Or null if not found.

Returns the appropriate renderer for a given class name .


public function getWhitelistServerParameters()
    {
        return array(
            '/^filter.*/' => true,
            '/^sort.*/' => true,
            '/^substringFilter.*/' => true,
            'advisorStatus' => true,
            'callback' => true,
            'campaign' => true,
            'catalog' => true,
            'channel' => true,
            'cookieId' => true,
            'count' => true,
            'do' => true,
            'event' => true,
            'followSearch' => true,
            'format' => true,
            'id' => true,
            'ids' => true,
            'idsOnly' => true,
            'ignoreForCache' => true,
            'instoreAds' => true,
            'isArticleNumber' => true,
            'log' => true,
            'mainId' => true,
            'masterId' => true,
            'maxRecordCount' => true,
            'maxResults' => true,
            'navigation' => true,
            'noArticleNumberSearch' => true,
            'omitContextName' => true,
            'origPageSize' => true,
            'origPos' => true,
            'page' => true,
            'pageId' => true,
            'pageSize' => true,
            'pos' => true,
            'price' => true,
            'productNumber' => true,
            'productsPerPage' => true,
            'query' => true,
            'queryFromSuggest' => true,
            'searchField' => true,
            'seoPath' => true,
            'sid' => true,
            'simi' => true,
            'title' => true,
            'useAsn' => true,
            'useAso' => true,
            'useCampaigns' => true,
            'useFoundWords' => true,
            'useKeywords' => true,
            'usePersonalization' => true,
            'userId' => true,
            'userInput' => true,
            'useSemanticEnhancer' => true,
            'verbose' => true,
            'wordCount' => true
        );
    }

public function getWhitelistServerParameters ( ) { return array ( '/^filter.*/' => true , '/^sort.*/' => true , '/^substringFilter.*/' => true , 'advisorStatus' => true , 'callback' => true , 'campaign' => true , 'catalog' => true , 'channel' => true , 'cookieId' => true , 'count' => true , 'do' => true , 'event' => true , 'followSearch' => true , 'format' => true , 'id' => true , 'ids' => true , 'idsOnly' => true , 'ignoreForCache' => true , 'instoreAds' => true , 'isArticleNumber' => true , 'log' => true , 'mainId' => true , 'masterId' => true , 'maxRecordCount' => true , 'maxResults' => true , 'navigation' => true , 'noArticleNumberSearch' => true , 'omitContextName' => true , 'origPageSize' => true , 'origPos' => true , 'page' => true , 'pageId' => true , 'pageSize' => true , 'pos' => true , 'price' => true , 'productNumber' => true , 'productsPerPage' => true , 'query' => true , 'queryFromSuggest' => true , 'searchField' => true , 'seoPath' => true , 'sid' => true , 'simi' => true , 'title' => true , 'useAsn' => true , 'useAso' => true , 'useCampaigns' => true , 'useFoundWords' => true , 'useKeywords' => true , 'usePersonalization' => true , 'userId' => true , 'userInput' => true , 'useSemanticEnhancer' => true , 'verbose' => true , 'wordCount' => true ) ; }

Get parameters which are allowed in server URLs.

@return array with string as key and boolean true as value for each item

Get parameters which are allowed in server URLs .


private function load($url) {
		if (!file_exists($url)) {
			throw new LoggerException("File [$url] does not exist.");
		}

		$properties = @parse_ini_file($url, true);
		if ($properties === false) {
			$error = error_get_last();
			throw new LoggerException("Error parsing configuration file: {$error['message']}");
		}

		return $properties;
	}

Loads and parses the INI configuration file.

@param string $url Path to the config file.
@throws LoggerException

Loads and parses the INI configuration file .


public function convert($path) {
		// Load the configuration
		$properties = $this->load($path);

		// Parse threshold
		if (isset($properties[self::THRESHOLD_PREFIX])) {
			$this->config['threshold'] = $properties[self::THRESHOLD_PREFIX];
		}

		// Parse root logger
		if (isset($properties[self::ROOT_LOGGER_PREFIX])) {
			$this->parseLogger($properties[self::ROOT_LOGGER_PREFIX], self::ROOT_LOGGER_NAME);
		}

		$appenders = array();

		foreach($properties as $key => $value) {
			// Parse loggers
			if ($this->beginsWith($key, self::LOGGER_PREFIX)) {
				$name = substr($key, strlen(self::LOGGER_PREFIX));
				$this->parseLogger($value, $name);
			}

			// Parse additivity
			if ($this->beginsWith($key, self::ADDITIVITY_PREFIX)) {
				$name = substr($key, strlen(self::ADDITIVITY_PREFIX));
				$this->config['loggers'][$name]['additivity'] = $value;
			}

			// Parse appenders
			else if ($this->beginsWith($key, self::APPENDER_PREFIX)) {
				$this->parseAppender($key, $value);
			}

			// Parse renderers
			else if ($this->beginsWith($key, self::RENDERER_PREFIX)) {
				$this->parseRenderer($key, $value);
			}
		}

		return $this->config;
	}

public
function
convert
(
$
path
)
{
// Load the configuration
$
properties
=
$
this
->
load
(
$
path
)
;
// Parse threshold
if
(
isset
(
$
properties
[
self
::
THRESHOLD_PREFIX
]
)
)
{
$
this
->
config
[
'threshold'
]
=
$
properties
[
self
::
THRESHOLD_PREFIX
]
;
}
// Parse root logger
if
(
isset
(
$
properties
[
self
::
ROOT_LOGGER_PREFIX
]
)
)
{
$
this
->
parseLogger
(
$
properties
[
self
::
ROOT_LOGGER_PREFIX
]
,
self
::
ROOT_LOGGER_NAME
)
;
}
$
appenders
=
array
(
)
;
foreach
(
$
properties
as
$
key
=>
$
value
)
{
// Parse loggers
if
(
$
this
->
beginsWith
(
$
key
,
self
::
LOGGER_PREFIX
)
)
{
$
name
=
substr
(
$
key
,
strlen
(
self
::
LOGGER_PREFIX
)
)
;
$
this
->
parseLogger
(
$
value
,
$
name
)
;
}
// Parse additivity
if
(
$
this
->
beginsWith
(
$
key
,
self
::
ADDITIVITY_PREFIX
)
)
{
$
name
=
substr
(
$
key
,
strlen
(
self
::
ADDITIVITY_PREFIX
)
)
;
$
this
->
config
[
'loggers'
]
[
$
name
]
[
'additivity'
]
=
$
value
;
}
// Parse appenders
else
if
(
$
this
->
beginsWith
(
$
key
,
self
::
APPENDER_PREFIX
)
)
{
$
this
->
parseAppender
(
$
key
,
$
value
)
;
}
// Parse renderers
else
if
(
$
this
->
beginsWith
(
$
key
,
self
::
RENDERER_PREFIX
)
)
{
$
this
->
parseRenderer
(
$
key
,
$
value
)
;
}
}
return
$
this
->
config
;
}

Converts the provided INI configuration file to a PHP array config.

@param string $path Path to the config file.
@throws LoggerException If the file cannot be loaded or parsed.

Converts the provided INI configuration file to a PHP array config .


private function parseLogger($value, $name) {
		// Value is divided by commas
		$parts = explode(',', $value);
		if (empty($value) || empty($parts)) {
			return;
		}

		// The first value is the logger level
		$level = array_shift($parts);

		// The remaining values are appender references
		$appenders = array();
		while($appender = array_shift($parts)) {
			$appender = trim($appender);
			if (!empty($appender)) {
				$appenders[] = trim($appender);
			}
		}

		// Find the target configuration
		if ($name == self::ROOT_LOGGER_NAME) {
			$this->config['rootLogger']['level'] = trim($level);
			$this->config['rootLogger']['appenders'] = $appenders;
		} else {
			$this->config['loggers'][$name]['level'] = trim($level);
			$this->config['loggers'][$name]['appenders'] = $appenders;
		}
	}

Parses a logger definition.

Loggers are defined in the following manner:
<pre>
log4php.logger.<name> = [<level>], [<appender-ref>, <appender-ref>, ...]
</pre>

@param string $value The configuration value (level and appender-refs).
@param string $name Logger name.


private function parseAppender($key, $value) {

		// Remove the appender prefix from key
		$subKey = substr($key, strlen(self::APPENDER_PREFIX));

		// Divide the string by dots
		$parts = explode('.', $subKey);
		$count = count($parts);

		// The first part is always the appender name
		$name = trim($parts[0]);

		// Only one part - this line defines the appender class
		if ($count == 1) {
			$this->config['appenders'][$name]['class'] = $value;
			return;
		}

		// Two parts - either a parameter, a threshold or layout class
		else if ($count == 2) {

			if ($parts[1] == 'layout') {
				$this->config['appenders'][$name]['layout']['class'] = $value;
				return;
			} else if ($parts[1] == 'threshold') {
				$this->config['appenders'][$name]['threshold'] = $value;
				return;
			} else {
				$this->config['appenders'][$name]['params'][$parts[1]] = $value;
				return;
			}
		}

		// Three parts - this can only be a layout parameter
		else if ($count == 3) {
			if ($parts[1] == 'layout') {
				$this->config['appenders'][$name]['layout']['params'][$parts[2]] = $value;
				return;
			}
		}

		trigger_error("log4php: Don't know how to parse the following line: \"$key = $value\". Skipping.");
	}

Parses an configuration line pertaining to an appender.

Parses the following patterns:

Appender class:

log4php.appender.<name> = <class>

Appender parameter:

log4php.appender.<name>.<param> = <value>

Appender threshold:

log4php.appender.<name>.threshold = <level>

Appender layout:

log4php.appender.<name>.layout = <layoutClass>

Layout parameter:

log4php.appender.<name>.layout.<param> = <value>

For example, a full appender config might look like:

log4php.appender.myAppender = LoggerAppenderConsole
log4php.appender.myAppender.threshold = info
log4php.appender.myAppender.target = stdout
log4php.appender.myAppender.layout = LoggerLayoutPattern
log4php.appender.myAppender.layout.conversionPattern = "%d %c: %m%n"

After parsing all these options, the following configuration can be
found under $this->config['appenders']['myAppender']:

array(
'class' => LoggerAppenderConsole,
'threshold' => info,
'params' => array(
'target' => 'stdout'
),
'layout' => array(
'class' => 'LoggerAppenderConsole',
'params' => array(
'conversionPattern' => '%d %c: %m%n'
)
)
)

@param string $key
@param string $value

Parses an configuration line pertaining to an appender .


private function parseRenderer($key, $value) {
		// Remove the appender prefix from key
		$renderedClass = substr($key, strlen(self::APPENDER_PREFIX));
		$renderingClass = $value;

		$this->config['renderers'][] = compact('renderedClass', 'renderingClass');
	}

private
function
parseRenderer
(
$
key
,
$
value
)
{
// Remove the appender prefix from key
$
renderedClass
=
substr
(
$
key
,
strlen
(
self
::
APPENDER_PREFIX
)
)
;
$
renderingClass
=
$
value
;
$
this
->
config
[
'renderers'
]
[
]
=
compact
(
'renderedClass'
,
'renderingClass'
)
;
}

Parses a renderer definition.

Renderers are defined as:
<pre>
log4php.renderer.<renderedClass> = <renderingClass>
</pre>

@param string $key log4php.renderer.<renderedClass>
@param string $value <renderingClass>


public function append(LoggerLoggingEvent $event) {
		$priority = $this->getSyslogPriority($event->getLevel());
		$message = $this->layout->format($event);

		openlog($this->ident, $this->intOption, $this->intFacility);
		syslog($priority, $message);
		closelog();
	}

public function append ( LoggerLoggingEvent $ event ) { $ priority = $ this -> getSyslogPriority ( $ event -> getLevel ( ) ) ; $ message = $ this -> layout -> format ( $ event ) ; openlog ( $ this -> ident , $ this -> intOption , $ this -> intFacility ) ; syslog ( $ priority , $ message ) ; closelog ( ) ; }

Appends the event to syslog.

Log is opened and closed each time because if it is not closed, it
can cause the Apache httpd server to log to whatever ident/facility
was used in openlog().

@see http://www.php.net/manual/en/function.syslog.php#97843


private function parseOption() {
		$value = 0;
		$options = explode('|', $this->option);

		foreach($options as $option) {
			if (!empty($option)) {
				$constant = "LOG_" . trim($option);
				if (defined($constant)) {
					$value |= constant($constant);
				} else {
					trigger_error("log4php: Invalid syslog option provided: $option. Whole option string: {$this->option}.", E_USER_WARNING);
				}
			}
		}
		return $value;
	}

Parses a syslog option string and returns the correspodning int value.

Parses a syslog option string and returns the correspodning int value .


private function parseFacility() {
		if (!empty($this->facility)) {
			$constant = "LOG_" . trim($this->facility);
			if (defined($constant)) {
				return constant($constant);
			} else {
				trigger_error("log4php: Invalid syslog facility provided: {$this->facility}.", E_USER_WARNING);
			}
		}
	}

Parses the facility string and returns the corresponding int value.

Parses the facility string and returns the corresponding int value .


private function parsePriority() {
		if (!empty($this->priority)) {
			$constant = "LOG_" . trim($this->priority);
			if (defined($constant)) {
				return constant($constant);
			} else {
				trigger_error("log4php: Invalid syslog priority provided: {$this->priority}.", E_USER_WARNING);
			}
		}
	}

Parses the priority string and returns the corresponding int value.

Parses the priority string and returns the corresponding int value .


public function append(LoggerLoggingEvent $event) {
		try {
			if ($this->collection != null) {
				$this->collection->insert($this->format($event));
			}
		} catch (MongoCursorException $ex) {
			$this->warn(sprintf('Error while writing to mongo collection: %s', $ex->getMessage()));
		}
	}

Appends a new event to the mongo database.

@param LoggerLoggingEvent $event

Appends a new event to the mongo database .


protected function formatThrowable(Exception $ex) {
		$array = array(
			'message' => $ex->getMessage(),
			'code' => $ex->getCode(),
			'stackTrace' => $ex->getTraceAsString(),
		);

		if (method_exists($ex, 'getPrevious') && $ex->getPrevious() !== null) {
			$array['innerException'] = $this->formatThrowable($ex->getPrevious());
		}

		return $array;
	}

protected function formatThrowable ( Exception $ ex ) { $ array = array ( 'message' => $ ex -> getMessage ( ) , 'code' => $ ex -> getCode ( ) , 'stackTrace' => $ ex -> getTraceAsString ( ) , ) ; if ( method_exists ( $ ex , 'getPrevious' ) && $ ex -> getPrevious ( ) !== null ) { $ array [ 'innerException' ] = $ this -> formatThrowable ( $ ex -> getPrevious ( ) ) ; } return $ array ; }

Converts an Exception into an array which can be logged to mongodb.

Supports innner exceptions (PHP >= 5.3)

@param Exception $ex
@return array

Converts an Exception into an array which can be logged to mongodb .


public function close() {
		if($this->closed != true) {
			$this->collection = null;
			if ($this->connection !== null) {
				$this->connection->close();
				$this->connection = null;
			}
			$this->closed = true;
		}
	}

public function close ( ) { if ( $ this -> closed != true ) { $ this -> collection = null ; if ( $ this -> connection !== null ) { $ this -> connection -> close ( ) ; $ this -> connection = null ; } $ this -> closed = true ; } }

Closes the connection to the logging database


public function configure(LoggerHierarchy $hierarchy, $input = null) {
		$config = $this->parse($input);
		$this->doConfigure($hierarchy, $config);
	}

public function configure ( LoggerHierarchy $ hierarchy , $ input = null ) { $ config = $ this -> parse ( $ input ) ; $ this -> doConfigure ( $ hierarchy , $ config ) ; }

Configures log4php based on the given configuration. The input can
either be a path to the config file, or a PHP array holding the
configuration.

If no configuration is given, or if the given configuration cannot be
parsed for whatever reason, a warning will be issued, and log4php
will use the default configuration contained in
{@link $defaultConfiguration}.

@param LoggerHierarchy $hierarchy The hierarchy on which to perform
the configuration.
@param string|array $input Either path to the config file or the
configuration as an array. If not set, default configuration
will be used.

Configures log4php based on the given configuration . The input can either be a path to the config file or a PHP array holding the configuration .


private function createAppenderLayout(LoggerAppender $appender, $config) {
		$name = $appender->getName();
		$class = $config['class'];
		if (empty($class)) {
			$this->warn("Layout class not specified for appender [$name]. Reverting to default layout.");
			return;
		}
		if (!class_exists($class)) {
			$this->warn("Nonexistant layout class [$class] specified for appender [$name]. Reverting to default layout.");
			return;
		}

		$layout = new $class();
		if (!($layout instanceof LoggerLayout)) {
			$this->warn("Invalid layout class [$class] sepcified for appender [$name]. Reverting to default layout.");
			return;
		}

		if (isset($config['params'])) {
			$this->setOptions($layout, $config['params']);
		}

		$layout->activateOptions();
		$appender->setLayout($layout);
	}

Parses layout config, creates the layout and links it to the appender.
@param LoggerAppender $appender
@param array $config Layout configuration.

Parses layout config creates the layout and links it to the appender .


public function setIdsOnly($idsOnly)
    {
        if($this->idsOnly && !$idsOnly)
            $this->upToDate = false;

        $this->idsOnly = $idsOnly;
        $parameters = $this->request->getParameters();
        $parameters['idsOnly'] = $idsOnly ? 'true' : 'false';
    }

public function setIdsOnly ( $ idsOnly ) { if ( $ this -> idsOnly && ! $ idsOnly ) $ this -> upToDate = false ; $ this -> idsOnly = $ idsOnly ; $ parameters = $ this -> request -> getParameters ( ) ; $ parameters [ 'idsOnly' ] = $ idsOnly ? 'true' : 'false' ; }

Set this to true to only retrieve the IDs of products instead
of full Record objects.
@param $idsOnly bool

Set this to true to only retrieve the IDs of products instead of full Record objects .


public function getFollowSearchValue()
    {
        $jsonData = $this->getResponseContent();
        //use searchParams of result if available
        if ($this->isValidResponse($jsonData) && isset($jsonData['searchResult']['searchParams'])) {
            $parameters = FF::getInstance(
                'Util\Parameters',
                $jsonData['searchResult']['searchParams']
            );
        //fallback to current request
        } else {
            $parameters = $this->parameters;
        }
        $searchParameters = FF::getInstance(
            'Data\SearchParameters',
            $parameters
        );
        $sorting = $searchParameters->getSortings();
        // check if followSearch was set in request data or sent by FF in result searchParams
        if($searchParameters->getFollowSearch() !== 0) {
            $followSearch =  $searchParameters->getFollowSearch();
        // use simiFirstRecord only if result was not sorted
        } elseif (empty($sorting)) {
            $jsonData = $this->getResponseContent();
            if($jsonData && $jsonData['searchResult'] && isset($jsonData['searchResult']['simiFirstRecord']))
                $followSearch = $jsonData['searchResult']['simiFirstRecord'];
        //mark as not valid
        } else {
            $followSearch = 0;
        }
        return $followSearch;
    }

Value for parameter "followSearch" for followups on initial search like filters, pagination, ...
Either from search results searchParams, request parameters or from search results "simiFirstRecord".
Returns 0 if no parameter "followSearch" could be acquired.

@return int

Value for parameter followSearch for followups on initial search like filters pagination ... Either from search results searchParams request parameters or from search results simiFirstRecord . Returns 0 if no parameter followSearch could be acquired .


public function addNext($filter) {
		if($this->next !== null) {
			$this->next->addNext($filter);
		} else {
			$this->next = $filter;
		}
	}

public function addNext ( $ filter ) { if ( $ this -> next !== null ) { $ this -> next -> addNext ( $ filter ) ; } else { $ this -> next = $ filter ; } }

Adds a new filter to the filter chain this filter is a part of.
If this filter has already and follow up filter, the param filter
is passed on until it is the last filter in chain.

@param $filter - the filter to add to this chain

Adds a new filter to the filter chain this filter is a part of . If this filter has already and follow up filter the param filter is passed on until it is the last filter in chain .


public function setResponse(Response $response, $url)
    {
        $this->response = $response;
        $this->previousUrl = $url;
    }

public function setResponse ( Response $ response , $ url ) { $ this -> response = $ response ; $ this -> previousUrl = $ url ; }

Set a response for the current connection settings along with the URL
which was used to obtain the response.
@param Response $response
@param string $url The URL corresponding to $response.

Set a response for the current connection settings along with the URL which was used to obtain the response .


public function setSid($sessionId)
    {
        if (strcmp($sessionId, $this->sid) !== 0) {
            $this->sid = $sessionId;
            $this->parameters['sid'] = $this->sid;
            $this->upToDate = false;
        }
    }

public function setSid ( $ sessionId ) { if ( strcmp ( $ sessionId , $ this -> sid ) !== 0 ) { $ this -> sid = $ sessionId ; $ this -> parameters [ 'sid' ] = $ this -> sid ; $ this -> upToDate = false ; } }

Set the session id for personalization.

@param string $sessionId session id

Set the session id for personalization .


public function equals($other) {
		if($other instanceof LoggerLevel) {
			if($this->level == $other->level) {
				return true;
			}
		} else {
			return false;
		}
	}

public function equals ( $ other ) { if ( $ other instanceof LoggerLevel ) { if ( $ this -> level == $ other -> level ) { return true ; } } else { return false ; } }

Compares two logger levels.

@param LoggerLevels $other
@return boolean


public static function getLevelOff() {
		if(!isset(self::$levelMap[LoggerLevel::OFF])) {
			self::$levelMap[LoggerLevel::OFF] = new LoggerLevel(LoggerLevel::OFF, 'OFF', LOG_ALERT);
		}
		return self::$levelMap[LoggerLevel::OFF];
	}

public static function getLevelOff ( ) { if ( ! isset ( self :: $ levelMap [ LoggerLevel :: OFF ] ) ) { self :: $ levelMap [ LoggerLevel :: OFF ] = new LoggerLevel ( LoggerLevel :: OFF , 'OFF' , LOG_ALERT ) ; } return self :: $ levelMap [ LoggerLevel :: OFF ] ; }

Returns an Off Level
@return LoggerLevel


public static function getLevelFatal() {
		if(!isset(self::$levelMap[LoggerLevel::FATAL])) {
			self::$levelMap[LoggerLevel::FATAL] = new LoggerLevel(LoggerLevel::FATAL, 'FATAL', LOG_ALERT);
		}
		return self::$levelMap[LoggerLevel::FATAL];
	}

public static function getLevelFatal ( ) { if ( ! isset ( self :: $ levelMap [ LoggerLevel :: FATAL ] ) ) { self :: $ levelMap [ LoggerLevel :: FATAL ] = new LoggerLevel ( LoggerLevel :: FATAL , 'FATAL' , LOG_ALERT ) ; } return self :: $ levelMap [ LoggerLevel :: FATAL ] ; }

Returns a Fatal Level
@return LoggerLevel


public static function getLevelError() {
		if(!isset(self::$levelMap[LoggerLevel::ERROR])) {
			self::$levelMap[LoggerLevel::ERROR] = new LoggerLevel(LoggerLevel::ERROR, 'ERROR', LOG_ERR);
		}
		return self::$levelMap[LoggerLevel::ERROR];
	}

public static function getLevelError ( ) { if ( ! isset ( self :: $ levelMap [ LoggerLevel :: ERROR ] ) ) { self :: $ levelMap [ LoggerLevel :: ERROR ] = new LoggerLevel ( LoggerLevel :: ERROR , 'ERROR' , LOG_ERR ) ; } return self :: $ levelMap [ LoggerLevel :: ERROR ] ; }

Returns an Error Level
@return LoggerLevel


public static function getLevelWarn() {
		if(!isset(self::$levelMap[LoggerLevel::WARN])) {
			self::$levelMap[LoggerLevel::WARN] = new LoggerLevel(LoggerLevel::WARN, 'WARN', LOG_WARNING);
		}
		return self::$levelMap[LoggerLevel::WARN];
	}

public static function getLevelWarn ( ) { if ( ! isset ( self :: $ levelMap [ LoggerLevel :: WARN ] ) ) { self :: $ levelMap [ LoggerLevel :: WARN ] = new LoggerLevel ( LoggerLevel :: WARN , 'WARN' , LOG_WARNING ) ; } return self :: $ levelMap [ LoggerLevel :: WARN ] ; }

Returns a Warn Level
@return LoggerLevel


public static function getLevelInfo() {
		if(!isset(self::$levelMap[LoggerLevel::INFO])) {
			self::$levelMap[LoggerLevel::INFO] = new LoggerLevel(LoggerLevel::INFO, 'INFO', LOG_INFO);
		}
		return self::$levelMap[LoggerLevel::INFO];
	}

public static function getLevelInfo ( ) { if ( ! isset ( self :: $ levelMap [ LoggerLevel :: INFO ] ) ) { self :: $ levelMap [ LoggerLevel :: INFO ] = new LoggerLevel ( LoggerLevel :: INFO , 'INFO' , LOG_INFO ) ; } return self :: $ levelMap [ LoggerLevel :: INFO ] ; }

Returns an Info Level
@return LoggerLevel


public static function getLevelDebug() {
		if(!isset(self::$levelMap[LoggerLevel::DEBUG])) {
			self::$levelMap[LoggerLevel::DEBUG] = new LoggerLevel(LoggerLevel::DEBUG, 'DEBUG', LOG_DEBUG);
		}
		return self::$levelMap[LoggerLevel::DEBUG];
	}

public static function getLevelDebug ( ) { if ( ! isset ( self :: $ levelMap [ LoggerLevel :: DEBUG ] ) ) { self :: $ levelMap [ LoggerLevel :: DEBUG ] = new LoggerLevel ( LoggerLevel :: DEBUG , 'DEBUG' , LOG_DEBUG ) ; } return self :: $ levelMap [ LoggerLevel :: DEBUG ] ; }

Returns a Debug Level
@return LoggerLevel


public static function getLevelTrace() {
		if(!isset(self::$levelMap[LoggerLevel::TRACE])) {
			self::$levelMap[LoggerLevel::TRACE] = new LoggerLevel(LoggerLevel::TRACE, 'TRACE', LOG_DEBUG);
		}
		return self::$levelMap[LoggerLevel::TRACE];
	}

public static function getLevelTrace ( ) { if ( ! isset ( self :: $ levelMap [ LoggerLevel :: TRACE ] ) ) { self :: $ levelMap [ LoggerLevel :: TRACE ] = new LoggerLevel ( LoggerLevel :: TRACE , 'TRACE' , LOG_DEBUG ) ; } return self :: $ levelMap [ LoggerLevel :: TRACE ] ; }

Returns a Trace Level
@return LoggerLevel


public static function getLevelAll() {
		if(!isset(self::$levelMap[LoggerLevel::ALL])) {
			self::$levelMap[LoggerLevel::ALL] = new LoggerLevel(LoggerLevel::ALL, 'ALL', LOG_DEBUG);
		}
		return self::$levelMap[LoggerLevel::ALL];
	}

public static function getLevelAll ( ) { if ( ! isset ( self :: $ levelMap [ LoggerLevel :: ALL ] ) ) { self :: $ levelMap [ LoggerLevel :: ALL ] = new LoggerLevel ( LoggerLevel :: ALL , 'ALL' , LOG_DEBUG ) ; } return self :: $ levelMap [ LoggerLevel :: ALL ] ; }

Returns an All Level
@return LoggerLevel


public static function toLevel($arg, $defaultLevel = null) {
		if(is_int($arg)) {
			switch($arg) {
				case self::ALL:	return self::getLevelAll();
				case self::TRACE: return self::getLevelTrace();
				case self::DEBUG: return self::getLevelDebug();
				case self::INFO: return self::getLevelInfo();
				case self::WARN: return self::getLevelWarn();
				case self::ERROR: return self::getLevelError();
				case self::FATAL: return self::getLevelFatal();
				case self::OFF:	return self::getLevelOff();
				default: return $defaultLevel;
			}
		} else {
			switch(strtoupper($arg)) {
				case 'ALL':	return self::getLevelAll();
				case 'TRACE': return self::getLevelTrace();
				case 'DEBUG': return self::getLevelDebug();
				case 'INFO': return self::getLevelInfo();
				case 'WARN': return self::getLevelWarn();
				case 'ERROR': return self::getLevelError();
				case 'FATAL': return self::getLevelFatal();
				case 'OFF':	return self::getLevelOff();
				default: return $defaultLevel;
			}
		}
	}

public static function toLevel ( $ arg , $ defaultLevel = null ) { if ( is_int ( $ arg ) ) { switch ( $ arg ) { case self :: ALL : return self :: getLevelAll ( ) ; case self :: TRACE : return self :: getLevelTrace ( ) ; case self :: DEBUG : return self :: getLevelDebug ( ) ; case self :: INFO : return self :: getLevelInfo ( ) ; case self :: WARN : return self :: getLevelWarn ( ) ; case self :: ERROR : return self :: getLevelError ( ) ; case self :: FATAL : return self :: getLevelFatal ( ) ; case self :: OFF : return self :: getLevelOff ( ) ; default : return $ defaultLevel ; } } else { switch ( strtoupper ( $ arg ) ) { case 'ALL' : return self :: getLevelAll ( ) ; case 'TRACE' : return self :: getLevelTrace ( ) ; case 'DEBUG' : return self :: getLevelDebug ( ) ; case 'INFO' : return self :: getLevelInfo ( ) ; case 'WARN' : return self :: getLevelWarn ( ) ; case 'ERROR' : return self :: getLevelError ( ) ; case 'FATAL' : return self :: getLevelFatal ( ) ; case 'OFF' : return self :: getLevelOff ( ) ; default : return $ defaultLevel ; } } }

Convert the input argument to a level. If the conversion fails, then
this method returns the provided default level.

@param mixed $arg The value to convert to level.
@param LoggerLevel $default Value to return if conversion is not possible.
@return LoggerLevel

Convert the input argument to a level . If the conversion fails then this method returns the provided default level .


public static function getSystemProperty($key, $def) {
		if(defined($key)) {
			return (string)constant($key);
		} else if(isset($_SERVER[$key])) {
			return (string)$_SERVER[$key];
		} else if(isset($_ENV[$key])) {
			return (string)$_ENV[$key];
		} else {
			return $def;
		}
	}

public static function getSystemProperty ( $ key , $ def ) { if ( defined ( $ key ) ) { return ( string ) constant ( $ key ) ; } else if ( isset ( $ _SERVER [ $ key ] ) ) { return ( string ) $ _SERVER [ $ key ] ; } else if ( isset ( $ _ENV [ $ key ] ) ) { return ( string ) $ _ENV [ $ key ] ; } else { return $ def ; } }

Read a predefined var.

It returns a value referenced by <var>$key</var> using this search criteria:
- if <var>$key</var> is a constant then return it. Else
- if <var>$key</var> is set in <var>$_ENV</var> then return it. Else
- return <var>$def</var>.

@param string $key The key to search for.
@param string $def The default value to return.
@return string	the string value of the system property, or the default
value if there is no property with that key.


public static function toLevelEx($value) {
		if ($value instanceof LoggerLevel) {
			return $value;
		}
		$level = LoggerLevel::toLevel($value);
		if ($level === null) {
			throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to a logger level.");
		}
		return $level;
	}

Converts the value to a level. Throws an exception if not possible.

Converts the value to a level . Throws an exception if not possible .


public static function toStringEx($value) {
		if (is_string($value)) {
			return $value;
		}
		if (is_numeric($value)) {
			return (string) $value;
		}
		if (is_object($value) && method_exists($value, '__toString')) {
			return (string) $value;
		}

		throw new LoggerException("Given value [" . var_export($value, true) . "] cannot be converted to string.");
	}

public
static
function
toStringEx
(
$
value
)
{
if
(
is_string
(
$
value
)
)
{
return
$
value
;
}
if
(
is_numeric
(
$
value
)
)
{
return
(
string
)
$
value
;
}
if
(
is_object
(
$
value
)
&&
method_exists
(
$
value
,
'__toString'
)
)
{
return
(
string
)
$
value
;
}
throw
new
LoggerException
(
"Given value ["
.
var_export
(
$
value
,
true
)
.
"] cannot be converted to string."
)
;
}

Converts a value to string, or throws an exception if not possible.

Objects can be converted to string if they implement the magic
__toString() method.

Converts a value to string or throws an exception if not possible .


public static function substConstants($string) {
		preg_match_all('/\${([^}]+)}/', $string, $matches);

		foreach($matches[1] as $key => $match) {
			$match = trim($match);
			$search = $matches[0][$key];
			$replacement = defined($match) ? constant($match) : '';
			$string = str_replace($search, $replacement, $string);
		}
		return $string;
	}

public static function substConstants ( $ string ) { preg_match_all ( '/\${([^}]+)}/' , $ string , $ matches ) ; foreach ( $ matches [ 1 ] as $ key => $ match ) { $ match = trim ( $ match ) ; $ search = $ matches [ 0 ] [ $ key ] ; $ replacement = defined ( $ match ) ? constant ( $ match ) : '' ; $ string = str_replace ( $ search , $ replacement , $ string ) ; } return $ string ; }

Performs value substitution for string options.

An option can contain PHP constants delimited by '${' and '}'.

E.g. for input string "some ${FOO} value", the method will attempt
to substitute ${FOO} with the value of constant FOO if it exists.

Therefore, if FOO is a constant, and it has value "bar", the resulting
string will be "some bar value".

If the constant is not defined, it will be replaced by an empty string,
and the resulting string will be "some  value".

@param string $string String on which to perform substitution.
@return string

Performs value substitution for string options .


public function getLogger($name) {
		if(!isset($this->loggers[$name])) {
			$logger = new Logger($name);

			$nodes = explode('.', $name);
			$firstNode = array_shift($nodes);

			// if name is not a first node but another first node is their
			if($firstNode != $name and isset($this->loggers[$firstNode])) {
				$logger->setParent($this->loggers[$firstNode]);
			} else {
				// if there is no father, set root logger as father
				$logger->setParent($this->root);
			}

			// if there are more nodes than one
			if(count($nodes) > 0) {
				// find parent node
				foreach($nodes as $node) {
					$parentNode = "$firstNode.$node";
					if(isset($this->loggers[$parentNode]) and $parentNode != $name) {
						$logger->setParent($this->loggers[$parentNode]);
					}
					$firstNode .= ".$node";
				}
			}

			$this->loggers[$name] = $logger;
		}

		return $this->loggers[$name];
	}

Returns a named logger instance logger. If it doesn't exist, one is created.

@param string $name Logger name
@return Logger Logger instance.

Returns a named logger instance logger . If it doesn t exist one is created .