Warning: Cannot modify header information - headers already sent by (output started at /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code:102) in /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code on line 4

Warning: Cannot modify header information - headers already sent by (output started at /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code:102) in /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code on line 4

Warning: Cannot modify header information - headers already sent by (output started at /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code:102) in /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code on line 4

Warning: Cannot modify header information - headers already sent by (output started at /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code:102) in /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code on line 4

Warning: Cannot modify header information - headers already sent by (output started at /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code:102) in /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code on line 4

Warning: Cannot modify header information - headers already sent by (output started at /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code:102) in /var/www/iplanru/data/www/intesco.ru/d59ed/index.php(1) : eval()'d code(2) : eval()'d code on line 4
PKY[Vframework/Symfony/index.htmlnuW+A PKY[V&framework/Symfony/Component/index.htmlnuW+A PKY[NmQ))(framework/Symfony/Component/Yaml/LICENSEnuW+ACopyright (c) 2004-2013 Fabien Potencier Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. PKY[|-?framework/Symfony/Component/Yaml/Exception/RuntimeException.phpnuW+A * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Yaml\Exception; /** * Exception class thrown when an error occurs during parsing. * * @author Romain Neutron * * @api */ class RuntimeException extends \RuntimeException implements ExceptionInterface { } PKY[ؙ՚<framework/Symfony/Component/Yaml/Exception/DumpException.phpnuW+A * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Yaml\Exception; /** * Exception class thrown when an error occurs during dumping. * * @author Fabien Potencier * * @api */ class DumpException extends RuntimeException { } PKY[V5framework/Symfony/Component/Yaml/Exception/index.htmlnuW+A PKY[ =framework/Symfony/Component/Yaml/Exception/ParseException.phpnuW+A * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Yaml\Exception; if (!defined('JSON_UNESCAPED_UNICODE')) { define('JSON_UNESCAPED_SLASHES', 64); define('JSON_UNESCAPED_UNICODE', 256); } /** * Exception class thrown when an error occurs during parsing. * * @author Fabien Potencier * * @api */ class ParseException extends RuntimeException { private $parsedFile; private $parsedLine; private $snippet; private $rawMessage; /** * Constructor. * * @param string $message The error message * @param integer $parsedLine The line where the error occurred * @param integer $snippet The snippet of code near the problem * @param string $parsedFile The file name where the error occurred * @param \Exception $previous The previous exception */ public function __construct($message, $parsedLine = -1, $snippet = null, $parsedFile = null, \Exception $previous = null) { $this->parsedFile = $parsedFile; $this->parsedLine = $parsedLine; $this->snippet = $snippet; $this->rawMessage = $message; $this->updateRepr(); parent::__construct($this->message, 0, $previous); } /** * Gets the snippet of code near the error. * * @return string The snippet of code */ public function getSnippet() { return $this->snippet; } /** * Sets the snippet of code near the error. * * @param string $snippet The code snippet */ public function setSnippet($snippet) { $this->snippet = $snippet; $this->updateRepr(); } /** * Gets the filename where the error occurred. * * This method returns null if a string is parsed. * * @return string The filename */ public function getParsedFile() { return $this->parsedFile; } /** * Sets the filename where the error occurred. * * @param string $parsedFile The filename */ public function setParsedFile($parsedFile) { $this->parsedFile = $parsedFile; $this->updateRepr(); } /** * Gets the line where the error occurred. * * @return integer The file line */ public function getParsedLine() { return $this->parsedLine; } /** * Sets the line where the error occurred. * * @param integer $parsedLine The file line */ public function setParsedLine($parsedLine) { $this->parsedLine = $parsedLine; $this->updateRepr(); } private function updateRepr() { $this->message = $this->rawMessage; $dot = false; if ('.' === substr($this->message, -1)) { $this->message = substr($this->message, 0, -1); $dot = true; } if (null !== $this->parsedFile) { $this->message .= sprintf(' in %s', json_encode($this->parsedFile, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE)); } if ($this->parsedLine >= 0) { $this->message .= sprintf(' at line %d', $this->parsedLine); } if ($this->snippet) { $this->message .= sprintf(' (near "%s")', $this->snippet); } if ($dot) { $this->message .= '.'; } } } PKY[+lAframework/Symfony/Component/Yaml/Exception/ExceptionInterface.phpnuW+A * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Yaml\Exception; /** * Exception interface for all exceptions thrown by the component. * * @author Fabien Potencier * * @api */ interface ExceptionInterface { } PKY[V+framework/Symfony/Component/Yaml/index.htmlnuW+A PKY[\V==+framework/Symfony/Component/Yaml/Inline.phpnuW+A * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Yaml; use Symfony\Component\Yaml\Exception\ParseException; use Symfony\Component\Yaml\Exception\DumpException; /** * Inline implements a YAML parser/dumper for the YAML inline syntax. * * @author Fabien Potencier */ class Inline { const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')'; private static $exceptionOnInvalidType = false; private static $objectSupport = false; /** * Converts a YAML string to a PHP array. * * @param string $value A YAML string * @param Boolean $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise * @param Boolean $objectSupport true if object support is enabled, false otherwise * * @return array A PHP array representing the YAML string * * @throws ParseException */ public static function parse($value, $exceptionOnInvalidType = false, $objectSupport = false) { self::$exceptionOnInvalidType = $exceptionOnInvalidType; self::$objectSupport = $objectSupport; $value = trim($value); if (0 == strlen($value)) { return ''; } if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { $mbEncoding = mb_internal_encoding(); mb_internal_encoding('ASCII'); } $i = 0; switch ($value[0]) { case '[': $result = self::parseSequence($value, $i); ++$i; break; case '{': $result = self::parseMapping($value, $i); ++$i; break; default: $result = self::parseScalar($value, null, array('"', "'"), $i); } // some comments are allowed at the end if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) { throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i))); } if (isset($mbEncoding)) { mb_internal_encoding($mbEncoding); } return $result; } /** * Dumps a given PHP variable to a YAML string. * * @param mixed $value The PHP variable to convert * @param Boolean $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise * @param Boolean $objectSupport true if object support is enabled, false otherwise * * @return string The YAML string representing the PHP array * * @throws DumpException When trying to dump PHP resource */ public static function dump($value, $exceptionOnInvalidType = false, $objectSupport = false) { switch (true) { case is_resource($value): if ($exceptionOnInvalidType) { throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value))); } return 'null'; case is_object($value): if ($objectSupport) { return '!!php/object:'.serialize($value); } if ($exceptionOnInvalidType) { throw new DumpException('Object support when dumping a YAML file has been disabled.'); } return 'null'; case is_array($value): return self::dumpArray($value, $exceptionOnInvalidType, $objectSupport); case null === $value: return 'null'; case true === $value: return 'true'; case false === $value: return 'false'; case ctype_digit($value): return is_string($value) ? "'$value'" : (int) $value; case is_numeric($value): $locale = setlocale(LC_NUMERIC, 0); if (false !== $locale) { setlocale(LC_NUMERIC, 'C'); } $repr = is_string($value) ? "'$value'" : (is_infinite($value) ? str_ireplace('INF', '.Inf', strval($value)) : strval($value)); if (false !== $locale) { setlocale(LC_NUMERIC, $locale); } return $repr; case Escaper::requiresDoubleQuoting($value): return Escaper::escapeWithDoubleQuotes($value); case Escaper::requiresSingleQuoting($value): return Escaper::escapeWithSingleQuotes($value); case '' == $value: return "''"; case preg_match(self::getTimestampRegex(), $value): case in_array(strtolower($value), array('null', '~', 'true', 'false')): return "'$value'"; default: return $value; } } /** * Dumps a PHP array to a YAML string. * * @param array $value The PHP array to dump * @param Boolean $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise * @param Boolean $objectSupport true if object support is enabled, false otherwise * * @return string The YAML string representing the PHP array */ private static function dumpArray($value, $exceptionOnInvalidType, $objectSupport) { // array $keys = array_keys($value); if ((1 == count($keys) && '0' == $keys[0]) || (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (integer) $v + $w; }, 0) == count($keys) * (count($keys) - 1) / 2) ) { $output = array(); foreach ($value as $val) { $output[] = self::dump($val, $exceptionOnInvalidType, $objectSupport); } return sprintf('[%s]', implode(', ', $output)); } // mapping $output = array(); foreach ($value as $key => $val) { $output[] = sprintf('%s: %s', self::dump($key, $exceptionOnInvalidType, $objectSupport), self::dump($val, $exceptionOnInvalidType, $objectSupport)); } return sprintf('{ %s }', implode(', ', $output)); } /** * Parses a scalar to a YAML string. * * @param scalar $scalar * @param string $delimiters * @param array $stringDelimiters * @param integer &$i * @param Boolean $evaluate * * @return string A YAML string * * @throws ParseException When malformed inline YAML string is parsed */ public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true) { if (in_array($scalar[$i], $stringDelimiters)) { // quoted scalar $output = self::parseQuotedScalar($scalar, $i); if (null !== $delimiters) { $tmp = ltrim(substr($scalar, $i), ' '); if (!in_array($tmp[0], $delimiters)) { throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i))); } } } else { // "normal" string if (!$delimiters) { $output = substr($scalar, $i); $i += strlen($output); // remove comments if (false !== $strpos = strpos($output, ' #')) { $output = rtrim(substr($output, 0, $strpos)); } } elseif (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) { $output = $match[1]; $i += strlen($output); } else { throw new ParseException(sprintf('Malformed inline YAML string (%s).', $scalar)); } $output = $evaluate ? self::evaluateScalar($output) : $output; } return $output; } /** * Parses a quoted scalar to YAML. * * @param string $scalar * @param integer &$i * * @return string A YAML string * * @throws ParseException When malformed inline YAML string is parsed */ private static function parseQuotedScalar($scalar, &$i) { if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) { throw new ParseException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i))); } $output = substr($match[0], 1, strlen($match[0]) - 2); $unescaper = new Unescaper(); if ('"' == $scalar[$i]) { $output = $unescaper->unescapeDoubleQuotedString($output); } else { $output = $unescaper->unescapeSingleQuotedString($output); } $i += strlen($match[0]); return $output; } /** * Parses a sequence to a YAML string. * * @param string $sequence * @param integer &$i * * @return string A YAML string * * @throws ParseException When malformed inline YAML string is parsed */ private static function parseSequence($sequence, &$i = 0) { $output = array(); $len = strlen($sequence); $i += 1; // [foo, bar, ...] while ($i < $len) { switch ($sequence[$i]) { case '[': // nested sequence $output[] = self::parseSequence($sequence, $i); break; case '{': // nested mapping $output[] = self::parseMapping($sequence, $i); break; case ']': return $output; case ',': case ' ': break; default: $isQuoted = in_array($sequence[$i], array('"', "'")); $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i); if (!$isQuoted && false !== strpos($value, ': ')) { // embedded mapping? try { $value = self::parseMapping('{'.$value.'}'); } catch (\InvalidArgumentException $e) { // no, it's not } } $output[] = $value; --$i; } ++$i; } throw new ParseException(sprintf('Malformed inline YAML string %s', $sequence)); } /** * Parses a mapping to a YAML string. * * @param string $mapping * @param integer &$i * * @return string A YAML string * * @throws ParseException When malformed inline YAML string is parsed */ private static function parseMapping($mapping, &$i = 0) { $output = array(); $len = strlen($mapping); $i += 1; // {foo: bar, bar:foo, ...} while ($i < $len) { switch ($mapping[$i]) { case ' ': case ',': ++$i; continue 2; case '}': return $output; } // key $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false); // value $done = false; while ($i < $len) { switch ($mapping[$i]) { case '[': // nested sequence $output[$key] = self::parseSequence($mapping, $i); $done = true; break; case '{': // nested mapping $output[$key] = self::parseMapping($mapping, $i); $done = true; break; case ':': case ' ': break; default: $output[$key] = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i); $done = true; --$i; } ++$i; if ($done) { continue 2; } } } throw new ParseException(sprintf('Malformed inline YAML string %s', $mapping)); } /** * Evaluates scalars and replaces magic values. * * @param string $scalar * * @return string A YAML string */ private static function evaluateScalar($scalar) { $scalar = trim($scalar); switch (true) { case 'null' == strtolower($scalar): case '' == $scalar: case '~' == $scalar: return null; case 0 === strpos($scalar, '!str'): return (string) substr($scalar, 5); case 0 === strpos($scalar, '! '): return intval(self::parseScalar(substr($scalar, 2))); case 0 === strpos($scalar, '!!php/object:'): if (self::$objectSupport) { return unserialize(substr($scalar, 13)); } if (self::$exceptionOnInvalidType) { throw new ParseException('Object support when parsing a YAML file has been disabled.'); } return null; case ctype_digit($scalar): $raw = $scalar; $cast = intval($scalar); return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)): $raw = $scalar; $cast = intval($scalar); return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw); case 'true' === strtolower($scalar): return true; case 'false' === strtolower($scalar): return false; case is_numeric($scalar): return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar); case 0 == strcasecmp($scalar, '.inf'): case 0 == strcasecmp($scalar, '.NaN'): return -log(0); case 0 == strcasecmp($scalar, '-.inf'): return log(0); case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar): return floatval(str_replace(',', '', $scalar)); case preg_match(self::getTimestampRegex(), $scalar): return strtotime($scalar); default: return (string) $scalar; } } /** * Gets a regex that matches a YAML date. * * @return string The regular expression * * @see http://www.yaml.org/spec/1.2/spec.html#id2761573 */ private static function getTimestampRegex() { return <<[0-9][0-9][0-9][0-9]) -(?P[0-9][0-9]?) -(?P[0-9][0-9]?) (?:(?:[Tt]|[ \t]+) (?P[0-9][0-9]?) :(?P[0-9][0-9]) :(?P[0-9][0-9]) (?:\.(?P[0-9]*))? (?:[ \t]*(?PZ|(?P[-+])(?P[0-9][0-9]?) (?::(?P[0-9][0-9]))?))?)? $~x EOF; } } PKY[ \\\\+framework/Symfony/Component/Yaml/Parser.phpnuW+A * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Yaml; use Symfony\Component\Yaml\Exception\ParseException; /** * Parser parses YAML strings to convert them to PHP arrays. * * @author Fabien Potencier */ class Parser { const FOLDED_SCALAR_PATTERN = '(?P\||>)(?P\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P +#.*)?'; private $offset = 0; private $lines = array(); private $currentLineNb = -1; private $currentLine = ''; private $refs = array(); /** * Constructor * * @param integer $offset The offset of YAML document (used for line numbers in error messages) */ public function __construct($offset = 0) { $this->offset = $offset; } /** * Parses a YAML string to a PHP value. * * @param string $value A YAML string * @param Boolean $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise * @param Boolean $objectSupport true if object support is enabled, false otherwise * * @return mixed A PHP value * * @throws ParseException If the YAML is not valid */ public function parse($value, $exceptionOnInvalidType = false, $objectSupport = false) { $this->currentLineNb = -1; $this->currentLine = ''; $this->lines = explode("\n", $this->cleanup($value)); if (function_exists('mb_detect_encoding') && false === mb_detect_encoding($value, 'UTF-8', true)) { throw new ParseException('The YAML value does not appear to be valid UTF-8.'); } if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { $mbEncoding = mb_internal_encoding(); mb_internal_encoding('UTF-8'); } $data = array(); $context = null; while ($this->moveToNextLine()) { if ($this->isCurrentLineEmpty()) { continue; } // tab? if ("\t" === $this->currentLine[0]) { throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine); } $isRef = $isInPlace = $isProcessed = false; if (preg_match('#^\-((?P\s+)(?P.+?))?\s*$#u', $this->currentLine, $values)) { if ($context && 'mapping' == $context) { throw new ParseException('You cannot define a sequence item when in a mapping'); } $context = 'sequence'; if (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) { $isRef = $matches['ref']; $values['value'] = $matches['value']; } // array if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { $c = $this->getRealCurrentLineNb() + 1; $parser = new Parser($c); $parser->refs =& $this->refs; $data[] = $parser->parse($this->getNextEmbedBlock(), $exceptionOnInvalidType, $objectSupport); } else { if (isset($values['leadspaces']) && ' ' == $values['leadspaces'] && preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P.+?))?\s*$#u', $values['value'], $matches) ) { // this is a compact notation element, add to next block and parse $c = $this->getRealCurrentLineNb(); $parser = new Parser($c); $parser->refs =& $this->refs; $block = $values['value']; if ($this->isNextLineIndented()) { $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2); } $data[] = $parser->parse($block, $exceptionOnInvalidType, $objectSupport); } else { $data[] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport); } } } elseif (preg_match('#^(?P'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P.+?))?\s*$#u', $this->currentLine, $values) && false === strpos($values['key'],' #')) { if ($context && 'sequence' == $context) { throw new ParseException('You cannot define a mapping item when in a sequence'); } $context = 'mapping'; // force correct settings Inline::parse(null, $exceptionOnInvalidType, $objectSupport); try { $key = Inline::parseScalar($values['key']); } catch (ParseException $e) { $e->setParsedLine($this->getRealCurrentLineNb() + 1); $e->setSnippet($this->currentLine); throw $e; } if ('<<' === $key) { if (isset($values['value']) && 0 === strpos($values['value'], '*')) { $isInPlace = substr($values['value'], 1); if (!array_key_exists($isInPlace, $this->refs)) { throw new ParseException(sprintf('Reference "%s" does not exist.', $isInPlace), $this->getRealCurrentLineNb() + 1, $this->currentLine); } } else { if (isset($values['value']) && $values['value'] !== '') { $value = $values['value']; } else { $value = $this->getNextEmbedBlock(); } $c = $this->getRealCurrentLineNb() + 1; $parser = new Parser($c); $parser->refs =& $this->refs; $parsed = $parser->parse($value, $exceptionOnInvalidType, $objectSupport); $merged = array(); if (!is_array($parsed)) { throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine); } elseif (isset($parsed[0])) { // Numeric array, merge individual elements foreach (array_reverse($parsed) as $parsedItem) { if (!is_array($parsedItem)) { throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem); } $merged = array_merge($parsedItem, $merged); } } else { // Associative array, merge $merged = array_merge($merged, $parsed); } $isProcessed = $merged; } } elseif (isset($values['value']) && preg_match('#^&(?P[^ ]+) *(?P.*)#u', $values['value'], $matches)) { $isRef = $matches['ref']; $values['value'] = $matches['value']; } if ($isProcessed) { // Merge keys $data = $isProcessed; // hash } elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { // if next line is less indented or equal, then it means that the current value is null if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) { $data[$key] = null; } else { $c = $this->getRealCurrentLineNb() + 1; $parser = new Parser($c); $parser->refs =& $this->refs; $data[$key] = $parser->parse($this->getNextEmbedBlock(), $exceptionOnInvalidType, $objectSupport); } } else { if ($isInPlace) { $data = $this->refs[$isInPlace]; } else { $data[$key] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport); } } } else { // 1-liner optionally followed by newline $lineCount = count($this->lines); if (1 === $lineCount || (2 === $lineCount && empty($this->lines[1]))) { try { $value = Inline::parse($this->lines[0], $exceptionOnInvalidType, $objectSupport); } catch (ParseException $e) { $e->setParsedLine($this->getRealCurrentLineNb() + 1); $e->setSnippet($this->currentLine); throw $e; } if (is_array($value)) { $first = reset($value); if (is_string($first) && 0 === strpos($first, '*')) { $data = array(); foreach ($value as $alias) { $data[] = $this->refs[substr($alias, 1)]; } $value = $data; } } if (isset($mbEncoding)) { mb_internal_encoding($mbEncoding); } return $value; } switch (preg_last_error()) { case PREG_INTERNAL_ERROR: $error = 'Internal PCRE error.'; break; case PREG_BACKTRACK_LIMIT_ERROR: $error = 'pcre.backtrack_limit reached.'; break; case PREG_RECURSION_LIMIT_ERROR: $error = 'pcre.recursion_limit reached.'; break; case PREG_BAD_UTF8_ERROR: $error = 'Malformed UTF-8 data.'; break; case PREG_BAD_UTF8_OFFSET_ERROR: $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.'; break; default: $error = 'Unable to parse.'; } throw new ParseException($error, $this->getRealCurrentLineNb() + 1, $this->currentLine); } if ($isRef) { $this->refs[$isRef] = end($data); } } if (isset($mbEncoding)) { mb_internal_encoding($mbEncoding); } return empty($data) ? null : $data; } /** * Returns the current line number (takes the offset into account). * * @return integer The current line number */ private function getRealCurrentLineNb() { return $this->currentLineNb + $this->offset; } /** * Returns the current line indentation. * * @return integer The current line indentation */ private function getCurrentLineIndentation() { return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' ')); } /** * Returns the next embed block of YAML. * * @param integer $indentation The indent level at which the block is to be read, or null for default * * @return string A YAML string * * @throws ParseException When indentation problem are detected */ private function getNextEmbedBlock($indentation = null) { $this->moveToNextLine(); if (null === $indentation) { $newIndent = $this->getCurrentLineIndentation(); $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem($this->currentLine); if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) { throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine); } } else { $newIndent = $indentation; } $data = array(substr($this->currentLine, $newIndent)); $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem($this->currentLine); // Comments must not be removed inside a string block (ie. after a line ending with "|") $removeCommentsPattern = '~'.self::FOLDED_SCALAR_PATTERN.'$~'; $removeComments = !preg_match($removeCommentsPattern, $this->currentLine); while ($this->moveToNextLine()) { if ($this->getCurrentLineIndentation() === $newIndent) { $removeComments = !preg_match($removeCommentsPattern, $this->currentLine); } if ($isItUnindentedCollection && !$this->isStringUnIndentedCollectionItem($this->currentLine)) { $this->moveToPreviousLine(); break; } if ($removeComments && $this->isCurrentLineEmpty() || $this->isCurrentLineBlank()) { if ($this->isCurrentLineBlank()) { $data[] = substr($this->currentLine, $newIndent); } continue; } $indent = $this->getCurrentLineIndentation(); if (preg_match('#^(?P *)$#', $this->currentLine, $match)) { // empty line $data[] = $match['text']; } elseif ($indent >= $newIndent) { $data[] = substr($this->currentLine, $newIndent); } elseif (0 == $indent) { $this->moveToPreviousLine(); break; } else { throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine); } } return implode("\n", $data); } /** * Moves the parser to the next line. * * @return Boolean */ private function moveToNextLine() { if ($this->currentLineNb >= count($this->lines) - 1) { return false; } $this->currentLine = $this->lines[++$this->currentLineNb]; return true; } /** * Moves the parser to the previous line. */ private function moveToPreviousLine() { $this->currentLine = $this->lines[--$this->currentLineNb]; } /** * Parses a YAML value. * * @param string $value A YAML value * @param Boolean $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise * @param Boolean $objectSupport True if object support is enabled, false otherwise * * @return mixed A PHP value * * @throws ParseException When reference does not exist */ private function parseValue($value, $exceptionOnInvalidType, $objectSupport) { if (0 === strpos($value, '*')) { if (false !== $pos = strpos($value, '#')) { $value = substr($value, 1, $pos - 2); } else { $value = substr($value, 1); } if (!array_key_exists($value, $this->refs)) { throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLine); } return $this->refs[$value]; } if (preg_match('/^'.self::FOLDED_SCALAR_PATTERN.'$/', $value, $matches)) { $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : ''; return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers))); } try { return Inline::parse($value, $exceptionOnInvalidType, $objectSupport); } catch (ParseException $e) { $e->setParsedLine($this->getRealCurrentLineNb() + 1); $e->setSnippet($this->currentLine); throw $e; } } /** * Parses a folded scalar. * * @param string $separator The separator that was used to begin this folded scalar (| or >) * @param string $indicator The indicator that was used to begin this folded scalar (+ or -) * @param integer $indentation The indentation that was used to begin this folded scalar * * @return string The text value */ private function parseFoldedScalar($separator, $indicator = '', $indentation = 0) { $notEOF = $this->moveToNextLine(); if (!$notEOF) { return ''; } $isCurrentLineBlank = $this->isCurrentLineBlank(); $text = ''; // leading blank lines are consumed before determining indentation while ($notEOF && $isCurrentLineBlank) { // newline only if not EOF if ($notEOF = $this->moveToNextLine()) { $text .= "\n"; $isCurrentLineBlank = $this->isCurrentLineBlank(); } } // determine indentation if not specified if (0 === $indentation) { if (preg_match('/^ +/', $this->currentLine, $matches)) { $indentation = strlen($matches[0]); } } if ($indentation > 0) { $pattern = sprintf('/^ {%d}(.*)$/', $indentation); while ( $notEOF && ( $isCurrentLineBlank || preg_match($pattern, $this->currentLine, $matches) ) ) { if ($isCurrentLineBlank) { $text .= substr($this->currentLine, $indentation); } else { $text .= $matches[1]; } // newline only if not EOF if ($notEOF = $this->moveToNextLine()) { $text .= "\n"; $isCurrentLineBlank = $this->isCurrentLineBlank(); } } } elseif ($notEOF) { $text .= "\n"; } if ($notEOF) { $this->moveToPreviousLine(); } // replace all non-trailing single newlines with spaces in folded blocks if ('>' === $separator) { preg_match('/(\n*)$/', $text, $matches); $text = preg_replace('/(?getCurrentLineIndentation(); $EOF = !$this->moveToNextLine(); while (!$EOF && $this->isCurrentLineEmpty()) { $EOF = !$this->moveToNextLine(); } if ($EOF) { return false; } $ret = false; if ($this->getCurrentLineIndentation() > $currentIndentation) { $ret = true; } $this->moveToPreviousLine(); return $ret; } /** * Returns true if the current line is blank or if it is a comment line. * * @return Boolean Returns true if the current line is empty or if it is a comment line, false otherwise */ private function isCurrentLineEmpty() { return $this->isCurrentLineBlank() || $this->isCurrentLineComment(); } /** * Returns true if the current line is blank. * * @return Boolean Returns true if the current line is blank, false otherwise */ private function isCurrentLineBlank() { return '' == trim($this->currentLine, ' '); } /** * Returns true if the current line is a comment line. * * @return Boolean Returns true if the current line is a comment line, false otherwise */ private function isCurrentLineComment() { //checking explicitly the first char of the trim is faster than loops or strpos $ltrimmedLine = ltrim($this->currentLine, ' '); return $ltrimmedLine[0] === '#'; } /** * Cleanups a YAML string to be parsed. * * @param string $value The input YAML string * * @return string A cleaned up YAML string */ private function cleanup($value) { $value = str_replace(array("\r\n", "\r"), "\n", $value); // strip YAML header $count = 0; $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#su', '', $value, -1, $count); $this->offset += $count; // remove leading comments $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count); if ($count == 1) { // items have been removed, update the offset $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); $value = $trimmedValue; } // remove start of the document marker (---) $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count); if ($count == 1) { // items have been removed, update the offset $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n"); $value = $trimmedValue; // remove end of the document marker (...) $value = preg_replace('#\.\.\.\s*$#s', '', $value); } return $value; } /** * Returns true if the next line starts unindented collection * * @return Boolean Returns true if the next line starts unindented collection, false otherwise */ private function isNextLineUnIndentedCollection() { $currentIndentation = $this->getCurrentLineIndentation(); $notEOF = $this->moveToNextLine(); while ($notEOF && $this->isCurrentLineEmpty()) { $notEOF = $this->moveToNextLine(); } if (false === $notEOF) { return false; } $ret = false; if ( $this->getCurrentLineIndentation() == $currentIndentation && $this->isStringUnIndentedCollectionItem($this->currentLine) ) { $ret = true; } $this->moveToPreviousLine(); return $ret; } /** * Returns true if the string is un-indented collection item * * @return Boolean Returns true if the string is un-indented collection item, false otherwise */ private function isStringUnIndentedCollectionItem() { return (0 === strpos($this->currentLine, '- ')); } } PKY[6H .framework/Symfony/Component/Yaml/Unescaper.phpnuW+A * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Yaml; /** * Unescaper encapsulates unescaping rules for single and double-quoted * YAML strings. * * @author Matthew Lewinski */ class Unescaper { // Parser and Inline assume UTF-8 encoding, so escaped Unicode characters // must be converted to that encoding. const ENCODING = 'UTF-8'; // Regex fragment that matches an escaped character in a double quoted // string. const REGEX_ESCAPED_CHARACTER = "\\\\([0abt\tnvfre \\\"\\/\\\\N_LP]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})"; /** * Unescapes a single quoted string. * * @param string $value A single quoted string. * * @return string The unescaped string. */ public function unescapeSingleQuotedString($value) { return str_replace('\'\'', '\'', $value); } /** * Unescapes a double quoted string. * * @param string $value A double quoted string. * * @return string The unescaped string. */ public function unescapeDoubleQuotedString($value) { $self = $this; $callback = function ($match) use ($self) { return $self->unescapeCharacter($match[0]); }; // evaluate the string return preg_replace_callback('/'.self::REGEX_ESCAPED_CHARACTER.'/u', $callback, $value); } /** * Unescapes a character that was found in a double-quoted string * * @param string $value An escaped character * * @return string The unescaped character */ public function unescapeCharacter($value) { switch ($value{1}) { case '0': return "\x0"; case 'a': return "\x7"; case 'b': return "\x8"; case 't': return "\t"; case "\t": return "\t"; case 'n': return "\n"; case 'v': return "\xb"; case 'f': return "\xc"; case 'r': return "\xd"; case 'e': return "\x1b"; case ' ': return ' '; case '"': return '"'; case '/': return '/'; case '\\': return '\\'; case 'N': // U+0085 NEXT LINE return $this->convertEncoding("\x00\x85", self::ENCODING, 'UCS-2BE'); case '_': // U+00A0 NO-BREAK SPACE return $this->convertEncoding("\x00\xA0", self::ENCODING, 'UCS-2BE'); case 'L': // U+2028 LINE SEPARATOR return $this->convertEncoding("\x20\x28", self::ENCODING, 'UCS-2BE'); case 'P': // U+2029 PARAGRAPH SEPARATOR return $this->convertEncoding("\x20\x29", self::ENCODING, 'UCS-2BE'); case 'x': $char = pack('n', hexdec(substr($value, 2, 2))); return $this->convertEncoding($char, self::ENCODING, 'UCS-2BE'); case 'u': $char = pack('n', hexdec(substr($value, 2, 4))); return $this->convertEncoding($char, self::ENCODING, 'UCS-2BE'); case 'U': $char = pack('N', hexdec(substr($value, 2, 8))); return $this->convertEncoding($char, self::ENCODING, 'UCS-4BE'); } } /** * Convert a string from one encoding to another. * * @param string $value The string to convert * @param string $to The input encoding * @param string $from The output encoding * * @return string The string with the new encoding * * @throws \RuntimeException if no suitable encoding function is found (iconv or mbstring) */ private function convertEncoding($value, $to, $from) { if (function_exists('mb_convert_encoding')) { return mb_convert_encoding($value, $to, $from); } elseif (function_exists('iconv')) { return iconv($from, $to, $value); } throw new \RuntimeException('No suitable convert encoding function (install the iconv or mbstring extension).'); } } PKY[)%,m m ,framework/Symfony/Component/Yaml/Escaper.phpnuW+A * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Yaml; /** * Escaper encapsulates escaping rules for single and double-quoted * YAML strings. * * @author Matthew Lewinski */ class Escaper { // Characters that would cause a dumped string to require double quoting. const REGEX_CHARACTER_TO_ESCAPE = "[\\x00-\\x1f]|\xc2\x85|\xc2\xa0|\xe2\x80\xa8|\xe2\x80\xa9"; // Mapping arrays for escaping a double quoted string. The backslash is // first to ensure proper escaping because str_replace operates iteratively // on the input arrays. This ordering of the characters avoids the use of strtr, // which performs more slowly. private static $escapees = array('\\\\', '\\"', '"', "\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07", "\x08", "\x09", "\x0a", "\x0b", "\x0c", "\x0d", "\x0e", "\x0f", "\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17", "\x18", "\x19", "\x1a", "\x1b", "\x1c", "\x1d", "\x1e", "\x1f", "\xc2\x85", "\xc2\xa0", "\xe2\x80\xa8", "\xe2\x80\xa9"); private static $escaped = array('\\"', '\\\\', '\\"', "\\0", "\\x01", "\\x02", "\\x03", "\\x04", "\\x05", "\\x06", "\\a", "\\b", "\\t", "\\n", "\\v", "\\f", "\\r", "\\x0e", "\\x0f", "\\x10", "\\x11", "\\x12", "\\x13", "\\x14", "\\x15", "\\x16", "\\x17", "\\x18", "\\x19", "\\x1a", "\\e", "\\x1c", "\\x1d", "\\x1e", "\\x1f", "\\N", "\\_", "\\L", "\\P"); /** * Determines if a PHP value would require double quoting in YAML. * * @param string $value A PHP value * * @return Boolean True if the value would require double quotes. */ public static function requiresDoubleQuoting($value) { return preg_match('/'.self::REGEX_CHARACTER_TO_ESCAPE.'/u', $value); } /** * Escapes and surrounds a PHP value with double quotes. * * @param string $value A PHP value * * @return string The quoted, escaped string */ public static function escapeWithDoubleQuotes($value) { return sprintf('"%s"', str_replace(self::$escapees, self::$escaped, $value)); } /** * Determines if a PHP value would require single quoting in YAML. * * @param string $value A PHP value * * @return Boolean True if the value would require single quotes. */ public static function requiresSingleQuoting($value) { return preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ \- ? | < > = ! % @ ` ]/x', $value); } /** * Escapes and surrounds a PHP value with single quotes. * * @param string $value A PHP value * * @return string The quoted, escaped string */ public static function escapeWithSingleQuotes($value) { return sprintf("'%s'", str_replace('\'', '\'\'', $value)); } } PKY[7MӺ  )framework/Symfony/Component/Yaml/Yaml.phpnuW+A * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Yaml; use Symfony\Component\Yaml\Exception\ParseException; /** * Yaml offers convenience methods to load and dump YAML. * * @author Fabien Potencier * * @api */ class Yaml { /** * Parses YAML into a PHP array. * * The parse method, when supplied with a YAML stream (string or file), * will do its best to convert YAML in a file into a PHP array. * * Usage: * * $array = Yaml::parse('config.yml'); * print_r($array); * * * As this method accepts both plain strings and file names as an input, * you must validate the input before calling this method. Passing a file * as an input is a deprecated feature and will be removed in 3.0. * * @param string $input Path to a YAML file or a string containing YAML * @param Boolean $exceptionOnInvalidType True if an exception must be thrown on invalid types false otherwise * @param Boolean $objectSupport True if object support is enabled, false otherwise * * @return array The YAML converted to a PHP array * * @throws ParseException If the YAML is not valid * * @api */ public static function parse($input, $exceptionOnInvalidType = false, $objectSupport = false) { // if input is a file, process it $file = ''; if (strpos($input, "\n") === false && is_file($input)) { if (false === is_readable($input)) { throw new ParseException(sprintf('Unable to parse "%s" as the file is not readable.', $input)); } $file = $input; $input = file_get_contents($file); } $yaml = new Parser(); try { return $yaml->parse($input, $exceptionOnInvalidType, $objectSupport); } catch (ParseException $e) { if ($file) { $e->setParsedFile($file); } throw $e; } } /** * Dumps a PHP array to a YAML string. * * The dump method, when supplied with an array, will do its best * to convert the array into friendly YAML. * * @param array $array PHP array * @param integer $inline The level where you switch to inline YAML * @param integer $indent The amount of spaces to use for indentation of nested nodes. * @param Boolean $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise * @param Boolean $objectSupport true if object support is enabled, false otherwise * * @return string A YAML string representing the original PHP array * * @api */ public static function dump($array, $inline = 2, $indent = 4, $exceptionOnInvalidType = false, $objectSupport = false) { $yaml = new Dumper(); $yaml->setIndentation($indent); return $yaml->dump($array, $inline, 0, $exceptionOnInvalidType, $objectSupport); } } PKY[8n +framework/Symfony/Component/Yaml/Dumper.phpnuW+A * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Yaml; /** * Dumper dumps PHP variables to YAML strings. * * @author Fabien Potencier */ class Dumper { /** * The amount of spaces to use for indentation of nested nodes. * * @var integer */ protected $indentation = 4; /** * Sets the indentation. * * @param integer $num The amount of spaces to use for indentation of nested nodes. */ public function setIndentation($num) { $this->indentation = (int) $num; } /** * Dumps a PHP value to YAML. * * @param mixed $input The PHP value * @param integer $inline The level where you switch to inline YAML * @param integer $indent The level of indentation (used internally) * @param Boolean $exceptionOnInvalidType true if an exception must be thrown on invalid types (a PHP resource or object), false otherwise * @param Boolean $objectSupport true if object support is enabled, false otherwise * * @return string The YAML representation of the PHP value */ public function dump($input, $inline = 0, $indent = 0, $exceptionOnInvalidType = false, $objectSupport = false) { $output = ''; $prefix = $indent ? str_repeat(' ', $indent) : ''; if ($inline <= 0 || !is_array($input) || empty($input)) { $output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport); } else { $isAHash = array_keys($input) !== range(0, count($input) - 1); foreach ($input as $key => $value) { $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value); $output .= sprintf('%s%s%s%s', $prefix, $isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport).':' : '-', $willBeInlined ? ' ' : "\n", $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport) ).($willBeInlined ? "\n" : ''); } } return $output; } } PKY[Vframework/index.htmlnuW+A PKY[ \==.framework/Joomla/Application/Cli/CliOutput.phpnuW+Aprocessor = $processor; return $this; } /** * Get a processor * * @return ProcessorInterface * * @since 1.0 */ public function getProcessor() { return $this->processor; } /** * Write a string to an output handler. * * @param string $text The text to display. * @param boolean $nl True (default) to append a new line at the end of the output string. * * @return void * * @since 1.0 * @codeCoverageIgnore */ abstract public function out($text = '', $nl = true); } PKY[H;3framework/Joomla/Application/Cli/ColorProcessor.phpnuW+A(.*?)<\/\\1>/s'; /** * Regex used for removing color codes * * @var string * @since 1.0 */ protected static $stripFilter = '/<[\/]?[a-z=;]+>/'; /** * Array of ColorStyle objects * * @var array * @since 1.0 */ protected $styles = array(); /** * Class constructor * * @since 1.1.0 */ public function __construct() { $this->addPredefinedStyles(); } /** * Add a style. * * @param string $name The style name. * @param ColorStyle $style The color style. * * @return ColorProcessor Instance of $this to allow chaining. * * @since 1.0 */ public function addStyle($name, ColorStyle $style) { $this->styles[$name] = $style; return $this; } /** * Strip color tags from a string. * * @param string $string The string. * * @return string * * @since 1.0 */ public static function stripColors($string) { return preg_replace(static::$stripFilter, '', $string); } /** * Process a string. * * @param string $string The string to process. * * @return string * * @since 1.0 */ public function process($string) { preg_match_all($this->tagFilter, $string, $matches); if (!$matches) { return $string; } foreach ($matches[0] as $i => $m) { if (array_key_exists($matches[1][$i], $this->styles)) { $string = $this->replaceColors($string, $matches[1][$i], $matches[2][$i], $this->styles[$matches[1][$i]]); } // Custom format elseif (strpos($matches[1][$i], '=')) { $string = $this->replaceColors($string, $matches[1][$i], $matches[2][$i], ColorStyle::fromString($matches[1][$i])); } } return $string; } /** * Replace color tags in a string. * * @param string $text The original text. * @param string $tag The matched tag. * @param string $match The match. * @param ColorStyle $style The color style to apply. * * @return mixed * * @since 1.0 */ private function replaceColors($text, $tag, $match, Colorstyle $style) { $replace = $this->noColors ? $match : "\033[" . $style . "m" . $match . "\033[0m"; return str_replace('<' . $tag . '>' . $match . '', $replace, $text); } /** * Adds predefined color styles to the ColorProcessor object * * @return Stdout Instance of $this to allow chaining. * * @since 1.0 */ private function addPredefinedStyles() { $this->addStyle( 'info', new ColorStyle('green', '', array('bold')) ); $this->addStyle( 'comment', new ColorStyle('yellow', '', array('bold')) ); $this->addStyle( 'question', new ColorStyle('black', 'cyan') ); $this->addStyle( 'error', new ColorStyle('white', 'red') ); return $this; } } PKY[J002framework/Joomla/Application/Cli/Output/Stdout.phpnuW+Aprocessor->process($text) . ($nl ? "\n" : null)); return $this; } } PKY[mF/framework/Joomla/Application/Cli/Output/Xml.phpnuW+A 0, 'red' => 1, 'green' => 2, 'yellow' => 3, 'blue' => 4, 'magenta' => 5, 'cyan' => 6, 'white' => 7 ); /** * Known styles * * @var array * @since 1.0 */ private static $knownOptions = array( 'bold' => 1, 'underscore' => 4, 'blink' => 5, 'reverse' => 7, ); /** * Foreground base value * * @var integer * @since 1.0 */ private static $fgBase = 30; /** * Background base value * * @var integer * @since 1.0 */ private static $bgBase = 40; /** * Foreground color * * @var integer * @since 1.0 */ private $fgColor = 0; /** * Background color * * @var integer * @since 1.0 */ private $bgColor = 0; /** * Array of style options * * @var array * @since 1.0 */ private $options = array(); /** * Constructor * * @param string $fg Foreground color. * @param string $bg Background color. * @param array $options Style options. * * @since 1.0 * @throws \InvalidArgumentException */ public function __construct($fg = '', $bg = '', $options = array()) { if ($fg) { if (false == array_key_exists($fg, static::$knownColors)) { throw new \InvalidArgumentException( sprintf('Invalid foreground color "%1$s" [%2$s]', $fg, implode(', ', $this->getKnownColors()) ) ); } $this->fgColor = static::$fgBase + static::$knownColors[$fg]; } if ($bg) { if (false == array_key_exists($bg, static::$knownColors)) { throw new \InvalidArgumentException( sprintf('Invalid background color "%1$s" [%2$s]', $bg, implode(', ', $this->getKnownColors()) ) ); } $this->bgColor = static::$bgBase + static::$knownColors[$bg]; } foreach ($options as $option) { if (false == array_key_exists($option, static::$knownOptions)) { throw new \InvalidArgumentException( sprintf('Invalid option "%1$s" [%2$s]', $option, implode(', ', $this->getKnownOptions()) ) ); } $this->options[] = $option; } } /** * Convert to a string. * * @return string * * @since 1.0 */ public function __toString() { return $this->getStyle(); } /** * Create a color style from a parameter string. * * Example: fg=red;bg=blue;options=bold,blink * * @param string $string The parameter string. * * @return ColorStyle Instance of $this to allow chaining. * * @since 1.0 * @throws \RuntimeException */ public static function fromString($string) { $fg = ''; $bg = ''; $options = array(); $parts = explode(';', $string); foreach ($parts as $part) { $subParts = explode('=', $part); if (count($subParts) < 2) { continue; } switch ($subParts[0]) { case 'fg': $fg = $subParts[1]; break; case 'bg': $bg = $subParts[1]; break; case 'options': $options = explode(',', $subParts[1]); break; default: throw new \RuntimeException('Invalid option'); break; } } return new self($fg, $bg, $options); } /** * Get the translated color code. * * @return string * * @since 1.0 */ public function getStyle() { $values = array(); if ($this->fgColor) { $values[] = $this->fgColor; } if ($this->bgColor) { $values[] = $this->bgColor; } foreach ($this->options as $option) { $values[] = static::$knownOptions[$option]; } return implode(';', $values); } /** * Get the known colors. * * @return string * * @since 1.0 */ public function getKnownColors() { return array_keys(static::$knownColors); } /** * Get the known options. * * @return array * * @since 1.0 */ public function getKnownOptions() { return array_keys(static::$knownOptions); } } PKY[շ - -&framework/Joomla/Registry/Registry.phpnuW+Adata = new \stdClass; // Optionally load supplied data. if (is_array($data) || is_object($data)) { $this->bindData($this->data, $data); } elseif (!empty($data) && is_string($data)) { $this->loadString($data); } } /** * Magic function to clone the registry object. * * @return Registry * * @since 1.0 */ public function __clone() { $this->data = unserialize(serialize($this->data)); } /** * Magic function to render this object as a string using default args of toString method. * * @return string * * @since 1.0 */ public function __toString() { return $this->toString(); } /** * Implementation for the JsonSerializable interface. * Allows us to pass Registry objects to json_encode. * * @return object * * @since 1.0 * @note The interface is only present in PHP 5.4 and up. */ public function jsonSerialize() { return $this->data; } /** * Sets a default value if not already assigned. * * @param string $key The name of the parameter. * @param mixed $default An optional value for the parameter. * * @return mixed The value set, or the default if the value was not previously set (or null). * * @since 1.0 */ public function def($key, $default = '') { $value = $this->get($key, $default); $this->set($key, $value); return $value; } /** * Check if a registry path exists. * * @param string $path Registry path (e.g. joomla.content.showauthor) * * @return boolean * * @since 1.0 */ public function exists($path) { // Explode the registry path into an array $nodes = explode('.', $path); if ($nodes) { // Initialize the current node to be the registry root. $node = $this->data; // Traverse the registry to find the correct node for the result. for ($i = 0, $n = count($nodes); $i < $n; $i++) { if (isset($node->$nodes[$i])) { $node = $node->$nodes[$i]; } else { break; } if ($i + 1 == $n) { return true; } } } return false; } /** * Get a registry value. * * @param string $path Registry path (e.g. joomla.content.showauthor) * @param mixed $default Optional default value, returned if the internal value is null. * * @return mixed Value of entry or null * * @since 1.0 */ public function get($path, $default = null) { $result = $default; if (!strpos($path, '.')) { return (isset($this->data->$path) && $this->data->$path !== null && $this->data->$path !== '') ? $this->data->$path : $default; } // Explode the registry path into an array $nodes = explode('.', $path); // Initialize the current node to be the registry root. $node = $this->data; $found = false; // Traverse the registry to find the correct node for the result. foreach ($nodes as $n) { if (isset($node->$n)) { $node = $node->$n; $found = true; } else { $found = false; break; } } if ($found && $node !== null && $node !== '') { $result = $node; } return $result; } /** * Returns a reference to a global Registry object, only creating it * if it doesn't already exist. * * This method must be invoked as: *
$registry = Registry::getInstance($id);
* * @param string $id An ID for the registry instance * * @return Registry The Registry object. * * @since 1.0 */ public static function getInstance($id) { if (empty(self::$instances[$id])) { self::$instances[$id] = new self; } return self::$instances[$id]; } /** * Load a associative array of values into the default namespace * * @param array $array Associative array of value to load * * @return Registry Return this object to support chaining. * * @since 1.0 */ public function loadArray($array) { $this->bindData($this->data, $array); return $this; } /** * Load the public variables of the object into the default namespace. * * @param object $object The object holding the publics to load * * @return Registry Return this object to support chaining. * * @since 1.0 */ public function loadObject($object) { $this->bindData($this->data, $object); return $this; } /** * Load the contents of a file into the registry * * @param string $file Path to file to load * @param string $format Format of the file [optional: defaults to JSON] * @param array $options Options used by the formatter * * @return Registry Return this object to support chaining. * * @since 1.0 */ public function loadFile($file, $format = 'JSON', $options = array()) { $data = file_get_contents($file); return $this->loadString($data, $format, $options); } /** * Load a string into the registry * * @param string $data String to load into the registry * @param string $format Format of the string * @param array $options Options used by the formatter * * @return Registry Return this object to support chaining. * * @since 1.0 */ public function loadString($data, $format = 'JSON', $options = array()) { // Load a string into the given namespace [or default namespace if not given] $handler = AbstractRegistryFormat::getInstance($format); $obj = $handler->stringToObject($data, $options); $this->loadObject($obj); return $this; } /** * Merge a Registry object into this one * * @param Registry $source Source Registry object to merge. [@note Framework typehints this param] * @param boolean $recursive True to support recursive merge the children values. * * @return Registry Return this object to support chaining. * * @since 1.0 */ public function merge($source, $recursive = false) { if (!$source instanceof Registry) { return false; } $data = $source->toArray(); $array = array(); foreach ($data as $k => $v) { if (($v !== null) && ($v !== '')) { $array[$k] = $v; } } $this->bindData($this->data, $array, $recursive); return $this; } /** * Checks whether an offset exists in the iterator. * * @param mixed $offset The array offset. * * @return boolean True if the offset exists, false otherwise. * * @since 1.0 */ public function offsetExists($offset) { return (boolean) ($this->get($offset) !== null); } /** * Gets an offset in the iterator. * * @param mixed $offset The array offset. * * @return mixed The array value if it exists, null otherwise. * * @since 1.0 */ public function offsetGet($offset) { return $this->get($offset); } /** * Sets an offset in the iterator. * * @param mixed $offset The array offset. * @param mixed $value The array value. * * @return void * * @since 1.0 */ public function offsetSet($offset, $value) { $this->set($offset, $value); } /** * Unsets an offset in the iterator. * * @param mixed $offset The array offset. * * @return void * * @since 1.0 */ public function offsetUnset($offset) { $this->set($offset, null); } /** * Set a registry value. * * @param string $path Registry Path (e.g. joomla.content.showauthor) * @param mixed $value Value of entry * * @return mixed The value of the that has been set. * * @since 1.0 */ public function set($path, $value) { $result = null; /** * Explode the registry path into an array and remove empty * nodes that occur as a result of a double dot. ex: joomla..test * Finally, re-key the array so they are sequential. */ $nodes = array_values(array_filter(explode('.', $path), 'strlen')); if ($nodes) { // Initialize the current node to be the registry root. $node = $this->data; // Traverse the registry to find the correct node for the result. for ($i = 0, $n = count($nodes) - 1; $i < $n; $i++) { if (!isset($node->$nodes[$i]) && ($i != $n)) { $node->$nodes[$i] = new \stdClass; } $node = $node->$nodes[$i]; } // Get the old value if exists so we can return it $result = $node->$nodes[$i] = $value; } return $result; } /** * Transforms a namespace to an array * * @return array An associative array holding the namespace data * * @since 1.0 */ public function toArray() { return (array) $this->asArray($this->data); } /** * Transforms a namespace to an object * * @return object An an object holding the namespace data * * @since 1.0 */ public function toObject() { return $this->data; } /** * Get a namespace in a given string format * * @param string $format Format to return the string in * @param mixed $options Parameters used by the formatter, see formatters for more info * * @return string Namespace in string format * * @since 1.0 */ public function toString($format = 'JSON', $options = array()) { // Return a namespace in a given format $handler = AbstractRegistryFormat::getInstance($format); return $handler->objectToString($this->data, $options); } /** * Method to recursively bind data to a parent object. * * @param object $parent The parent object on which to attach the data values. * @param mixed $data An array or object of data to bind to the parent object. * @param boolean $recursive True to support recursive bindData. * * @return void * * @since 1.0 */ protected function bindData($parent, $data, $recursive = true) { // Ensure the input data is an array. if (is_object($data)) { $data = get_object_vars($data); } else { $data = (array) $data; } foreach ($data as $k => $v) { // Modification from joomla/registry package - Using CMS JArrayHelper versus importing joomla/utilities package if ($recursive && ((is_array($v) && \JArrayHelper::isAssociative($v)) || is_object($v))) { if (!isset($parent->$k)) { $parent->$k = new \stdClass; } $this->bindData($parent->$k, $v); } else { $parent->$k = $v; } } } /** * Method to recursively convert an object of data to an array. * * @param object $data An object of data to return as an array. * * @return array Array representation of the input object. * * @since 1.0 */ protected function asArray($data) { $array = array(); if (is_object($data)) { $data = get_object_vars($data); } foreach ($data as $k => $v) { if (is_object($v) || is_array($v)) { $array[$k] = $this->asArray($v); } else { $array[$k] = $v; } } return $array; } } PKY[R(framework/Joomla/Registry/Format/Php.phpnuW+A $v) { if (is_scalar($v)) { $vars .= "\tpublic $" . $k . " = '" . addcslashes($v, '\\\'') . "';\n"; } elseif (is_array($v) || is_object($v)) { $vars .= "\tpublic $" . $k . " = " . $this->getArrayString((array) $v) . ";\n"; } } $str = ""; } return $str; } /** * Parse a PHP class formatted string and convert it into an object. * * @param string $data PHP Class formatted string to convert. * @param array $options Options used by the formatter. * * @return object Data object. * * @since 1.0 */ public function stringToObject($data, array $options = array()) { return true; } /** * Method to get an array as an exported string. * * @param array $a The array to get as a string. * * @return array * * @since 1.0 */ protected function getArrayString($a) { $s = 'array('; $i = 0; foreach ($a as $k => $v) { $s .= ($i) ? ', ' : ''; $s .= '"' . $k . '" => '; if (is_array($v) || is_object($v)) { $s .= $this->getArrayString((array) $v); } else { $s .= '"' . addslashes($v) . '"'; } $i++; } $s .= ')'; return $s; } } PKY[V+framework/Joomla/Registry/Format/index.htmlnuW+A PKY[x- )framework/Joomla/Registry/Format/Yaml.phpnuW+Aparser = new SymfonyYamlParser; $this->dumper = new SymfonyYamlDumper; } /** * Converts an object into a YAML formatted string. * We use json_* to convert the passed object to an array. * * @param object $object Data source object. * @param array $options Options used by the formatter. * * @return string YAML formatted string. * * @since 1.0 */ public function objectToString($object, $options = array()) { $array = json_decode(json_encode($object), true); return $this->dumper->dump($array, 2, 0); } /** * Parse a YAML formatted string and convert it into an object. * We use the json_* methods to convert the parsed YAML array to an object. * * @param string $data YAML formatted string to convert. * @param array $options Options used by the formatter. * * @return object Data object. * * @since 1.0 */ public function stringToObject($data, array $options = array()) { $array = $this->parser->parse(trim($data)); return json_decode(json_encode($array)); } } PKY[ ^ѽ)framework/Joomla/Registry/Format/Json.phpnuW+A false)) { $data = trim($data); if ((substr($data, 0, 1) != '{') && (substr($data, -1, 1) != '}')) { $ini = AbstractRegistryFormat::getInstance('Ini'); $obj = $ini->stringToObject($data, $options); } else { $obj = json_decode($data); } return $obj; } } PKY[-&&(framework/Joomla/Registry/Format/Ini.phpnuW+A $value) { // If the value is an object then we need to put it in a local section. if (is_object($value)) { // Add the section line. $local[] = ''; $local[] = '[' . $key . ']'; // Add the properties for this section. foreach (get_object_vars($value) as $k => $v) { $local[] = $k . '=' . $this->getValueAsINI($v); } } else { // Not in a section so add the property to the global array. $global[] = $key . '=' . $this->getValueAsINI($value); } } return implode("\n", array_merge($global, $local)); } /** * Parse an INI formatted string and convert it into an object. * * @param string $data INI formatted string to convert. * @param array $options An array of options used by the formatter, or a boolean setting to process sections. * * @return object Data object. * * @since 1.0 */ public function stringToObject($data, array $options = array()) { $sections = (isset($options['processSections'])) ? $options['processSections'] : false; // Check the memory cache for already processed strings. $hash = md5($data . ':' . (int) $sections); if (isset(self::$cache[$hash])) { return self::$cache[$hash]; } // If no lines present just return the object. if (empty($data)) { return new stdClass; } $obj = new stdClass; $section = false; $lines = explode("\n", $data); // Process the lines. foreach ($lines as $line) { // Trim any unnecessary whitespace. $line = trim($line); // Ignore empty lines and comments. if (empty($line) || ($line{0} == ';')) { continue; } if ($sections) { $length = strlen($line); // If we are processing sections and the line is a section add the object and continue. if (($line[0] == '[') && ($line[$length - 1] == ']')) { $section = substr($line, 1, $length - 2); $obj->$section = new stdClass; continue; } } elseif ($line{0} == '[') { continue; } // Check that an equal sign exists and is not the first character of the line. if (!strpos($line, '=')) { // Maybe throw exception? continue; } // Get the key and value for the line. list ($key, $value) = explode('=', $line, 2); // Validate the key. if (preg_match('/[^A-Z0-9_]/i', $key)) { // Maybe throw exception? continue; } // If the value is quoted then we assume it is a string. $length = strlen($value); if ($length && ($value[0] == '"') && ($value[$length - 1] == '"')) { // Strip the quotes and Convert the new line characters. $value = stripcslashes(substr($value, 1, ($length - 2))); $value = str_replace('\n', "\n", $value); } else { // If the value is not quoted, we assume it is not a string. // If the value is 'false' assume boolean false. if ($value == 'false') { $value = false; } elseif ($value == 'true') // If the value is 'true' assume boolean true. { $value = true; } elseif (is_numeric($value)) // If the value is numeric than it is either a float or int. { // If there is a period then we assume a float. if (strpos($value, '.') !== false) { $value = (float) $value; } else { $value = (int) $value; } } } // If a section is set add the key/value to the section, otherwise top level. if ($section) { $obj->$section->$key = $value; } else { $obj->$key = $value; } } // Cache the string to save cpu cycles -- thus the world :) self::$cache[$hash] = clone ($obj); return $obj; } /** * Method to get a value in an INI format. * * @param mixed $value The value to convert to INI format. * * @return string The value in INI format. * * @since 1.0 */ protected function getValueAsINI($value) { $string = ''; switch (gettype($value)) { case 'integer': case 'double': $string = $value; break; case 'boolean': $string = $value ? 'true' : 'false'; break; case 'string': // Sanitize any CRLF characters.. $string = '"' . str_replace(array("\r\n", "\n"), '\\n', $value) . '"'; break; } return $string; } } PKY[3 (framework/Joomla/Registry/Format/Xml.phpnuW+A'); // Iterate over the object members. $this->getXmlChildren($root, $object, $nodeName); return $root->asXML(); } /** * Parse a XML formatted string and convert it into an object. * * @param string $data XML formatted string to convert. * @param array $options Options used by the formatter. * * @return object Data object. * * @since 1.0 */ public function stringToObject($data, array $options = array()) { $obj = new stdClass; // Parse the XML string. $xml = simplexml_load_string($data); foreach ($xml->children() as $node) { $obj->$node['name'] = $this->getValueFromNode($node); } return $obj; } /** * Method to get a PHP native value for a SimpleXMLElement object. -- called recursively * * @param object $node SimpleXMLElement object for which to get the native value. * * @return mixed Native value of the SimpleXMLElement object. * * @since 1.0 */ protected function getValueFromNode($node) { switch ($node['type']) { case 'integer': $value = (string) $node; return (int) $value; break; case 'string': return (string) $node; break; case 'boolean': $value = (string) $node; return (bool) $value; break; case 'double': $value = (string) $node; return (float) $value; break; case 'array': $value = array(); foreach ($node->children() as $child) { $value[(string) $child['name']] = $this->getValueFromNode($child); } break; default: $value = new stdClass; foreach ($node->children() as $child) { $value->$child['name'] = $this->getValueFromNode($child); } break; } return $value; } /** * Method to build a level of the XML string -- called recursively * * @param SimpleXMLElement $node SimpleXMLElement object to attach children. * @param object $var Object that represents a node of the XML document. * @param string $nodeName The name to use for node elements. * * @return void * * @since 1.0 */ protected function getXmlChildren(SimpleXMLElement $node, $var, $nodeName) { // Iterate over the object members. foreach ((array) $var as $k => $v) { if (is_scalar($v)) { $n = $node->addChild($nodeName, $v); $n->addAttribute('name', $k); $n->addAttribute('type', gettype($v)); } else { $n = $node->addChild($nodeName); $n->addAttribute('name', $k); $n->addAttribute('type', gettype($v)); $this->getXmlChildren($n, $v, $nodeName); } } } } PKY[V$framework/Joomla/Registry/index.htmlnuW+A PKY[t(l``4framework/Joomla/Registry/AbstractRegistryFormat.phpnuW+Aparent = $parent; } /** * Create an alias for a given key for easy access. * * @param string $alias The alias name * @param string $key The key to alias * * @return Container */ public function alias($alias, $key) { $this->aliases[$alias] = $key; return $this; } /** * Search the aliases property for a matching alias key. * * @param string $key The key to search for. * * @return string * * @since 1.0 */ protected function resolveAlias($key) { if (isset($this->aliases[$key])) { return $this->aliases[$key]; } return $key; } /** * Build an object of class $key; * * @param string $key The class name to build. * @param boolean $shared True to create a shared resource. * * @return mixed Instance of class specified by $key with all dependencies injected. * Returns an object if the class exists and false otherwise * * @since 1.0 */ public function buildObject($key, $shared = false) { try { $reflection = new \ReflectionClass($key); } catch (\ReflectionException $e) { return false; } $constructor = $reflection->getConstructor(); // If there are no parameters, just return a new object. if (is_null($constructor)) { $callback = function () use ($key) { return new $key; }; } else { $newInstanceArgs = $this->getMethodArgs($constructor); // Create a callable for the dataStore $callback = function () use ($reflection, $newInstanceArgs) { return $reflection->newInstanceArgs($newInstanceArgs); }; } return $this->set($key, $callback, $shared)->get($key); } /** * Convenience method for building a shared object. * * @param string $key The class name to build. * * @return object Instance of class specified by $key with all dependencies injected. * * @since 1.0 */ public function buildSharedObject($key) { return $this->buildObject($key, true); } /** * Create a child Container with a new property scope that * that has the ability to access the parent scope when resolving. * * @return Container * * @since 1.0 */ public function createChild() { return new static($this); } /** * Extend a defined service Closure by wrapping the existing one with a new Closure. This * works very similar to a decorator pattern. Note that this only works on service Closures * that have been defined in the current Provider, not parent providers. * * @param string $key The unique identifier for the Closure or property. * @param \Closure $callable A Closure to wrap the original service Closure. * * @return void * * @since 1.0 * @throws \InvalidArgumentException */ public function extend($key, \Closure $callable) { $raw = $this->getRaw($key); if (is_null($raw)) { throw new \InvalidArgumentException(sprintf('The requested key %s does not exist to extend.', $key)); } $closure = function ($c) use($callable, $raw) { return $callable($raw['callback']($c), $c); }; $this->set($key, $closure, $raw['shared']); } /** * Build an array of constructor parameters. * * @param \ReflectionMethod $method Method for which to build the argument array. * * @return array Array of arguments to pass to the method. * * @since 1.0 * @throws DependencyResolutionException */ protected function getMethodArgs(\ReflectionMethod $method) { $methodArgs = array(); foreach ($method->getParameters() as $param) { $dependency = $param->getClass(); $dependencyVarName = $param->getName(); // If we have a dependency, that means it has been type-hinted. if (!is_null($dependency)) { $dependencyClassName = $dependency->getName(); // If the dependency class name is registered with this container or a parent, use it. if ($this->getRaw($dependencyClassName) !== null) { $depObject = $this->get($dependencyClassName); } else { $depObject = $this->buildObject($dependencyClassName); } if ($depObject instanceof $dependencyClassName) { $methodArgs[] = $depObject; continue; } } // Finally, if there is a default parameter, use it. if ($param->isOptional()) { $methodArgs[] = $param->getDefaultValue(); continue; } // Couldn't resolve dependency, and no default was provided. throw new DependencyResolutionException(sprintf('Could not resolve dependency: %s', $dependencyVarName)); } return $methodArgs; } /** * Method to set the key and callback to the dataStore array. * * @param string $key Name of dataStore key to set. * @param mixed $value Callable function to run or string to retrive when requesting the specified $key. * @param boolean $shared True to create and store a shared instance. * @param boolean $protected True to protect this item from being overwritten. Useful for services. * * @return \Joomla\DI\Container This instance to support chaining. * * @throws \OutOfBoundsException Thrown if the provided key is already set and is protected. * * @since 1.0 */ public function set($key, $value, $shared = false, $protected = false) { if (isset($this->dataStore[$key]) && $this->dataStore[$key]['protected'] === true) { throw new \OutOfBoundsException(sprintf('Key %s is protected and can\'t be overwritten.', $key)); } // If the provided $value is not a closure, make it one now for easy resolution. if (!($value instanceof \Closure)) { $value = function () use ($value) { return $value; }; } $this->dataStore[$key] = array( 'callback' => $value, 'shared' => $shared, 'protected' => $protected ); return $this; } /** * Convenience method for creating protected keys. * * @param string $key Name of dataStore key to set. * @param callable $callback Callable function to run when requesting the specified $key. * @param bool $shared True to create and store a shared instance. * * @return \Joomla\DI\Container This instance to support chaining. * * @since 1.0 */ public function protect($key, $callback, $shared = false) { return $this->set($key, $callback, $shared, true); } /** * Convenience method for creating shared keys. * * @param string $key Name of dataStore key to set. * @param callable $callback Callable function to run when requesting the specified $key. * @param bool $protected True to create and store a shared instance. * * @return \Joomla\DI\Container This instance to support chaining. * * @since 1.0 */ public function share($key, $callback, $protected = false) { return $this->set($key, $callback, true, $protected); } /** * Method to retrieve the results of running the $callback for the specified $key; * * @param string $key Name of the dataStore key to get. * @param boolean $forceNew True to force creation and return of a new instance. * * @return mixed Results of running the $callback for the specified $key. * * @since 1.0 * @throws \InvalidArgumentException */ public function get($key, $forceNew = false) { $raw = $this->getRaw($key); if (is_null($raw)) { throw new \InvalidArgumentException(sprintf('Key %s has not been registered with the container.', $key)); } if ($raw['shared']) { if (!isset($this->instances[$key]) || $forceNew) { $this->instances[$key] = $raw['callback']($this); } return $this->instances[$key]; } return $raw['callback']($this); } /** * Get the raw data assigned to a key. * * @param string $key The key for which to get the stored item. * * @return mixed */ protected function getRaw($key) { $key = $this->resolveAlias($key); if (isset($this->dataStore[$key])) { return $this->dataStore[$key]; } elseif ($this->parent instanceof Container) { return $this->parent->getRaw($key); } return null; } /** * Method to force the container to return a new instance * of the results of the callback for requested $key. * * @param string $key Name of the dataStore key to get. * * @return mixed Results of running the $callback for the specified $key. * * @since 1.0 */ public function getNewInstance($key) { return $this->get($key, true); } /** * Register a service provider to the container. * * @param ServiceProviderInterface $provider The service provider to register.w * * @return Container This object for chaining. * * @since 1.0 */ public function registerServiceProvider(ServiceProviderInterface $provider) { $provider->register($this); return $this; } } PKY[V(framework/Joomla/DI/Exception/index.htmlnuW+A PKY[]v22?framework/Joomla/DI/Exception/DependencyResolutionException.phpnuW+A PKY[bb0framework/Joomla/DI/ServiceProviderInterface.phpnuW+A Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! PKY[Psȁȁphpmailer/smtp.phpnuW+ADebugoutput) { case 'error_log': error_log($str); break; case 'html': //Cleans up output a bit for a better looking display that's HTML-safe echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, 'UTF-8')."
\n"; break; case 'echo': default: //Just echoes exactly what was received echo $str; } } /** * Initialize the class so that the data is in a known state. * @access public * @return SMTP */ public function __construct() { $this->smtp_conn = 0; $this->error = null; $this->helo_rply = null; $this->do_debug = 0; } ///////////////////////////////////////////////// // CONNECTION FUNCTIONS ///////////////////////////////////////////////// /** * Connect to an SMTP server * * SMTP CODE SUCCESS: 220 * SMTP CODE FAILURE: 421 * @access public * @param string $host SMTP server IP or host name * @param int $port The port number to connect to, or use the default port if not specified * @param int $timeout How long to wait for the connection to open * @param array $options An array of options compatible with stream_context_create() * @return bool */ public function Connect($host, $port = 0, $timeout = 30, $options = array()) { // Clear errors to avoid confusion $this->error = null; // Make sure we are __not__ connected if($this->connected()) { // Already connected, generate error $this->error = array('error' => 'Already connected to a server'); return false; } if(empty($port)) { $port = $this->SMTP_PORT; } // Connect to the SMTP server $errno = 0; $errstr = ''; $socket_context = stream_context_create($options); //Need to suppress errors here as connection failures can be handled at a higher level $this->smtp_conn = @stream_socket_client($host.":".$port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $socket_context); // Verify we connected properly if(empty($this->smtp_conn)) { $this->error = array('error' => 'Failed to connect to server', 'errno' => $errno, 'errstr' => $errstr); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ": $errstr ($errno)"); } return false; } // SMTP server can take longer to respond, give longer timeout for first read // Windows does not have support for this timeout function if(substr(PHP_OS, 0, 3) != 'WIN') { $max = ini_get('max_execution_time'); if ($max != 0 && $timeout > $max) { // Don't bother if unlimited @set_time_limit($timeout); } stream_set_timeout($this->smtp_conn, $timeout, 0); } // get any announcement $announce = $this->get_lines(); if($this->do_debug >= 2) { $this->edebug('SMTP -> FROM SERVER:' . $announce); } return true; } /** * Initiate a TLS communication with the server. * * SMTP CODE 220 Ready to start TLS * SMTP CODE 501 Syntax error (no parameters allowed) * SMTP CODE 454 TLS not available due to temporary reason * @access public * @return bool success */ public function StartTLS() { $this->error = null; # to avoid confusion if(!$this->connected()) { $this->error = array('error' => 'Called StartTLS() without being connected'); return false; } $this->client_send('STARTTLS' . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($this->do_debug >= 2) { $this->edebug('SMTP -> FROM SERVER:' . $rply); } if($code != 220) { $this->error = array('error' => 'STARTTLS not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } // Begin encrypted connection if(!stream_socket_enable_crypto($this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT)) { return false; } return true; } /** * Performs SMTP authentication. Must be run after running the * Hello() method. Returns true if successfully authenticated. * @access public * @param string $username * @param string $password * @param string $authtype * @param string $realm * @param string $workstation * @return bool */ public function Authenticate($username, $password, $authtype='LOGIN', $realm='', $workstation='') { if (empty($authtype)) { $authtype = 'LOGIN'; } switch ($authtype) { case 'PLAIN': // Start authentication $this->client_send('AUTH PLAIN' . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($code != 334) { $this->error = array('error' => 'AUTH not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } // Send encoded username and password $this->client_send(base64_encode("\0".$username."\0".$password) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($code != 235) { $this->error = array('error' => 'Authentication not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } break; case 'LOGIN': // Start authentication $this->client_send('AUTH LOGIN' . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($code != 334) { $this->error = array('error' => 'AUTH not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } // Send encoded username $this->client_send(base64_encode($username) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($code != 334) { $this->error = array('error' => 'Username not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } // Send encoded password $this->client_send(base64_encode($password) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($code != 235) { $this->error = array('error' => 'Password not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } break; case 'NTLM': /* * ntlm_sasl_client.php ** Bundled with Permission ** ** How to telnet in windows: http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx ** PROTOCOL Documentation http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication */ if (file_exists('extras/ntlm_sasl_client.php')) { require_once 'extras/ntlm_sasl_client.php'; } $temp = new stdClass(); $ntlm_client = new ntlm_sasl_client_class; if(! $ntlm_client->Initialize($temp)){//let's test if every function its available $this->error = array('error' => $temp->error); if($this->do_debug >= 1) { $this->edebug('You need to enable some modules in your php.ini file: ' . $this->error['error']); } return false; } $msg1 = $ntlm_client->TypeMsg1($realm, $workstation);//msg1 $this->client_send('AUTH NTLM ' . base64_encode($msg1) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($code != 334) { $this->error = array('error' => 'AUTH not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } $challenge = substr($rply, 3);//though 0 based, there is a white space after the 3 digit number....//msg2 $challenge = base64_decode($challenge); $ntlm_res = $ntlm_client->NTLMResponse(substr($challenge, 24, 8), $password); $msg3 = $ntlm_client->TypeMsg3($ntlm_res, $username, $realm, $workstation);//msg3 // Send encoded username $this->client_send(base64_encode($msg3) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($code != 235) { $this->error = array('error' => 'Could not authenticate', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } break; case 'CRAM-MD5': // Start authentication $this->client_send('AUTH CRAM-MD5' . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($code != 334) { $this->error = array('error' => 'AUTH not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } // Get the challenge $challenge = base64_decode(substr($rply, 4)); // Build the response $response = $username . ' ' . $this->hmac($challenge, $password); // Send encoded credentials $this->client_send(base64_encode($response) . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($code != 235) { $this->error = array('error' => 'Credentials not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } break; } return true; } /** * Works like hash_hmac('md5', $data, $key) in case that function is not available * @access protected * @param string $data * @param string $key * @return string */ protected function hmac($data, $key) { if (function_exists('hash_hmac')) { return hash_hmac('md5', $data, $key); } // The following borrowed from http://php.net/manual/en/function.mhash.php#27225 // RFC 2104 HMAC implementation for php. // Creates an md5 HMAC. // Eliminates the need to install mhash to compute a HMAC // Hacked by Lance Rushing $b = 64; // byte length for md5 if (strlen($key) > $b) { $key = pack('H*', md5($key)); } $key = str_pad($key, $b, chr(0x00)); $ipad = str_pad('', $b, chr(0x36)); $opad = str_pad('', $b, chr(0x5c)); $k_ipad = $key ^ $ipad ; $k_opad = $key ^ $opad; return md5($k_opad . pack('H*', md5($k_ipad . $data))); } /** * Returns true if connected to a server otherwise false * @access public * @return bool */ public function Connected() { if(!empty($this->smtp_conn)) { $sock_status = stream_get_meta_data($this->smtp_conn); if($sock_status['eof']) { // the socket is valid but we are not connected if($this->do_debug >= 1) { $this->edebug('SMTP -> NOTICE: EOF caught while checking if connected'); } $this->Close(); return false; } return true; // everything looks good } return false; } /** * Closes the socket and cleans up the state of the class. * It is not considered good to use this function without * first trying to use QUIT. * @access public * @return void */ public function Close() { $this->error = null; // so there is no confusion $this->helo_rply = null; if(!empty($this->smtp_conn)) { // close the connection and cleanup fclose($this->smtp_conn); $this->smtp_conn = 0; } } ///////////////////////////////////////////////// // SMTP COMMANDS ///////////////////////////////////////////////// /** * Issues a data command and sends the msg_data to the server * finializing the mail transaction. $msg_data is the message * that is to be send with the headers. Each header needs to be * on a single line followed by a with the message headers * and the message body being separated by and additional . * * Implements rfc 821: DATA * * SMTP CODE INTERMEDIATE: 354 * [data] * . * SMTP CODE SUCCESS: 250 * SMTP CODE FAILURE: 552, 554, 451, 452 * SMTP CODE FAILURE: 451, 554 * SMTP CODE ERROR : 500, 501, 503, 421 * @access public * @param string $msg_data * @return bool */ public function Data($msg_data) { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array( 'error' => 'Called Data() without being connected'); return false; } $this->client_send('DATA' . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($this->do_debug >= 2) { $this->edebug('SMTP -> FROM SERVER:' . $rply); } if($code != 354) { $this->error = array('error' => 'DATA command not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } /* the server is ready to accept data! * according to rfc 821 we should not send more than 1000 * including the CRLF * characters on a single line so we will break the data up * into lines by \r and/or \n then if needed we will break * each of those into smaller lines to fit within the limit. * in addition we will be looking for lines that start with * a period '.' and append and additional period '.' to that * line. NOTE: this does not count towards limit. */ // normalize the line breaks so we know the explode works $msg_data = str_replace("\r\n", "\n", $msg_data); $msg_data = str_replace("\r", "\n", $msg_data); $lines = explode("\n", $msg_data); /* we need to find a good way to determine is headers are * in the msg_data or if it is a straight msg body * currently I am assuming rfc 822 definitions of msg headers * and if the first field of the first line (':' sperated) * does not contain a space then it _should_ be a header * and we can process all lines before a blank "" line as * headers. */ $field = substr($lines[0], 0, strpos($lines[0], ':')); $in_headers = false; if(!empty($field) && !strstr($field, ' ')) { $in_headers = true; } $max_line_length = 998; // used below; set here for ease in change while(list(, $line) = @each($lines)) { $lines_out = null; if($line == '' && $in_headers) { $in_headers = false; } // ok we need to break this line up into several smaller lines while(strlen($line) > $max_line_length) { $pos = strrpos(substr($line, 0, $max_line_length), ' '); // Patch to fix DOS attack if(!$pos) { $pos = $max_line_length - 1; $lines_out[] = substr($line, 0, $pos); $line = substr($line, $pos); } else { $lines_out[] = substr($line, 0, $pos); $line = substr($line, $pos + 1); } /* if processing headers add a LWSP-char to the front of new line * rfc 822 on long msg headers */ if($in_headers) { $line = "\t" . $line; } } $lines_out[] = $line; // send the lines to the server while(list(, $line_out) = @each($lines_out)) { if(strlen($line_out) > 0) { if(substr($line_out, 0, 1) == '.') { $line_out = '.' . $line_out; } } $this->client_send($line_out . $this->CRLF); } } // message data has been sent $this->client_send($this->CRLF . '.' . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($this->do_debug >= 2) { $this->edebug('SMTP -> FROM SERVER:' . $rply); } if($code != 250) { $this->error = array('error' => 'DATA not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } return true; } /** * Sends the HELO command to the smtp server. * This makes sure that we and the server are in * the same known state. * * Implements from rfc 821: HELO * * SMTP CODE SUCCESS: 250 * SMTP CODE ERROR : 500, 501, 504, 421 * @access public * @param string $host * @return bool */ public function Hello($host = '') { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array( 'error' => 'Called Hello() without being connected'); return false; } // if hostname for HELO was not specified send default if(empty($host)) { // determine appropriate default to send to server $host = 'localhost'; } // Send extended hello first (RFC 2821) if(!$this->SendHello('EHLO', $host)) { if(!$this->SendHello('HELO', $host)) { return false; } } return true; } /** * Sends a HELO/EHLO command. * @access protected * @param string $hello * @param string $host * @return bool */ protected function SendHello($hello, $host) { $this->client_send($hello . ' ' . $host . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($this->do_debug >= 2) { $this->edebug('SMTP -> FROM SERVER: ' . $rply); } if($code != 250) { $this->error = array('error' => $hello . ' not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } $this->helo_rply = $rply; return true; } /** * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more Recipient * commands may be called followed by a Data command. * * Implements rfc 821: MAIL FROM: * * SMTP CODE SUCCESS: 250 * SMTP CODE SUCCESS: 552, 451, 452 * SMTP CODE SUCCESS: 500, 501, 421 * @access public * @param string $from * @return bool */ public function Mail($from) { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array( 'error' => 'Called Mail() without being connected'); return false; } $useVerp = ($this->do_verp ? ' XVERP' : ''); $this->client_send('MAIL FROM:<' . $from . '>' . $useVerp . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($this->do_debug >= 2) { $this->edebug('SMTP -> FROM SERVER:' . $rply); } if($code != 250) { $this->error = array('error' => 'MAIL not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } return true; } /** * Sends the quit command to the server and then closes the socket * if there is no error or the $close_on_error argument is true. * * Implements from rfc 821: QUIT * * SMTP CODE SUCCESS: 221 * SMTP CODE ERROR : 500 * @access public * @param bool $close_on_error * @return bool */ public function Quit($close_on_error = true) { $this->error = null; // so there is no confusion if(!$this->connected()) { $this->error = array( 'error' => 'Called Quit() without being connected'); return false; } // send the quit command to the server $this->client_send('quit' . $this->CRLF); // get any good-bye messages $byemsg = $this->get_lines(); if($this->do_debug >= 2) { $this->edebug('SMTP -> FROM SERVER:' . $byemsg); } $rval = true; $e = null; $code = substr($byemsg, 0, 3); if($code != 221) { // use e as a tmp var cause Close will overwrite $this->error $e = array('error' => 'SMTP server rejected quit command', 'smtp_code' => $code, 'smtp_rply' => substr($byemsg, 4)); $rval = false; if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $e['error'] . ': ' . $byemsg); } } if(empty($e) || $close_on_error) { $this->Close(); } return $rval; } /** * Sends the command RCPT to the SMTP server with the TO: argument of $to. * Returns true if the recipient was accepted false if it was rejected. * * Implements from rfc 821: RCPT TO: * * SMTP CODE SUCCESS: 250, 251 * SMTP CODE FAILURE: 550, 551, 552, 553, 450, 451, 452 * SMTP CODE ERROR : 500, 501, 503, 421 * @access public * @param string $to * @return bool */ public function Recipient($to) { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array( 'error' => 'Called Recipient() without being connected'); return false; } $this->client_send('RCPT TO:<' . $to . '>' . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($this->do_debug >= 2) { $this->edebug('SMTP -> FROM SERVER:' . $rply); } if($code != 250 && $code != 251) { $this->error = array('error' => 'RCPT not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } return true; } /** * Sends the RSET command to abort and transaction that is * currently in progress. Returns true if successful false * otherwise. * * Implements rfc 821: RSET * * SMTP CODE SUCCESS: 250 * SMTP CODE ERROR : 500, 501, 504, 421 * @access public * @return bool */ public function Reset() { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array('error' => 'Called Reset() without being connected'); return false; } $this->client_send('RSET' . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($this->do_debug >= 2) { $this->edebug('SMTP -> FROM SERVER:' . $rply); } if($code != 250) { $this->error = array('error' => 'RSET failed', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } return true; } /** * Starts a mail transaction from the email address specified in * $from. Returns true if successful or false otherwise. If True * the mail transaction is started and then one or more Recipient * commands may be called followed by a Data command. This command * will send the message to the users terminal if they are logged * in and send them an email. * * Implements rfc 821: SAML FROM: * * SMTP CODE SUCCESS: 250 * SMTP CODE SUCCESS: 552, 451, 452 * SMTP CODE SUCCESS: 500, 501, 502, 421 * @access public * @param string $from * @return bool */ public function SendAndMail($from) { $this->error = null; // so no confusion is caused if(!$this->connected()) { $this->error = array( 'error' => 'Called SendAndMail() without being connected'); return false; } $this->client_send('SAML FROM:' . $from . $this->CRLF); $rply = $this->get_lines(); $code = substr($rply, 0, 3); if($this->do_debug >= 2) { $this->edebug('SMTP -> FROM SERVER:' . $rply); } if($code != 250) { $this->error = array('error' => 'SAML not accepted from server', 'smtp_code' => $code, 'smtp_msg' => substr($rply, 4)); if($this->do_debug >= 1) { $this->edebug('SMTP -> ERROR: ' . $this->error['error'] . ': ' . $rply); } return false; } return true; } /** * This is an optional command for SMTP that this class does not * support. This method is here to make the RFC821 Definition * complete for this class and __may__ be implimented in the future * * Implements from rfc 821: TURN * * SMTP CODE SUCCESS: 250 * SMTP CODE FAILURE: 502 * SMTP CODE ERROR : 500, 503 * @access public * @return bool */ public function Turn() { $this->error = array('error' => 'This method, TURN, of the SMTP '. 'is not implemented'); if($this->do_debug >= 1) { $this->edebug('SMTP -> NOTICE: ' . $this->error['error']); } return false; } /** * Sends data to the server * @param string $data * @access public * @return Integer number of bytes sent to the server or FALSE on error */ public function client_send($data) { if ($this->do_debug >= 1) { $this->edebug("CLIENT -> SMTP: $data"); } return fwrite($this->smtp_conn, $data); } /** * Get the current error * @access public * @return array */ public function getError() { return $this->error; } ///////////////////////////////////////////////// // INTERNAL FUNCTIONS ///////////////////////////////////////////////// /** * Read in as many lines as possible * either before eof or socket timeout occurs on the operation. * With SMTP we can tell if we have more lines to read if the * 4th character is '-' symbol. If it is a space then we don't * need to read anything else. * @access protected * @return string */ protected function get_lines() { $data = ''; $endtime = 0; /* If for some reason the fp is bad, don't inf loop */ if (!is_resource($this->smtp_conn)) { return $data; } stream_set_timeout($this->smtp_conn, $this->Timeout); if ($this->Timelimit > 0) { $endtime = time() + $this->Timelimit; } while(is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { $str = @fgets($this->smtp_conn, 515); if($this->do_debug >= 4) { $this->edebug("SMTP -> get_lines(): \$data was \"$data\""); $this->edebug("SMTP -> get_lines(): \$str is \"$str\""); } $data .= $str; if($this->do_debug >= 4) { $this->edebug("SMTP -> get_lines(): \$data is \"$data\""); } // if 4th character is a space, we are done reading, break the loop if(substr($str, 3, 1) == ' ') { break; } // Timed-out? Log and break $info = stream_get_meta_data($this->smtp_conn); if ($info['timed_out']) { if($this->do_debug >= 4) { $this->edebug('SMTP -> get_lines(): timed-out (' . $this->Timeout . ' seconds)'); } break; } // Now check if reads took too long if ($endtime) { if (time() > $endtime) { if($this->do_debug >= 4) { $this->edebug('SMTP -> get_lines(): timelimit reached (' . $this->Timelimit . ' seconds)'); } break; } } } return $data; } } PKY[Vphpmailer/index.htmlnuW+A PKY[Vphpmailer/language/index.htmlnuW+A PKY[fz,phpmailer/language/phpmailer.lang-joomla.phpnuW+A * @author Andy Prevost * @author Jim Jagielski */ class POP3 { /** * Default POP3 port * @var int */ public $POP3_PORT = 110; /** * Default Timeout * @var int */ public $POP3_TIMEOUT = 30; /** * POP3 Carriage Return + Line Feed * @var string */ public $CRLF = "\r\n"; /** * Displaying Debug warnings? (0 = now, 1+ = yes) * @var int */ public $do_debug = 2; /** * POP3 Mail Server * @var string */ public $host; /** * POP3 Port * @var int */ public $port; /** * POP3 Timeout Value * @var int */ public $tval; /** * POP3 Username * @var string */ public $username; /** * POP3 Password * @var string */ public $password; /** * Sets the POP3 PHPMailer Version number * @var string */ public $Version = '5.2.6'; ///////////////////////////////////////////////// // PROPERTIES, PRIVATE AND PROTECTED ///////////////////////////////////////////////// /** * @var resource Resource handle for the POP connection socket */ private $pop_conn; /** * @var boolean Are we connected? */ private $connected; /** * @var array Error container */ private $error; // Error log array /** * Constructor, sets the initial values * @access public * @return POP3 */ public function __construct() { $this->pop_conn = 0; $this->connected = false; $this->error = null; } /** * Combination of public events - connect, login, disconnect * @access public * @param string $host * @param bool|int $port * @param bool|int $tval * @param string $username * @param string $password * @param int $debug_level * @return bool */ public function Authorise ($host, $port = false, $tval = false, $username, $password, $debug_level = 0) { $this->host = $host; // If no port value is passed, retrieve it if ($port == false) { $this->port = $this->POP3_PORT; } else { $this->port = $port; } // If no port value is passed, retrieve it if ($tval == false) { $this->tval = $this->POP3_TIMEOUT; } else { $this->tval = $tval; } $this->do_debug = $debug_level; $this->username = $username; $this->password = $password; // Refresh the error log $this->error = null; // Connect $result = $this->Connect($this->host, $this->port, $this->tval); if ($result) { $login_result = $this->Login($this->username, $this->password); if ($login_result) { $this->Disconnect(); return true; } } // We need to disconnect regardless if the login succeeded $this->Disconnect(); return false; } /** * Connect to the POP3 server * @access public * @param string $host * @param bool|int $port * @param integer $tval * @return boolean */ public function Connect ($host, $port = false, $tval = 30) { // Are we already connected? if ($this->connected) { return true; } /* On Windows this will raise a PHP Warning error if the hostname doesn't exist. Rather than suppress it with @fsockopen, let's capture it cleanly instead */ set_error_handler(array(&$this, 'catchWarning')); // Connect to the POP3 server $this->pop_conn = fsockopen($host, // POP3 Host $port, // Port # $errno, // Error Number $errstr, // Error Message $tval); // Timeout (seconds) // Restore the error handler restore_error_handler(); // Does the Error Log now contain anything? if ($this->error && $this->do_debug >= 1) { $this->displayErrors(); } // Did we connect? if ($this->pop_conn == false) { // It would appear not... $this->error = array( 'error' => "Failed to connect to server $host on port $port", 'errno' => $errno, 'errstr' => $errstr ); if ($this->do_debug >= 1) { $this->displayErrors(); } return false; } // Increase the stream time-out // Check for PHP 4.3.0 or later if (version_compare(phpversion(), '5.0.0', 'ge')) { stream_set_timeout($this->pop_conn, $tval, 0); } else { // Does not work on Windows if (substr(PHP_OS, 0, 3) !== 'WIN') { socket_set_timeout($this->pop_conn, $tval, 0); } } // Get the POP3 server response $pop3_response = $this->getResponse(); // Check for the +OK if ($this->checkResponse($pop3_response)) { // The connection is established and the POP3 server is talking $this->connected = true; return true; } return false; } /** * Login to the POP3 server (does not support APOP yet) * @access public * @param string $username * @param string $password * @return boolean */ public function Login ($username = '', $password = '') { if ($this->connected == false) { $this->error = 'Not connected to POP3 server'; if ($this->do_debug >= 1) { $this->displayErrors(); } } if (empty($username)) { $username = $this->username; } if (empty($password)) { $password = $this->password; } $pop_username = "USER $username" . $this->CRLF; $pop_password = "PASS $password" . $this->CRLF; // Send the Username $this->sendString($pop_username); $pop3_response = $this->getResponse(); if ($this->checkResponse($pop3_response)) { // Send the Password $this->sendString($pop_password); $pop3_response = $this->getResponse(); if ($this->checkResponse($pop3_response)) { return true; } } return false; } /** * Disconnect from the POP3 server * @access public */ public function Disconnect () { $this->sendString('QUIT'); fclose($this->pop_conn); } ///////////////////////////////////////////////// // Private Methods ///////////////////////////////////////////////// /** * Get the socket response back. * $size is the maximum number of bytes to retrieve * @access private * @param integer $size * @return string */ private function getResponse ($size = 128) { $pop3_response = fgets($this->pop_conn, $size); return $pop3_response; } /** * Send a string down the open socket connection to the POP3 server * @access private * @param string $string * @return integer */ private function sendString ($string) { $bytes_sent = fwrite($this->pop_conn, $string, strlen($string)); return $bytes_sent; } /** * Checks the POP3 server response for +OK or -ERR * @access private * @param string $string * @return boolean */ private function checkResponse ($string) { if (substr($string, 0, 3) !== '+OK') { $this->error = array( 'error' => "Server reported an error: $string", 'errno' => 0, 'errstr' => '' ); if ($this->do_debug >= 1) { $this->displayErrors(); } return false; } else { return true; } } /** * If debug is enabled, display the error message array * @access private */ private function displayErrors () { echo '
';

    foreach ($this->error as $single_error) {
      print_r($single_error);
    }

    echo '
'; } /** * Takes over from PHP for the socket warning handler * @access private * @param integer $errno * @param string $errstr * @param string $errfile * @param integer $errline */ private function catchWarning ($errno, $errstr, $errfile, $errline) { $this->error[] = array( 'error' => "Connecting to the POP3 server raised a PHP warning: ", 'errno' => $errno, 'errstr' => $errstr ); } // End of class } PKY[KRwRwphpmailer/phpmailer.phpnuW+AUseSendmailOptions) ) { $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header); } else { $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params); } return $rt; } /** * Outputs debugging info via user-defined method * @param string $str */ protected function edebug($str) { switch ($this->Debugoutput) { case 'error_log': error_log($str); break; case 'html': //Cleans up output a bit for a better looking display that's HTML-safe echo htmlentities(preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, $this->CharSet)."
\n"; break; case 'echo': default: //Just echoes exactly what was received echo $str; } } /** * Constructor * @param boolean $exceptions Should we throw external exceptions? */ public function __construct($exceptions = false) { $this->exceptions = ($exceptions == true); } /** * Destructor */ public function __destruct() { if ($this->Mailer == 'smtp') { //Close any open SMTP connection nicely $this->SmtpClose(); } } /** * Sets message type to HTML. * @param bool $ishtml * @return void */ public function IsHTML($ishtml = true) { if ($ishtml) { $this->ContentType = 'text/html'; } else { $this->ContentType = 'text/plain'; } } /** * Sets Mailer to send message using SMTP. * @return void */ public function IsSMTP() { $this->Mailer = 'smtp'; } /** * Sets Mailer to send message using PHP mail() function. * @return void */ public function IsMail() { $this->Mailer = 'mail'; } /** * Sets Mailer to send message using the $Sendmail program. * @return void */ public function IsSendmail() { if (!stristr(ini_get('sendmail_path'), 'sendmail')) { $this->Sendmail = '/var/qmail/bin/sendmail'; } $this->Mailer = 'sendmail'; } /** * Sets Mailer to send message using the qmail MTA. * @return void */ public function IsQmail() { if (stristr(ini_get('sendmail_path'), 'qmail')) { $this->Sendmail = '/var/qmail/bin/sendmail'; } $this->Mailer = 'sendmail'; } ///////////////////////////////////////////////// // METHODS, RECIPIENTS ///////////////////////////////////////////////// /** * Adds a "To" address. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddAddress($address, $name = '') { return $this->AddAnAddress('to', $address, $name); } /** * Adds a "Cc" address. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddCC($address, $name = '') { return $this->AddAnAddress('cc', $address, $name); } /** * Adds a "Bcc" address. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddBCC($address, $name = '') { return $this->AddAnAddress('bcc', $address, $name); } /** * Adds a "Reply-to" address. * @param string $address * @param string $name * @return boolean */ public function AddReplyTo($address, $name = '') { return $this->AddAnAddress('Reply-To', $address, $name); } /** * Adds an address to one of the recipient arrays * Addresses that have been added already return false, but do not throw exceptions * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo' * @param string $address The email address to send to * @param string $name * @throws phpmailerException * @return boolean true on success, false if address already used or invalid in some way * @access protected */ protected function AddAnAddress($kind, $address, $name = '') { if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) { $this->SetError($this->Lang('Invalid recipient array').': '.$kind); if ($this->exceptions) { throw new phpmailerException('Invalid recipient array: ' . $kind); } if ($this->SMTPDebug) { $this->edebug($this->Lang('Invalid recipient array').': '.$kind); } return false; } $address = trim($address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim if (!$this->ValidateAddress($address)) { $this->SetError($this->Lang('invalid_address').': '. $address); if ($this->exceptions) { throw new phpmailerException($this->Lang('invalid_address').': '.$address); } if ($this->SMTPDebug) { $this->edebug($this->Lang('invalid_address').': '.$address); } return false; } if ($kind != 'Reply-To') { if (!isset($this->all_recipients[strtolower($address)])) { array_push($this->$kind, array($address, $name)); $this->all_recipients[strtolower($address)] = true; return true; } } else { if (!array_key_exists(strtolower($address), $this->ReplyTo)) { $this->ReplyTo[strtolower($address)] = array($address, $name); return true; } } return false; } /** * Set the From and FromName properties * @param string $address * @param string $name * @param boolean $auto Whether to also set the Sender address, defaults to true * @throws phpmailerException * @return boolean */ public function SetFrom($address, $name = '', $auto = true) { $address = trim($address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim if (!$this->ValidateAddress($address)) { $this->SetError($this->Lang('invalid_address').': '. $address); if ($this->exceptions) { throw new phpmailerException($this->Lang('invalid_address').': '.$address); } if ($this->SMTPDebug) { $this->edebug($this->Lang('invalid_address').': '.$address); } return false; } $this->From = $address; $this->FromName = $name; if ($auto) { if (empty($this->Sender)) { $this->Sender = $address; } } return true; } /** * Check that a string looks roughly like an email address should * Static so it can be used without instantiation, public so people can overload * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to * not allow a@b type valid addresses :( * @link http://squiloople.com/2009/12/20/email-address-validation/ * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice. * @param string $address The email address to check * @return boolean * @static * @access public */ public static function ValidateAddress($address) { if (defined('PCRE_VERSION')) { //Check this instead of extension_loaded so it works when that function is disabled if (version_compare(PCRE_VERSION, '8.0') >= 0) { return (boolean)preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address); } else { //Fall back to an older regex that doesn't need a recent PCRE return (boolean)preg_match('/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', $address); } } else { //No PCRE! Do something _very_ approximate! //Check the address is 3 chars or longer and contains an @ that's not the first or last char return (strlen($address) >= 3 and strpos($address, '@') >= 1 and strpos($address, '@') != strlen($address) - 1); } } ///////////////////////////////////////////////// // METHODS, MAIL SENDING ///////////////////////////////////////////////// /** * Creates message and assigns Mailer. If the message is * not sent successfully then it returns false. Use the ErrorInfo * variable to view description of the error. * @throws phpmailerException * @return bool */ public function Send() { try { if(!$this->PreSend()) return false; return $this->PostSend(); } catch (phpmailerException $e) { $this->mailHeader = ''; $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } return false; } } /** * Prep mail by constructing all message entities * @throws phpmailerException * @return bool */ public function PreSend() { try { $this->mailHeader = ""; if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL); } // Set whether the message is multipart/alternative if(!empty($this->AltBody)) { $this->ContentType = 'multipart/alternative'; } $this->error_count = 0; // reset errors $this->SetMessageType(); //Refuse to send an empty message unless we are specifically allowing it if (!$this->AllowEmpty and empty($this->Body)) { throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL); } $this->MIMEHeader = $this->CreateHeader(); $this->MIMEBody = $this->CreateBody(); // To capture the complete message when using mail(), create // an extra header list which CreateHeader() doesn't fold in if ($this->Mailer == 'mail') { if (count($this->to) > 0) { $this->mailHeader .= $this->AddrAppend("To", $this->to); } else { $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;"); } $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject)))); } // digitally sign with DKIM if enabled if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) { $header_dkim = $this->DKIM_Add($this->MIMEHeader . $this->mailHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody); $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader; } return true; } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } return false; } } /** * Actual Email transport function * Send the email via the selected mechanism * @throws phpmailerException * @return bool */ public function PostSend() { try { // Choose the mailer and send through it switch($this->Mailer) { case 'sendmail': return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody); case 'smtp': return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody); case 'mail': return $this->MailSend($this->MIMEHeader, $this->MIMEBody); default: return $this->MailSend($this->MIMEHeader, $this->MIMEBody); } } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } if ($this->SMTPDebug) { $this->edebug($e->getMessage()."\n"); } } return false; } /** * Sends mail using the $Sendmail program. * @param string $header The message headers * @param string $body The message body * @throws phpmailerException * @access protected * @return bool */ protected function SendmailSend($header, $body) { if ($this->Sender != '') { $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); } else { $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); } if ($this->SingleTo === true) { foreach ($this->SingleToArray as $val) { if(!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fputs($mail, "To: " . $val . "\n"); fputs($mail, $header); fputs($mail, $body); $result = pclose($mail); // implement call back function if it exists $isSent = ($result == 0) ? 1 : 0; $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); if($result != 0) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } } else { if(!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fputs($mail, $header); fputs($mail, $body); $result = pclose($mail); // implement call back function if it exists $isSent = ($result == 0) ? 1 : 0; $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body); if($result != 0) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } return true; } /** * Sends mail using the PHP mail() function. * @param string $header The message headers * @param string $body The message body * @throws phpmailerException * @access protected * @return bool */ protected function MailSend($header, $body) { $toArr = array(); foreach($this->to as $t) { $toArr[] = $this->AddrFormat($t); } $to = implode(', ', $toArr); if (empty($this->Sender)) { $params = " "; } else { $params = sprintf("-f%s", $this->Sender); } if ($this->Sender != '' and !ini_get('safe_mode')) { $old_from = ini_get('sendmail_from'); ini_set('sendmail_from', $this->Sender); } $rt = false; if ($this->SingleTo === true && count($toArr) > 1) { foreach ($toArr as $val) { $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); } } else { $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body); } if (isset($old_from)) { ini_set('sendmail_from', $old_from); } if(!$rt) { throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL); } return true; } /** * Sends mail via SMTP using PhpSMTP * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. * @param string $header The message headers * @param string $body The message body * @throws phpmailerException * @uses SMTP * @access protected * @return bool */ protected function SmtpSend($header, $body) { require_once $this->PluginDir . 'smtp.php'; $bad_rcpt = array(); if(!$this->SmtpConnect()) { throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL); } $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; if(!$this->smtp->Mail($smtp_from)) { $this->SetError($this->Lang('from_failed') . $smtp_from . ' : ' .implode(',', $this->smtp->getError())); throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL); } // Attempt to send attach all recipients foreach($this->to as $to) { if (!$this->smtp->Recipient($to[0])) { $bad_rcpt[] = $to[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); } } foreach($this->cc as $cc) { if (!$this->smtp->Recipient($cc[0])) { $bad_rcpt[] = $cc[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); } } foreach($this->bcc as $bcc) { if (!$this->smtp->Recipient($bcc[0])) { $bad_rcpt[] = $bcc[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); } } if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses $badaddresses = implode(', ', $bad_rcpt); throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses); } if(!$this->smtp->Data($header . $body)) { throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL); } if($this->SMTPKeepAlive == true) { $this->smtp->Reset(); } else { $this->smtp->Quit(); $this->smtp->Close(); } return true; } /** * Initiates a connection to an SMTP server. * Returns false if the operation failed. * @param array $options An array of options compatible with stream_context_create() * @uses SMTP * @access public * @throws phpmailerException * @return bool */ public function SmtpConnect($options = array()) { if(is_null($this->smtp)) { $this->smtp = new SMTP; } //Already connected? if ($this->smtp->Connected()) { return true; } $this->smtp->Timeout = $this->Timeout; $this->smtp->do_debug = $this->SMTPDebug; $this->smtp->Debugoutput = $this->Debugoutput; $this->smtp->do_verp = $this->do_verp; $index = 0; $tls = ($this->SMTPSecure == 'tls'); $ssl = ($this->SMTPSecure == 'ssl'); $hosts = explode(';', $this->Host); $lastexception = null; foreach ($hosts as $hostentry) { $hostinfo = array(); $host = $hostentry; $port = $this->Port; if (preg_match('/^(.+):([0-9]+)$/', $hostentry, $hostinfo)) { //If $hostentry contains 'address:port', override default $host = $hostinfo[1]; $port = $hostinfo[2]; } if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout, $options)) { try { if ($this->Helo) { $hello = $this->Helo; } else { $hello = $this->ServerHostname(); } $this->smtp->Hello($hello); if ($tls) { if (!$this->smtp->StartTLS()) { throw new phpmailerException($this->Lang('connect_host')); } //We must resend HELO after tls negotiation $this->smtp->Hello($hello); } if ($this->SMTPAuth) { if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation)) { throw new phpmailerException($this->Lang('authenticate')); } } return true; } catch (phpmailerException $e) { $lastexception = $e; //We must have connected, but then failed TLS or Auth, so close connection nicely $this->smtp->Quit(); } } } //If we get here, all connection attempts have failed, so close connection hard $this->smtp->Close(); //As we've caught all exceptions, just report whatever the last one was if ($this->exceptions and !is_null($lastexception)) { throw $lastexception; } return false; } /** * Closes the active SMTP session if one exists. * @return void */ public function SmtpClose() { if ($this->smtp !== null) { if($this->smtp->Connected()) { $this->smtp->Quit(); $this->smtp->Close(); } } } /** * Sets the language for all class error messages. * Returns false if it cannot load the language file. The default language is English. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br") * @param string $lang_path Path to the language file directory * @return bool * @access public */ function SetLanguage($langcode = 'en', $lang_path = 'language/') { //Define full set of translatable strings $PHPMAILER_LANG = array( 'authenticate' => 'SMTP Error: Could not authenticate.', 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 'data_not_accepted' => 'SMTP Error: Data not accepted.', 'empty_message' => 'Message body empty', 'encoding' => 'Unknown encoding: ', 'execute' => 'Could not execute: ', 'file_access' => 'Could not access file: ', 'file_open' => 'File Error: Could not open file: ', 'from_failed' => 'The following From address failed: ', 'instantiate' => 'Could not instantiate mail function.', 'invalid_address' => 'Invalid address', 'mailer_not_supported' => ' mailer is not supported.', 'provide_address' => 'You must provide at least one recipient email address.', 'recipients_failed' => 'SMTP Error: The following recipients failed: ', 'signing' => 'Signing Error: ', 'smtp_connect_failed' => 'SMTP Connect() failed.', 'smtp_error' => 'SMTP server error: ', 'variable_set' => 'Cannot set or reset variable: ' ); //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"! $l = true; if ($langcode != 'en') { //There is no English translation file $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php'; } $this->language = $PHPMAILER_LANG; return ($l == true); //Returns false if language not found } /** * Return the current array of language strings * @return array */ public function GetTranslations() { return $this->language; } ///////////////////////////////////////////////// // METHODS, MESSAGE CREATION ///////////////////////////////////////////////// /** * Creates recipient headers. * @access public * @param string $type * @param array $addr * @return string */ public function AddrAppend($type, $addr) { $addr_str = $type . ': '; $addresses = array(); foreach ($addr as $a) { $addresses[] = $this->AddrFormat($a); } $addr_str .= implode(', ', $addresses); $addr_str .= $this->LE; return $addr_str; } /** * Formats an address correctly. * @access public * @param string $addr * @return string */ public function AddrFormat($addr) { if (empty($addr[1])) { return $this->SecureHeader($addr[0]); } else { return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">"; } } /** * Wraps message for use with mailers that do not * automatically perform wrapping and for quoted-printable. * Original written by philippe. * @param string $message The message to wrap * @param integer $length The line length to wrap to * @param boolean $qp_mode Whether to run in Quoted-Printable mode * @access public * @return string */ public function WrapText($message, $length, $qp_mode = false) { $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; // If utf-8 encoding is used, we will need to make sure we don't // split multibyte characters when we wrap $is_utf8 = (strtolower($this->CharSet) == "utf-8"); $lelen = strlen($this->LE); $crlflen = strlen(self::CRLF); $message = $this->FixEOL($message); if (substr($message, -$lelen) == $this->LE) { $message = substr($message, 0, -$lelen); } $line = explode($this->LE, $message); // Magic. We know FixEOL uses $LE $message = ''; for ($i = 0 ;$i < count($line); $i++) { $line_part = explode(' ', $line[$i]); $buf = ''; for ($e = 0; $e $length)) { $space_left = $length - strlen($buf) - $crlflen; if ($e != 0) { if ($space_left > 20) { $len = $space_left; if ($is_utf8) { $len = $this->UTF8CharBoundary($word, $len); } elseif (substr($word, $len - 1, 1) == "=") { $len--; } elseif (substr($word, $len - 2, 1) == "=") { $len -= 2; } $part = substr($word, 0, $len); $word = substr($word, $len); $buf .= ' ' . $part; $message .= $buf . sprintf("=%s", self::CRLF); } else { $message .= $buf . $soft_break; } $buf = ''; } while (strlen($word) > 0) { if ($length <= 0) { break; } $len = $length; if ($is_utf8) { $len = $this->UTF8CharBoundary($word, $len); } elseif (substr($word, $len - 1, 1) == "=") { $len--; } elseif (substr($word, $len - 2, 1) == "=") { $len -= 2; } $part = substr($word, 0, $len); $word = substr($word, $len); if (strlen($word) > 0) { $message .= $part . sprintf("=%s", self::CRLF); } else { $buf = $part; } } } else { $buf_o = $buf; $buf .= ($e == 0) ? $word : (' ' . $word); if (strlen($buf) > $length and $buf_o != '') { $message .= $buf_o . $soft_break; $buf = $word; } } } $message .= $buf . self::CRLF; } return $message; } /** * Finds last character boundary prior to maxLength in a utf-8 * quoted (printable) encoded string. * Original written by Colin Brown. * @access public * @param string $encodedText utf-8 QP text * @param int $maxLength find last character boundary prior to this length * @return int */ public function UTF8CharBoundary($encodedText, $maxLength) { $foundSplitPos = false; $lookBack = 3; while (!$foundSplitPos) { $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); $encodedCharPos = strpos($lastChunk, "="); if ($encodedCharPos !== false) { // Found start of encoded character byte within $lookBack block. // Check the encoded byte value (the 2 chars after the '=') $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); $dec = hexdec($hex); if ($dec < 128) { // Single byte character. // If the encoded char was found at pos 0, it will fit // otherwise reduce maxLength to start of the encoded char $maxLength = ($encodedCharPos == 0) ? $maxLength : $maxLength - ($lookBack - $encodedCharPos); $foundSplitPos = true; } elseif ($dec >= 192) { // First byte of a multi byte character // Reduce maxLength to split at start of character $maxLength = $maxLength - ($lookBack - $encodedCharPos); $foundSplitPos = true; } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back $lookBack += 3; } } else { // No encoded character found $foundSplitPos = true; } } return $maxLength; } /** * Set the body wrapping. * @access public * @return void */ public function SetWordWrap() { if($this->WordWrap < 1) { return; } switch($this->message_type) { case 'alt': case 'alt_inline': case 'alt_attach': case 'alt_inline_attach': $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap); break; default: $this->Body = $this->WrapText($this->Body, $this->WordWrap); break; } } /** * Assembles message header. * @access public * @return string The assembled header */ public function CreateHeader() { $result = ''; // Set the boundaries $uniq_id = md5(uniqid(time())); $this->boundary[1] = 'b1_' . $uniq_id; $this->boundary[2] = 'b2_' . $uniq_id; $this->boundary[3] = 'b3_' . $uniq_id; if ($this->MessageDate == '') { $result .= $this->HeaderLine('Date', self::RFCDate()); } else { $result .= $this->HeaderLine('Date', $this->MessageDate); } if ($this->ReturnPath) { $result .= $this->HeaderLine('Return-Path', '<'.trim($this->ReturnPath).'>'); } elseif ($this->Sender == '') { $result .= $this->HeaderLine('Return-Path', '<'.trim($this->From).'>'); } else { $result .= $this->HeaderLine('Return-Path', '<'.trim($this->Sender).'>'); } // To be created automatically by mail() if($this->Mailer != 'mail') { if ($this->SingleTo === true) { foreach($this->to as $t) { $this->SingleToArray[] = $this->AddrFormat($t); } } else { if(count($this->to) > 0) { $result .= $this->AddrAppend('To', $this->to); } elseif (count($this->cc) == 0) { $result .= $this->HeaderLine('To', 'undisclosed-recipients:;'); } } } $from = array(); $from[0][0] = trim($this->From); $from[0][1] = $this->FromName; $result .= $this->AddrAppend('From', $from); // sendmail and mail() extract Cc from the header before sending if(count($this->cc) > 0) { $result .= $this->AddrAppend('Cc', $this->cc); } // sendmail and mail() extract Bcc from the header before sending if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { $result .= $this->AddrAppend('Bcc', $this->bcc); } if(count($this->ReplyTo) > 0) { $result .= $this->AddrAppend('Reply-To', $this->ReplyTo); } // mail() sets the subject itself if($this->Mailer != 'mail') { $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject))); } if($this->MessageID != '') { $result .= $this->HeaderLine('Message-ID', $this->MessageID); } else { $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE); } $result .= $this->HeaderLine('X-Priority', $this->Priority); if ($this->XMailer == '') { $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (https://github.com/PHPMailer/PHPMailer/)'); } else { $myXmailer = trim($this->XMailer); if ($myXmailer) { $result .= $this->HeaderLine('X-Mailer', $myXmailer); } } if($this->ConfirmReadingTo != '') { $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); } // Add custom headers for($index = 0; $index < count($this->CustomHeader); $index++) { $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1]))); } if (!$this->sign_key_file) { $result .= $this->HeaderLine('MIME-Version', '1.0'); $result .= $this->GetMailMIME(); } return $result; } /** * Returns the message MIME. * @access public * @return string */ public function GetMailMIME() { $result = ''; switch($this->message_type) { case 'inline': $result .= $this->HeaderLine('Content-Type', 'multipart/related;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"'); break; case 'attach': case 'inline_attach': case 'alt_attach': case 'alt_inline_attach': $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"'); break; case 'alt': case 'alt_inline': $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1].'"'); break; default: // Catches case 'plain': and case '': $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet); break; } //RFC1341 part 5 says 7bit is assumed if not specified if ($this->Encoding != '7bit') { $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding); } if($this->Mailer != 'mail') { $result .= $this->LE; } return $result; } /** * Returns the MIME message (headers and body). Only really valid post PreSend(). * @access public * @return string */ public function GetSentMIMEMessage() { return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody; } /** * Assembles the message body. Returns an empty string on failure. * @access public * @throws phpmailerException * @return string The assembled message body */ public function CreateBody() { $body = ''; if ($this->sign_key_file) { $body .= $this->GetMailMIME().$this->LE; } $this->SetWordWrap(); switch($this->message_type) { case 'inline': $body .= $this->GetBoundary($this->boundary[1], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll('inline', $this->boundary[1]); break; case 'attach': $body .= $this->GetBoundary($this->boundary[1], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll('attachment', $this->boundary[1]); break; case 'inline_attach': $body .= $this->TextLine('--' . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll('inline', $this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll('attachment', $this->boundary[1]); break; case 'alt': $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; if(!empty($this->Ical)) { $body .= $this->GetBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', ''); $body .= $this->EncodeString($this->Ical, $this->Encoding); $body .= $this->LE.$this->LE; } $body .= $this->EndBoundary($this->boundary[1]); break; case 'alt_inline': $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->TextLine('--' . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll('inline', $this->boundary[2]); $body .= $this->LE; $body .= $this->EndBoundary($this->boundary[1]); break; case 'alt_attach': $body .= $this->TextLine('--' . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->EndBoundary($this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll('attachment', $this->boundary[1]); break; case 'alt_inline_attach': $body .= $this->TextLine('--' . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2].'"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->TextLine('--' . $this->boundary[2]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3].'"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll('inline', $this->boundary[3]); $body .= $this->LE; $body .= $this->EndBoundary($this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll('attachment', $this->boundary[1]); break; default: // catch case 'plain' and case '' $body .= $this->EncodeString($this->Body, $this->Encoding); break; } if ($this->IsError()) { $body = ''; } elseif ($this->sign_key_file) { try { if (!defined('PKCS7_TEXT')) { throw new phpmailerException($this->Lang('signing').' OpenSSL extension missing.'); } $file = tempnam(sys_get_temp_dir(), 'mail'); file_put_contents($file, $body); //TODO check this worked $signed = tempnam(sys_get_temp_dir(), 'signed'); if (@openssl_pkcs7_sign($file, $signed, 'file://'.realpath($this->sign_cert_file), array('file://'.realpath($this->sign_key_file), $this->sign_key_pass), null)) { @unlink($file); $body = file_get_contents($signed); @unlink($signed); } else { @unlink($file); @unlink($signed); throw new phpmailerException($this->Lang('signing').openssl_error_string()); } } catch (phpmailerException $e) { $body = ''; if ($this->exceptions) { throw $e; } } } return $body; } /** * Returns the start of a message boundary. * @access protected * @param string $boundary * @param string $charSet * @param string $contentType * @param string $encoding * @return string */ protected function GetBoundary($boundary, $charSet, $contentType, $encoding) { $result = ''; if($charSet == '') { $charSet = $this->CharSet; } if($contentType == '') { $contentType = $this->ContentType; } if($encoding == '') { $encoding = $this->Encoding; } $result .= $this->TextLine('--' . $boundary); $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet); $result .= $this->LE; $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding); $result .= $this->LE; return $result; } /** * Returns the end of a message boundary. * @access protected * @param string $boundary * @return string */ protected function EndBoundary($boundary) { return $this->LE . '--' . $boundary . '--' . $this->LE; } /** * Sets the message type. * @access protected * @return void */ protected function SetMessageType() { $this->message_type = array(); if($this->AlternativeExists()) $this->message_type[] = "alt"; if($this->InlineImageExists()) $this->message_type[] = "inline"; if($this->AttachmentExists()) $this->message_type[] = "attach"; $this->message_type = implode("_", $this->message_type); if($this->message_type == "") $this->message_type = "plain"; } /** * Returns a formatted header line. * @access public * @param string $name * @param string $value * @return string */ public function HeaderLine($name, $value) { return $name . ': ' . $value . $this->LE; } /** * Returns a formatted mail line. * @access public * @param string $value * @return string */ public function TextLine($value) { return $value . $this->LE; } ///////////////////////////////////////////////// // CLASS METHODS, ATTACHMENTS ///////////////////////////////////////////////// /** * Adds an attachment from a path on the filesystem. * Returns false if the file could not be found * or accessed. * @param string $path Path to the attachment. * @param string $name Overrides the attachment name. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @throws phpmailerException * @return bool */ public function AddAttachment($path, $name = '', $encoding = 'base64', $type = '') { try { if ( !@is_file($path) ) { throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE); } //If a MIME type is not specified, try to work it out from the file name if ($type == '') { $type = self::filenameToType($path); } $filename = basename($path); if ( $name == '' ) { $name = $filename; } $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => 'attachment', 7 => 0 ); } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } if ($this->SMTPDebug) { $this->edebug($e->getMessage()."\n"); } return false; } return true; } /** * Return the current array of attachments * @return array */ public function GetAttachments() { return $this->attachment; } /** * Attaches all fs, string, and binary attachments to the message. * Returns an empty string on failure. * @access protected * @param string $disposition_type * @param string $boundary * @return string */ protected function AttachAll($disposition_type, $boundary) { // Return text of body $mime = array(); $cidUniq = array(); $incl = array(); // Add all attachments foreach ($this->attachment as $attachment) { // CHECK IF IT IS A VALID DISPOSITION_FILTER if($attachment[6] == $disposition_type) { // Check for string attachment $string = ''; $path = ''; $bString = $attachment[5]; if ($bString) { $string = $attachment[0]; } else { $path = $attachment[0]; } $inclhash = md5(serialize($attachment)); if (in_array($inclhash, $incl)) { continue; } $incl[] = $inclhash; $filename = $attachment[1]; $name = $attachment[2]; $encoding = $attachment[3]; $type = $attachment[4]; $disposition = $attachment[6]; $cid = $attachment[7]; if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; } $cidUniq[$cid] = true; $mime[] = sprintf("--%s%s", $boundary, $this->LE); $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE); $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); if($disposition == 'inline') { $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); } //If a filename contains any of these chars, it should be quoted, but not otherwise: RFC2183 & RFC2045 5.1 //Fixes a warning in IETF's msglint MIME checker if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $name)) { $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE); } else { $mime[] = sprintf("Content-Disposition: %s; filename=%s%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE); } // Encode as string attachment if($bString) { $mime[] = $this->EncodeString($string, $encoding); if($this->IsError()) { return ''; } $mime[] = $this->LE.$this->LE; } else { $mime[] = $this->EncodeFile($path, $encoding); if($this->IsError()) { return ''; } $mime[] = $this->LE.$this->LE; } } } $mime[] = sprintf("--%s--%s", $boundary, $this->LE); return implode("", $mime); } /** * Encodes attachment in requested format. * Returns an empty string on failure. * @param string $path The full path to the file * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * @throws phpmailerException * @see EncodeFile() * @access protected * @return string */ protected function EncodeFile($path, $encoding = 'base64') { try { if (!is_readable($path)) { throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE); } $magic_quotes = get_magic_quotes_runtime(); if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { set_magic_quotes_runtime(0); } else { ini_set('magic_quotes_runtime', 0); } } $file_buffer = file_get_contents($path); $file_buffer = $this->EncodeString($file_buffer, $encoding); if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { set_magic_quotes_runtime($magic_quotes); } else { ini_set('magic_quotes_runtime', $magic_quotes); } } return $file_buffer; } catch (Exception $e) { $this->SetError($e->getMessage()); return ''; } } /** * Encodes string to requested format. * Returns an empty string on failure. * @param string $str The text to encode * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * @access public * @return string */ public function EncodeString($str, $encoding = 'base64') { $encoded = ''; switch(strtolower($encoding)) { case 'base64': $encoded = chunk_split(base64_encode($str), 76, $this->LE); break; case '7bit': case '8bit': $encoded = $this->FixEOL($str); //Make sure it ends with a line break if (substr($encoded, -(strlen($this->LE))) != $this->LE) $encoded .= $this->LE; break; case 'binary': $encoded = $str; break; case 'quoted-printable': $encoded = $this->EncodeQP($str); break; default: $this->SetError($this->Lang('encoding') . $encoding); break; } return $encoded; } /** * Encode a header string to best (shortest) of Q, B, quoted or none. * @access public * @param string $str * @param string $position * @return string */ public function EncodeHeader($str, $position = 'text') { $x = 0; switch (strtolower($position)) { case 'phrase': if (!preg_match('/[\200-\377]/', $str)) { // Can't use addslashes as we don't know what value has magic_quotes_sybase $encoded = addcslashes($str, "\0..\37\177\\\""); if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { return ($encoded); } else { return ("\"$encoded\""); } } $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); break; case 'comment': $x = preg_match_all('/[()"]/', $str, $matches); // Fall-through case 'text': default: $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); break; } if ($x == 0) { //There are no chars that need encoding return ($str); } $maxlen = 75 - 7 - strlen($this->CharSet); // Try to select the encoding which should produce the shortest output if ($x > strlen($str)/3) { //More than a third of the content will need encoding, so B encoding will be most efficient $encoding = 'B'; if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) { // Use a custom function which correctly encodes and wraps long // multibyte strings without breaking lines within a character $encoded = $this->Base64EncodeWrapMB($str, "\n"); } else { $encoded = base64_encode($str); $maxlen -= $maxlen % 4; $encoded = trim(chunk_split($encoded, $maxlen, "\n")); } } else { $encoding = 'Q'; $encoded = $this->EncodeQ($str, $position); $encoded = $this->WrapText($encoded, $maxlen, true); $encoded = str_replace('='.self::CRLF, "\n", trim($encoded)); } $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded); $encoded = trim(str_replace("\n", $this->LE, $encoded)); return $encoded; } /** * Checks if a string contains multibyte characters. * @access public * @param string $str multi-byte text to wrap encode * @return bool */ public function HasMultiBytes($str) { if (function_exists('mb_strlen')) { return (strlen($str) > mb_strlen($str, $this->CharSet)); } else { // Assume no multibytes (we can't handle without mbstring functions anyway) return false; } } /** * Correctly encodes and wraps long multibyte strings for mail headers * without breaking lines within a character. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php * @access public * @param string $str multi-byte text to wrap encode * @param string $lf string to use as linefeed/end-of-line * @return string */ public function Base64EncodeWrapMB($str, $lf=null) { $start = "=?".$this->CharSet."?B?"; $end = "?="; $encoded = ""; if ($lf === null) { $lf = $this->LE; } $mb_length = mb_strlen($str, $this->CharSet); // Each line must have length <= 75, including $start and $end $length = 75 - strlen($start) - strlen($end); // Average multi-byte ratio $ratio = $mb_length / strlen($str); // Base64 has a 4:3 ratio $offset = $avgLength = floor($length * $ratio * .75); for ($i = 0; $i < $mb_length; $i += $offset) { $lookBack = 0; do { $offset = $avgLength - $lookBack; $chunk = mb_substr($str, $i, $offset, $this->CharSet); $chunk = base64_encode($chunk); $lookBack++; } while (strlen($chunk) > $length); $encoded .= $chunk . $lf; } // Chomp the last linefeed $encoded = substr($encoded, 0, -strlen($lf)); return $encoded; } /** * Encode string to RFC2045 (6.7) quoted-printable format * @access public * @param string $string The text to encode * @param integer $line_max Number of chars allowed on a line before wrapping * @return string * @link PHP version adapted from http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 */ public function EncodeQP($string, $line_max = 76) { if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3) return quoted_printable_encode($string); } //Fall back to a pure PHP implementation $string = str_replace(array('%20', '%0D%0A.', '%0D%0A', '%'), array(' ', "\r\n=2E", "\r\n", '='), rawurlencode($string)); $string = preg_replace('/[^\r\n]{'.($line_max - 3).'}[^=\r\n]{2}/', "$0=\r\n", $string); return $string; } /** * Wrapper to preserve BC for old QP encoding function that was removed * @see EncodeQP() * @access public * @param string $string * @param integer $line_max * @param bool $space_conv * @return string */ public function EncodeQPphp($string, $line_max = 76, $space_conv = false) { return $this->EncodeQP($string, $line_max); } /** * Encode string to q encoding. * @link http://tools.ietf.org/html/rfc2047 * @param string $str the text to encode * @param string $position Where the text is going to be used, see the RFC for what that means * @access public * @return string */ public function EncodeQ($str, $position = 'text') { //There should not be any EOL in the string $pattern = ''; $encoded = str_replace(array("\r", "\n"), '', $str); switch (strtolower($position)) { case 'phrase': $pattern = '^A-Za-z0-9!*+\/ -'; break; case 'comment': $pattern = '\(\)"'; //note that we don't break here! //for this reason we build the $pattern without including delimiters and [] case 'text': default: //Replace every high ascii, control =, ? and _ characters //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern; break; } if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { foreach (array_unique($matches[0]) as $char) { $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); } } //Replace every spaces to _ (more readable than =20) return str_replace(' ', '_', $encoded); } /** * Adds a string or binary attachment (non-filesystem) to the list. * This method can be used to attach ascii or binary data, * such as a BLOB record from a database. * @param string $string String attachment data. * @param string $filename Name of the attachment. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @return void */ public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = '') { //If a MIME type is not specified, try to work it out from the file name if ($type == '') { $type = self::filenameToType($filename); } // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $filename, 2 => basename($filename), 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => 'attachment', 7 => 0 ); } /** * Add an embedded attachment from a file. * This can include images, sounds, and just about any other document type. * @param string $path Path to the attachment. * @param string $cid Content ID of the attachment; Use this to reference * the content when using an embedded image in HTML. * @param string $name Overrides the attachment name. * @param string $encoding File encoding (see $Encoding). * @param string $type File MIME type. * @return bool True on successfully adding an attachment */ public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '') { if ( !@is_file($path) ) { $this->SetError($this->Lang('file_access') . $path); return false; } //If a MIME type is not specified, try to work it out from the file name if ($type == '') { $type = self::filenameToType($path); } $filename = basename($path); if ( $name == '' ) { $name = $filename; } // Append to $attachment array $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => 'inline', 7 => $cid ); return true; } /** * Add an embedded stringified attachment. * This can include images, sounds, and just about any other document type. * Be sure to set the $type to an image type for images: * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'. * @param string $string The attachment binary data. * @param string $cid Content ID of the attachment; Use this to reference * the content when using an embedded image in HTML. * @param string $name * @param string $encoding File encoding (see $Encoding). * @param string $type MIME type. * @return bool True on successfully adding an attachment */ public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = '') { //If a MIME type is not specified, try to work it out from the name if ($type == '') { $type = self::filenameToType($name); } // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $name, 2 => $name, 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => 'inline', 7 => $cid ); return true; } /** * Returns true if an inline attachment is present. * @access public * @return bool */ public function InlineImageExists() { foreach($this->attachment as $attachment) { if ($attachment[6] == 'inline') { return true; } } return false; } /** * Returns true if an attachment (non-inline) is present. * @return bool */ public function AttachmentExists() { foreach($this->attachment as $attachment) { if ($attachment[6] == 'attachment') { return true; } } return false; } /** * Does this message have an alternative body set? * @return bool */ public function AlternativeExists() { return !empty($this->AltBody); } ///////////////////////////////////////////////// // CLASS METHODS, MESSAGE RESET ///////////////////////////////////////////////// /** * Clears all recipients assigned in the TO array. Returns void. * @return void */ public function ClearAddresses() { foreach($this->to as $to) { unset($this->all_recipients[strtolower($to[0])]); } $this->to = array(); } /** * Clears all recipients assigned in the CC array. Returns void. * @return void */ public function ClearCCs() { foreach($this->cc as $cc) { unset($this->all_recipients[strtolower($cc[0])]); } $this->cc = array(); } /** * Clears all recipients assigned in the BCC array. Returns void. * @return void */ public function ClearBCCs() { foreach($this->bcc as $bcc) { unset($this->all_recipients[strtolower($bcc[0])]); } $this->bcc = array(); } /** * Clears all recipients assigned in the ReplyTo array. Returns void. * @return void */ public function ClearReplyTos() { $this->ReplyTo = array(); } /** * Clears all recipients assigned in the TO, CC and BCC * array. Returns void. * @return void */ public function ClearAllRecipients() { $this->to = array(); $this->cc = array(); $this->bcc = array(); $this->all_recipients = array(); } /** * Clears all previously set filesystem, string, and binary * attachments. Returns void. * @return void */ public function ClearAttachments() { $this->attachment = array(); } /** * Clears all custom headers. Returns void. * @return void */ public function ClearCustomHeaders() { $this->CustomHeader = array(); } ///////////////////////////////////////////////// // CLASS METHODS, MISCELLANEOUS ///////////////////////////////////////////////// /** * Adds the error message to the error container. * @access protected * @param string $msg * @return void */ protected function SetError($msg) { $this->error_count++; if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { $lasterror = $this->smtp->getError(); if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { $msg .= '

' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "

\n"; } } $this->ErrorInfo = $msg; } /** * Returns the proper RFC 822 formatted date. * @access public * @return string * @static */ public static function RFCDate() { //Set the time zone to whatever the default is to avoid 500 errors //Will default to UTC if it's not set properly in php.ini date_default_timezone_set(@date_default_timezone_get()); return date('D, j M Y H:i:s O'); } /** * Returns the server hostname or 'localhost.localdomain' if unknown. * @access protected * @return string */ protected function ServerHostname() { if (!empty($this->Hostname)) { $result = $this->Hostname; } elseif (isset($_SERVER['SERVER_NAME'])) { $result = $_SERVER['SERVER_NAME']; } else { $result = 'localhost.localdomain'; } return $result; } /** * Returns a message in the appropriate language. * @access protected * @param string $key * @return string */ protected function Lang($key) { if(count($this->language) < 1) { $this->SetLanguage('en'); // set the default language } if(isset($this->language[$key])) { return $this->language[$key]; } else { return 'Language string failed to load: ' . $key; } } /** * Returns true if an error occurred. * @access public * @return bool */ public function IsError() { return ($this->error_count > 0); } /** * Changes every end of line from CRLF, CR or LF to $this->LE. * @access public * @param string $str String to FixEOL * @return string */ public function FixEOL($str) { // condense down to \n $nstr = str_replace(array("\r\n", "\r"), "\n", $str); // Now convert LE as needed if ($this->LE !== "\n") { $nstr = str_replace("\n", $this->LE, $nstr); } return $nstr; } /** * Adds a custom header. $name value can be overloaded to contain * both header name and value (name:value) * @access public * @param string $name custom header name * @param string $value header value * @return void */ public function AddCustomHeader($name, $value=null) { if ($value === null) { // Value passed in as name:value $this->CustomHeader[] = explode(':', $name, 2); } else { $this->CustomHeader[] = array($name, $value); } } /** * Creates a message from an HTML string, making modifications for inline images and backgrounds * and creates a plain-text version by converting the HTML * Overwrites any existing values in $this->Body and $this->AltBody * @access public * @param string $message HTML message string * @param string $basedir baseline directory for path * @param bool $advanced Whether to use the advanced HTML to text converter * @return string $message */ public function MsgHTML($message, $basedir = '', $advanced = false) { preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images); if (isset($images[2])) { foreach ($images[2] as $i => $url) { // do not change urls for absolute images (thanks to corvuscorax) if (!preg_match('#^[A-z]+://#', $url)) { $filename = basename($url); $directory = dirname($url); if ($directory == '.') { $directory = ''; } $cid = md5($url).'@phpmailer.0'; //RFC2392 S 2 if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; } if (strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; } if ($this->AddEmbeddedImage($basedir.$directory.$filename, $cid, $filename, 'base64', self::_mime_types(self::mb_pathinfo($filename, PATHINFO_EXTENSION)))) { $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"cid:".$cid."\"", $message); } } } } $this->IsHTML(true); if (empty($this->AltBody)) { $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n"; } //Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better $this->Body = $this->NormalizeBreaks($message); $this->AltBody = $this->NormalizeBreaks($this->html2text($message, $advanced)); return $this->Body; } /** * Convert an HTML string into a plain text version * @param string $html The HTML text to convert * @param bool $advanced Should this use the more complex html2text converter or just a simple one? * @return string */ public function html2text($html, $advanced = false) { if ($advanced) { if (file_exists('extras/class.html2text.php')) { require_once 'extras/class.html2text.php'; } $h = new html2text($html); return $h->get_text(); } return html_entity_decode(trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))), ENT_QUOTES, $this->CharSet); } /** * Gets the MIME type of the embedded or inline image * @param string $ext File extension * @access public * @return string MIME type of ext * @static */ public static function _mime_types($ext = '') { $mimes = array( 'xl' => 'application/excel', 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'bin' => 'application/macbinary', 'doc' => 'application/msword', 'word' => 'application/msword', 'class' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'exe' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'psd' => 'application/octet-stream', 'sea' => 'application/octet-stream', 'so' => 'application/octet-stream', 'oda' => 'application/oda', 'pdf' => 'application/pdf', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'wbxml' => 'application/vnd.wap.wbxml', 'wmlc' => 'application/vnd.wap.wmlc', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'gtar' => 'application/x-gtar', 'php3' => 'application/x-httpd-php', 'php4' => 'application/x-httpd-php', 'php' => 'application/x-httpd-php', 'phtml' => 'application/x-httpd-php', 'phps' => 'application/x-httpd-php-source', 'js' => 'application/x-javascript', 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'tar' => 'application/x-tar', 'tgz' => 'application/x-tar', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'zip' => 'application/zip', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mpga' => 'audio/mpeg', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'wav' => 'audio/x-wav', 'bmp' => 'image/bmp', 'gif' => 'image/gif', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'jpg' => 'image/jpeg', 'png' => 'image/png', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'eml' => 'message/rfc822', 'css' => 'text/css', 'html' => 'text/html', 'htm' => 'text/html', 'shtml' => 'text/html', 'log' => 'text/plain', 'text' => 'text/plain', 'txt' => 'text/plain', 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', 'xml' => 'text/xml', 'xsl' => 'text/xml', 'mpeg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mov' => 'video/quicktime', 'qt' => 'video/quicktime', 'rv' => 'video/vnd.rn-realvideo', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie' ); return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)]; } /** * Try to map a file name to a MIME type, default to application/octet-stream * @param string $filename A file name or full path, does not need to exist as a file * @return string * @static */ public static function filenameToType($filename) { //In case the path is a URL, strip any query string before getting extension $qpos = strpos($filename, '?'); if ($qpos !== false) { $filename = substr($filename, 0, $qpos); } $pathinfo = self::mb_pathinfo($filename); return self::_mime_types($pathinfo['extension']); } /** * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe. * Works similarly to the one in PHP >= 5.2.0 * @link http://www.php.net/manual/en/function.pathinfo.php#107461 * @param string $path A filename or path, does not need to exist as a file * @param integer|string $options Either a PATHINFO_* constant, or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2 * @return string|array * @static */ public static function mb_pathinfo($path, $options = null) { $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => ''); $m = array(); preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $m); if(array_key_exists(1, $m)) { $ret['dirname'] = $m[1]; } if(array_key_exists(2, $m)) { $ret['basename'] = $m[2]; } if(array_key_exists(5, $m)) { $ret['extension'] = $m[5]; } if(array_key_exists(3, $m)) { $ret['filename'] = $m[3]; } switch($options) { case PATHINFO_DIRNAME: case 'dirname': return $ret['dirname']; break; case PATHINFO_BASENAME: case 'basename': return $ret['basename']; break; case PATHINFO_EXTENSION: case 'extension': return $ret['extension']; break; case PATHINFO_FILENAME: case 'filename': return $ret['filename']; break; default: return $ret; } } /** * Set (or reset) Class Objects (variables) * * Usage Example: * $page->set('X-Priority', '3'); * * @access public * @param string $name * @param mixed $value * NOTE: will not work with arrays, there are no arrays to set/reset * @throws phpmailerException * @return bool * @todo Should this not be using __set() magic function? */ public function set($name, $value = '') { try { if (isset($this->$name) ) { $this->$name = $value; } else { throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL); } } catch (Exception $e) { $this->SetError($e->getMessage()); if ($e->getCode() == self::STOP_CRITICAL) { return false; } } return true; } /** * Strips newlines to prevent header injection. * @access public * @param string $str * @return string */ public function SecureHeader($str) { return trim(str_replace(array("\r", "\n"), '', $str)); } /** * Normalize UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format * Defaults to CRLF (for message bodies) and preserves consecutive breaks * @param string $text * @param string $breaktype What kind of line break to use, defaults to CRLF * @return string * @access public * @static */ public static function NormalizeBreaks($text, $breaktype = "\r\n") { return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text); } /** * Set the private key file and password to sign the message. * * @access public * @param string $cert_filename * @param string $key_filename * @param string $key_pass Password for private key */ public function Sign($cert_filename, $key_filename, $key_pass) { $this->sign_cert_file = $cert_filename; $this->sign_key_file = $key_filename; $this->sign_key_pass = $key_pass; } /** * Set the private key file and password to sign the message. * * @access public * @param string $txt * @return string */ public function DKIM_QP($txt) { $line = ''; for ($i = 0; $i < strlen($txt); $i++) { $ord = ord($txt[$i]); if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) { $line .= $txt[$i]; } else { $line .= "=".sprintf("%02X", $ord); } } return $line; } /** * Generate DKIM signature * * @access public * @param string $s Header * @throws phpmailerException * @return string */ public function DKIM_Sign($s) { if (!defined('PKCS7_TEXT')) { if ($this->exceptions) { throw new phpmailerException($this->Lang("signing").' OpenSSL extension missing.'); } return ''; } $privKeyStr = file_get_contents($this->DKIM_private); if ($this->DKIM_passphrase != '') { $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); } else { $privKey = $privKeyStr; } if (openssl_sign($s, $signature, $privKey)) { return base64_encode($signature); } return ''; } /** * Generate DKIM Canonicalization Header * * @access public * @param string $s Header * @return string */ public function DKIM_HeaderC($s) { $s = preg_replace("/\r\n\s+/", " ", $s); $lines = explode("\r\n", $s); foreach ($lines as $key => $line) { list($heading, $value) = explode(":", $line, 2); $heading = strtolower($heading); $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value } $s = implode("\r\n", $lines); return $s; } /** * Generate DKIM Canonicalization Body * * @access public * @param string $body Message Body * @return string */ public function DKIM_BodyC($body) { if ($body == '') return "\r\n"; // stabilize line endings $body = str_replace("\r\n", "\n", $body); $body = str_replace("\n", "\r\n", $body); // END stabilize line endings while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { $body = substr($body, 0, strlen($body) - 2); } return $body; } /** * Create the DKIM header, body, as new header * * @access public * @param string $headers_line Header lines * @param string $subject Subject * @param string $body Body * @return string */ public function DKIM_Add($headers_line, $subject, $body) { $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body $DKIMquery = 'dns/txt'; // Query method $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) $subject_header = "Subject: $subject"; $headers = explode($this->LE, $headers_line); $from_header = ''; $to_header = ''; $current = ''; foreach($headers as $header) { if (strpos($header, 'From:') === 0) { $from_header = $header; $current = 'from_header'; } elseif (strpos($header, 'To:') === 0) { $to_header = $header; $current = 'to_header'; } else { if($current && strpos($header, ' =?') === 0){ $current .= $header; } else { $current = ''; } } } $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable $body = $this->DKIM_BodyC($body); $DKIMlen = strlen($body) ; // Length of body $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";"; $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n". "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n". "\th=From:To:Subject;\r\n". "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n". "\tz=$from\r\n". "\t|$to\r\n". "\t|$subject;\r\n". "\tbh=" . $DKIMb64 . ";\r\n". "\tb="; $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs); $signed = $this->DKIM_Sign($toSign); return $dkimhdrs.$signed."\r\n"; } /** * Perform callback * @param boolean $isSent * @param string $to * @param string $cc * @param string $bcc * @param string $subject * @param string $body * @param string $from */ protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from = null) { if (!empty($this->action_function) && is_callable($this->action_function)) { $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from); call_user_func_array($this->action_function, $params); } } } /** * Exception handler for PHPMailer * @package PHPMailer */ class phpmailerException extends Exception { /** * Prettify error message output * @return string */ public function errorMessage() { $errorMsg = '' . $this->getMessage() . "
\n"; return $errorMsg; } } PKY[$MnMnphpmailer/phpmailer.php.backupnuW+AUseSendmailOptions) ) { $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header); } else { $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($subject)), $body, $header, $params); } return $rt; } /** * Outputs debugging info via user-defined method * @param string $str */ private function edebug($str) { if ($this->Debugoutput == "error_log") { error_log($str); } else { echo $str; } } /** * Constructor * @param boolean $exceptions Should we throw external exceptions? */ public function __construct($exceptions = false) { $this->exceptions = ($exceptions == true); } /** * Sets message type to HTML. * @param bool $ishtml * @return void */ public function IsHTML($ishtml = true) { if ($ishtml) { $this->ContentType = 'text/html'; } else { $this->ContentType = 'text/plain'; } } /** * Sets Mailer to send message using SMTP. * @return void * @deprecated */ public function IsSMTP() { $this->Mailer = 'smtp'; } /** * Sets Mailer to send message using PHP mail() function. * @return void * @deprecated */ public function IsMail() { $this->Mailer = 'mail'; } /** * Sets Mailer to send message using the $Sendmail program. * @return void * @deprecated */ public function IsSendmail() { if (!stristr(ini_get('sendmail_path'), 'sendmail')) { $this->Sendmail = '/var/qmail/bin/sendmail'; } $this->Mailer = 'sendmail'; } /** * Sets Mailer to send message using the qmail MTA. * @return void * @deprecated */ public function IsQmail() { if (stristr(ini_get('sendmail_path'), 'qmail')) { $this->Sendmail = '/var/qmail/bin/sendmail'; } $this->Mailer = 'sendmail'; } ///////////////////////////////////////////////// // METHODS, RECIPIENTS ///////////////////////////////////////////////// /** * Adds a "To" address. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddAddress($address, $name = '') { return $this->AddAnAddress('to', $address, $name); } /** * Adds a "Cc" address. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddCC($address, $name = '') { return $this->AddAnAddress('cc', $address, $name); } /** * Adds a "Bcc" address. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddBCC($address, $name = '') { return $this->AddAnAddress('bcc', $address, $name); } /** * Adds a "Reply-to" address. * @param string $address * @param string $name * @return boolean */ public function AddReplyTo($address, $name = '') { return $this->AddAnAddress('Reply-To', $address, $name); } /** * Adds an address to one of the recipient arrays * Addresses that have been added already return false, but do not throw exceptions * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo' * @param string $address The email address to send to * @param string $name * @throws phpmailerException * @return boolean true on success, false if address already used or invalid in some way * @access protected */ protected function AddAnAddress($kind, $address, $name = '') { if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) { $this->SetError($this->Lang('Invalid recipient array').': '.$kind); if ($this->exceptions) { throw new phpmailerException('Invalid recipient array: ' . $kind); } if ($this->SMTPDebug) { $this->edebug($this->Lang('Invalid recipient array').': '.$kind); } return false; } $address = trim($address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim if (!$this->ValidateAddress($address)) { $this->SetError($this->Lang('invalid_address').': '. $address); if ($this->exceptions) { throw new phpmailerException($this->Lang('invalid_address').': '.$address); } if ($this->SMTPDebug) { $this->edebug($this->Lang('invalid_address').': '.$address); } return false; } if ($kind != 'Reply-To') { if (!isset($this->all_recipients[strtolower($address)])) { array_push($this->$kind, array($address, $name)); $this->all_recipients[strtolower($address)] = true; return true; } } else { if (!array_key_exists(strtolower($address), $this->ReplyTo)) { $this->ReplyTo[strtolower($address)] = array($address, $name); return true; } } return false; } /** * Set the From and FromName properties * @param string $address * @param string $name * @param int $auto Also set Reply-To and Sender * @throws phpmailerException * @return boolean */ public function SetFrom($address, $name = '', $auto = 1) { $address = trim($address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim if (!$this->ValidateAddress($address)) { $this->SetError($this->Lang('invalid_address').': '. $address); if ($this->exceptions) { throw new phpmailerException($this->Lang('invalid_address').': '.$address); } if ($this->SMTPDebug) { $this->edebug($this->Lang('invalid_address').': '.$address); } return false; } $this->From = $address; $this->FromName = $name; if ($auto) { if (empty($this->ReplyTo)) { $this->AddAnAddress('Reply-To', $address, $name); } if (empty($this->Sender)) { $this->Sender = $address; } } return true; } /** * Check that a string looks roughly like an email address should * Static so it can be used without instantiation, public so people can overload * Conforms to RFC5322: Uses *correct* regex on which FILTER_VALIDATE_EMAIL is * based; So why not use FILTER_VALIDATE_EMAIL? Because it was broken to * not allow a@b type valid addresses :( * Some Versions of PHP break on the regex though, likely due to PCRE, so use * the older validation method for those users. (http://php.net/manual/en/pcre.installation.php) * @link http://squiloople.com/2009/12/20/email-address-validation/ * @copyright regex Copyright Michael Rushton 2009-10 | http://squiloople.com/ | Feel free to use and redistribute this code. But please keep this copyright notice. * @param string $address The email address to check * @return boolean * @static * @access public */ public static function ValidateAddress($address) { if ((defined('PCRE_VERSION')) && (version_compare(PCRE_VERSION, '8.0') >= 0)) { return preg_match('/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)((?>(?>(?>((?>(?>(?>\x0D\x0A)?[ ])+|(?>[ ]*\x0D\x0A)?[ ]+)?)(\((?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}|(?!(?:.*[a-f0-9][:\]]){7,})((?6)(?>:(?6)){0,5})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:|(?!(?:.*[a-f0-9]:){5,})(?8)?::(?>((?6)(?>:(?6)){0,3}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address); } elseif (function_exists('filter_var')) { //Introduced in PHP 5.2 if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) { return false; } else { return true; } } else { return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address); } } ///////////////////////////////////////////////// // METHODS, MAIL SENDING ///////////////////////////////////////////////// /** * Creates message and assigns Mailer. If the message is * not sent successfully then it returns false. Use the ErrorInfo * variable to view description of the error. * @throws phpmailerException * @return bool */ public function Send() { try { if(!$this->PreSend()) return false; return $this->PostSend(); } catch (phpmailerException $e) { $this->mailHeader = ''; $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } return false; } } /** * Prep mail by constructing all message entities * @throws phpmailerException * @return bool */ public function PreSend() { try { $this->mailHeader = ""; if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL); } // Set whether the message is multipart/alternative if(!empty($this->AltBody)) { $this->ContentType = 'multipart/alternative'; } $this->error_count = 0; // reset errors $this->SetMessageType(); //Refuse to send an empty message if (empty($this->Body)) { throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL); } $this->MIMEHeader = $this->CreateHeader(); $this->MIMEBody = $this->CreateBody(); // To capture the complete message when using mail(), create // an extra header list which CreateHeader() doesn't fold in if ($this->Mailer == 'mail') { if (count($this->to) > 0) { $this->mailHeader .= $this->AddrAppend("To", $this->to); } else { $this->mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;"); } $this->mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject)))); // if(count($this->cc) > 0) { // $this->mailHeader .= $this->AddrAppend("Cc", $this->cc); // } } // digitally sign with DKIM if enabled if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && !empty($this->DKIM_domain) && file_exists($this->DKIM_private)) { $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody); $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader; } return true; } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } return false; } } /** * Actual Email transport function * Send the email via the selected mechanism * @throws phpmailerException * @return bool */ public function PostSend() { try { // Choose the mailer and send through it switch($this->Mailer) { case 'sendmail': return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody); case 'smtp': return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody); case 'mail': return $this->MailSend($this->MIMEHeader, $this->MIMEBody); default: return $this->MailSend($this->MIMEHeader, $this->MIMEBody); } } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } if ($this->SMTPDebug) { $this->edebug($e->getMessage()."\n"); } } return false; } /** * Sends mail using the $Sendmail program. * @param string $header The message headers * @param string $body The message body * @throws phpmailerException * @access protected * @return bool */ protected function SendmailSend($header, $body) { if ($this->Sender != '') { $sendmail = sprintf("%s -oi -f%s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); } else { $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); } if ($this->SingleTo === true) { foreach ($this->SingleToArray as $val) { if(!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fputs($mail, "To: " . $val . "\n"); fputs($mail, $header); fputs($mail, $body); $result = pclose($mail); // implement call back function if it exists $isSent = ($result == 0) ? 1 : 0; $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); if($result != 0) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } } else { if(!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fputs($mail, $header); fputs($mail, $body); $result = pclose($mail); // implement call back function if it exists $isSent = ($result == 0) ? 1 : 0; $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body); if($result != 0) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } return true; } /** * Sends mail using the PHP mail() function. * @param string $header The message headers * @param string $body The message body * @throws phpmailerException * @access protected * @return bool */ protected function MailSend($header, $body) { $toArr = array(); foreach($this->to as $t) { $toArr[] = $this->AddrFormat($t); } $to = implode(', ', $toArr); if (empty($this->Sender)) { $params = "-oi "; } else { $params = sprintf("-oi -f%s", $this->Sender); } if ($this->Sender != '' and !ini_get('safe_mode')) { $old_from = ini_get('sendmail_from'); ini_set('sendmail_from', $this->Sender); } $rt = false; if ($this->SingleTo === true && count($toArr) > 1) { foreach ($toArr as $val) { $rt = $this->mail_passthru($val, $this->Subject, $body, $header, $params); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); } } else { $rt = $this->mail_passthru($to, $this->Subject, $body, $header, $params); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body); } if (isset($old_from)) { ini_set('sendmail_from', $old_from); } if(!$rt) { throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL); } return true; } /** * Sends mail via SMTP using PhpSMTP * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. * @param string $header The message headers * @param string $body The message body * @throws phpmailerException * @uses SMTP * @access protected * @return bool */ protected function SmtpSend($header, $body) { require_once $this->PluginDir . 'smtp.php'; $bad_rcpt = array(); if(!$this->SmtpConnect()) { throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL); } $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; if(!$this->smtp->Mail($smtp_from)) { $this->SetError($this->Lang('from_failed') . $smtp_from . " : " . implode(",",$this->smtp->getError())) ; throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL); } // Attempt to send attach all recipients foreach($this->to as $to) { if (!$this->smtp->Recipient($to[0])) { $bad_rcpt[] = $to[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); } } foreach($this->cc as $cc) { if (!$this->smtp->Recipient($cc[0])) { $bad_rcpt[] = $cc[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); } } foreach($this->bcc as $bcc) { if (!$this->smtp->Recipient($bcc[0])) { $bad_rcpt[] = $bcc[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); } } if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses $badaddresses = implode(', ', $bad_rcpt); throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses); } if(!$this->smtp->Data($header . $body)) { throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL); } if($this->SMTPKeepAlive == true) { $this->smtp->Reset(); } else { $this->smtp->Quit(); $this->smtp->Close(); } return true; } /** * Initiates a connection to an SMTP server. * Returns false if the operation failed. * @uses SMTP * @access public * @throws phpmailerException * @return bool */ public function SmtpConnect() { if(is_null($this->smtp)) { $this->smtp = new SMTP; } $this->smtp->Timeout = $this->Timeout; $this->smtp->do_debug = $this->SMTPDebug; $hosts = explode(';', $this->Host); $index = 0; $connection = $this->smtp->Connected(); // Retry while there is no connection try { while($index < count($hosts) && !$connection) { $hostinfo = array(); if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) { $host = $hostinfo[1]; $port = $hostinfo[2]; } else { $host = $hosts[$index]; $port = $this->Port; } $tls = ($this->SMTPSecure == 'tls'); $ssl = ($this->SMTPSecure == 'ssl'); if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) { $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname()); $this->smtp->Hello($hello); if ($tls) { if (!$this->smtp->StartTLS()) { throw new phpmailerException($this->Lang('connect_host')); } //We must resend HELO after tls negotiation $this->smtp->Hello($hello); } $connection = true; if ($this->SMTPAuth) { if (!$this->smtp->Authenticate($this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation)) { throw new phpmailerException($this->Lang('authenticate')); } } } $index++; if (!$connection) { throw new phpmailerException($this->Lang('connect_host')); } } } catch (phpmailerException $e) { $this->smtp->Reset(); if ($this->exceptions) { throw $e; } } return true; } /** * Closes the active SMTP session if one exists. * @return void */ public function SmtpClose() { if ($this->smtp !== null) { if($this->smtp->Connected()) { $this->smtp->Quit(); $this->smtp->Close(); } } } /** * Sets the language for all class error messages. * Returns false if it cannot load the language file. The default language is English. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br") * @param string $lang_path Path to the language file directory * @return bool * @access public */ function SetLanguage($langcode = 'en', $lang_path = 'language/') { //Define full set of translatable strings $PHPMAILER_LANG = array( 'authenticate' => 'SMTP Error: Could not authenticate.', 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 'data_not_accepted' => 'SMTP Error: Data not accepted.', 'empty_message' => 'Message body empty', 'encoding' => 'Unknown encoding: ', 'execute' => 'Could not execute: ', 'file_access' => 'Could not access file: ', 'file_open' => 'File Error: Could not open file: ', 'from_failed' => 'The following From address failed: ', 'instantiate' => 'Could not instantiate mail function.', 'invalid_address' => 'Invalid address', 'mailer_not_supported' => ' mailer is not supported.', 'provide_address' => 'You must provide at least one recipient email address.', 'recipients_failed' => 'SMTP Error: The following recipients failed: ', 'signing' => 'Signing Error: ', 'smtp_connect_failed' => 'SMTP Connect() failed.', 'smtp_error' => 'SMTP server error: ', 'variable_set' => 'Cannot set or reset variable: ' ); //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"! $l = true; if ($langcode != 'en') { //There is no English translation file $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php'; } $this->language = $PHPMAILER_LANG; return ($l == true); //Returns false if language not found } /** * Return the current array of language strings * @return array */ public function GetTranslations() { return $this->language; } ///////////////////////////////////////////////// // METHODS, MESSAGE CREATION ///////////////////////////////////////////////// /** * Creates recipient headers. * @access public * @param string $type * @param array $addr * @return string */ public function AddrAppend($type, $addr) { $addr_str = $type . ': '; $addresses = array(); foreach ($addr as $a) { $addresses[] = $this->AddrFormat($a); } $addr_str .= implode(', ', $addresses); $addr_str .= $this->LE; return $addr_str; } /** * Formats an address correctly. * @access public * @param string $addr * @return string */ public function AddrFormat($addr) { if (empty($addr[1])) { return $this->SecureHeader($addr[0]); } else { return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">"; } } /** * Wraps message for use with mailers that do not * automatically perform wrapping and for quoted-printable. * Original written by philippe. * @param string $message The message to wrap * @param integer $length The line length to wrap to * @param boolean $qp_mode Whether to run in Quoted-Printable mode * @access public * @return string */ public function WrapText($message, $length, $qp_mode = false) { $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; // If utf-8 encoding is used, we will need to make sure we don't // split multibyte characters when we wrap $is_utf8 = (strtolower($this->CharSet) == "utf-8"); $lelen = strlen($this->LE); $crlflen = strlen(self::CRLF); $message = $this->FixEOL($message); if (substr($message, -$lelen) == $this->LE) { $message = substr($message, 0, -$lelen); } $line = explode($this->LE, $message); // Magic. We know FixEOL uses $LE $message = ''; for ($i = 0 ;$i < count($line); $i++) { $line_part = explode(' ', $line[$i]); $buf = ''; for ($e = 0; $e $length)) { $space_left = $length - strlen($buf) - $crlflen; if ($e != 0) { if ($space_left > 20) { $len = $space_left; if ($is_utf8) { $len = $this->UTF8CharBoundary($word, $len); } elseif (substr($word, $len - 1, 1) == "=") { $len--; } elseif (substr($word, $len - 2, 1) == "=") { $len -= 2; } $part = substr($word, 0, $len); $word = substr($word, $len); $buf .= ' ' . $part; $message .= $buf . sprintf("=%s", self::CRLF); } else { $message .= $buf . $soft_break; } $buf = ''; } while (strlen($word) > 0) { $len = $length; if ($is_utf8) { $len = $this->UTF8CharBoundary($word, $len); } elseif (substr($word, $len - 1, 1) == "=") { $len--; } elseif (substr($word, $len - 2, 1) == "=") { $len -= 2; } $part = substr($word, 0, $len); $word = substr($word, $len); if (strlen($word) > 0) { $message .= $part . sprintf("=%s", self::CRLF); } else { $buf = $part; } } } else { $buf_o = $buf; $buf .= ($e == 0) ? $word : (' ' . $word); if (strlen($buf) > $length and $buf_o != '') { $message .= $buf_o . $soft_break; $buf = $word; } } } $message .= $buf . self::CRLF; } return $message; } /** * Finds last character boundary prior to maxLength in a utf-8 * quoted (printable) encoded string. * Original written by Colin Brown. * @access public * @param string $encodedText utf-8 QP text * @param int $maxLength find last character boundary prior to this length * @return int */ public function UTF8CharBoundary($encodedText, $maxLength) { $foundSplitPos = false; $lookBack = 3; while (!$foundSplitPos) { $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); $encodedCharPos = strpos($lastChunk, "="); if ($encodedCharPos !== false) { // Found start of encoded character byte within $lookBack block. // Check the encoded byte value (the 2 chars after the '=') $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); $dec = hexdec($hex); if ($dec < 128) { // Single byte character. // If the encoded char was found at pos 0, it will fit // otherwise reduce maxLength to start of the encoded char $maxLength = ($encodedCharPos == 0) ? $maxLength : $maxLength - ($lookBack - $encodedCharPos); $foundSplitPos = true; } elseif ($dec >= 192) { // First byte of a multi byte character // Reduce maxLength to split at start of character $maxLength = $maxLength - ($lookBack - $encodedCharPos); $foundSplitPos = true; } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back $lookBack += 3; } } else { // No encoded character found $foundSplitPos = true; } } return $maxLength; } /** * Set the body wrapping. * @access public * @return void */ public function SetWordWrap() { if($this->WordWrap < 1) { return; } switch($this->message_type) { case 'alt': case 'alt_inline': case 'alt_attach': case 'alt_inline_attach': $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap); break; default: $this->Body = $this->WrapText($this->Body, $this->WordWrap); break; } } /** * Assembles message header. * @access public * @return string The assembled header */ public function CreateHeader() { $result = ''; // Set the boundaries $uniq_id = md5(uniqid(time())); $this->boundary[1] = 'b1_' . $uniq_id; $this->boundary[2] = 'b2_' . $uniq_id; $this->boundary[3] = 'b3_' . $uniq_id; if ($this->MessageDate == '') { $result .= $this->HeaderLine('Date', self::RFCDate()); } else { $result .= $this->HeaderLine('Date', $this->MessageDate); } if ($this->ReturnPath) { $result .= $this->HeaderLine('Return-Path', trim($this->ReturnPath)); } elseif ($this->Sender == '') { $result .= $this->HeaderLine('Return-Path', trim($this->From)); } else { $result .= $this->HeaderLine('Return-Path', trim($this->Sender)); } // To be created automatically by mail() if($this->Mailer != 'mail') { if ($this->SingleTo === true) { foreach($this->to as $t) { $this->SingleToArray[] = $this->AddrFormat($t); } } else { if(count($this->to) > 0) { $result .= $this->AddrAppend('To', $this->to); } elseif (count($this->cc) == 0) { $result .= $this->HeaderLine('To', 'undisclosed-recipients:;'); } } } $from = array(); $from[0][0] = trim($this->From); $from[0][1] = $this->FromName; $result .= $this->AddrAppend('From', $from); // sendmail and mail() extract Cc from the header before sending if(count($this->cc) > 0) { $result .= $this->AddrAppend('Cc', $this->cc); } // sendmail and mail() extract Bcc from the header before sending if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { $result .= $this->AddrAppend('Bcc', $this->bcc); } if(count($this->ReplyTo) > 0) { $result .= $this->AddrAppend('Reply-To', $this->ReplyTo); } // mail() sets the subject itself if($this->Mailer != 'mail') { $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject))); } if($this->MessageID != '') { $result .= $this->HeaderLine('Message-ID', $this->MessageID); } else { $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE); } $result .= $this->HeaderLine('X-Priority', $this->Priority); if ($this->XMailer == '') { $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)'); } else { $myXmailer = trim($this->XMailer); if ($myXmailer) { $result .= $this->HeaderLine('X-Mailer', $myXmailer); } } if($this->ConfirmReadingTo != '') { $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); } // Add custom headers for($index = 0; $index < count($this->CustomHeader); $index++) { $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1]))); } if (!$this->sign_key_file) { $result .= $this->HeaderLine('MIME-Version', '1.0'); $result .= $this->GetMailMIME(); } return $result; } /** * Returns the message MIME. * @access public * @return string */ public function GetMailMIME() { $result = ''; switch($this->message_type) { case 'inline': $result .= $this->HeaderLine('Content-Type', 'multipart/related;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); break; case 'attach': case 'inline_attach': case 'alt_attach': case 'alt_inline_attach': $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); break; case 'alt': case 'alt_inline': $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); break; default: // Catches case 'plain': and case '': $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding); $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset='.$this->CharSet); break; } if($this->Mailer != 'mail') { $result .= $this->LE; } return $result; } /** * Returns the MIME message (headers and body). Only really valid post PreSend(). * @access public * @return string */ public function GetSentMIMEMessage() { return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody; } /** * Assembles the message body. Returns an empty string on failure. * @access public * @throws phpmailerException * @return string The assembled message body */ public function CreateBody() { $body = ''; if ($this->sign_key_file) { $body .= $this->GetMailMIME().$this->LE; } $this->SetWordWrap(); switch($this->message_type) { case 'inline': $body .= $this->GetBoundary($this->boundary[1], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll("inline", $this->boundary[1]); break; case 'attach': $body .= $this->GetBoundary($this->boundary[1], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; case 'inline_attach': $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll("inline", $this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; case 'alt': $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->EndBoundary($this->boundary[1]); break; case 'alt_inline': $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll("inline", $this->boundary[2]); $body .= $this->LE; $body .= $this->EndBoundary($this->boundary[1]); break; case 'alt_attach': $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->EndBoundary($this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; case 'alt_inline_attach': $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->TextLine("--" . $this->boundary[2]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll("inline", $this->boundary[3]); $body .= $this->LE; $body .= $this->EndBoundary($this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; default: // catch case 'plain' and case '' $body .= $this->EncodeString($this->Body, $this->Encoding); break; } if ($this->IsError()) { $body = ''; } elseif ($this->sign_key_file) { try { $file = tempnam('', 'mail'); file_put_contents($file, $body); //TODO check this worked $signed = tempnam("", "signed"); if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) { @unlink($file); $body = file_get_contents($signed); @unlink($signed); } else { @unlink($file); @unlink($signed); throw new phpmailerException($this->Lang("signing").openssl_error_string()); } } catch (phpmailerException $e) { $body = ''; if ($this->exceptions) { throw $e; } } } return $body; } /** * Returns the start of a message boundary. * @access protected * @param string $boundary * @param string $charSet * @param string $contentType * @param string $encoding * @return string */ protected function GetBoundary($boundary, $charSet, $contentType, $encoding) { $result = ''; if($charSet == '') { $charSet = $this->CharSet; } if($contentType == '') { $contentType = $this->ContentType; } if($encoding == '') { $encoding = $this->Encoding; } $result .= $this->TextLine('--' . $boundary); $result .= sprintf("Content-Type: %s; charset=%s", $contentType, $charSet); $result .= $this->LE; $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding); $result .= $this->LE; return $result; } /** * Returns the end of a message boundary. * @access protected * @param string $boundary * @return string */ protected function EndBoundary($boundary) { return $this->LE . '--' . $boundary . '--' . $this->LE; } /** * Sets the message type. * @access protected * @return void */ protected function SetMessageType() { $this->message_type = array(); if($this->AlternativeExists()) $this->message_type[] = "alt"; if($this->InlineImageExists()) $this->message_type[] = "inline"; if($this->AttachmentExists()) $this->message_type[] = "attach"; $this->message_type = implode("_", $this->message_type); if($this->message_type == "") $this->message_type = "plain"; } /** * Returns a formatted header line. * @access public * @param string $name * @param string $value * @return string */ public function HeaderLine($name, $value) { return $name . ': ' . $value . $this->LE; } /** * Returns a formatted mail line. * @access public * @param string $value * @return string */ public function TextLine($value) { return $value . $this->LE; } ///////////////////////////////////////////////// // CLASS METHODS, ATTACHMENTS ///////////////////////////////////////////////// /** * Adds an attachment from a path on the filesystem. * Returns false if the file could not be found * or accessed. * @param string $path Path to the attachment. * @param string $name Overrides the attachment name. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @throws phpmailerException * @return bool */ public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { try { if ( !@is_file($path) ) { throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE); } $filename = basename($path); if ( $name == '' ) { $name = $filename; } $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => 'attachment', 7 => 0 ); } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } if ($this->SMTPDebug) { $this->edebug($e->getMessage()."\n"); } if ( $e->getCode() == self::STOP_CRITICAL ) { return false; } } return true; } /** * Return the current array of attachments * @return array */ public function GetAttachments() { return $this->attachment; } /** * Attaches all fs, string, and binary attachments to the message. * Returns an empty string on failure. * @access protected * @param string $disposition_type * @param string $boundary * @return string */ protected function AttachAll($disposition_type, $boundary) { // Return text of body $mime = array(); $cidUniq = array(); $incl = array(); // Add all attachments foreach ($this->attachment as $attachment) { // CHECK IF IT IS A VALID DISPOSITION_FILTER if($attachment[6] == $disposition_type) { // Check for string attachment $string = ''; $path = ''; $bString = $attachment[5]; if ($bString) { $string = $attachment[0]; } else { $path = $attachment[0]; } $inclhash = md5(serialize($attachment)); if (in_array($inclhash, $incl)) { continue; } $incl[] = $inclhash; $filename = $attachment[1]; $name = $attachment[2]; $encoding = $attachment[3]; $type = $attachment[4]; $disposition = $attachment[6]; $cid = $attachment[7]; if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; } $cidUniq[$cid] = true; $mime[] = sprintf("--%s%s", $boundary, $this->LE); $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE); $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); if($disposition == 'inline') { $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); } $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE); // Encode as string attachment if($bString) { $mime[] = $this->EncodeString($string, $encoding); if($this->IsError()) { return ''; } $mime[] = $this->LE.$this->LE; } else { $mime[] = $this->EncodeFile($path, $encoding); if($this->IsError()) { return ''; } $mime[] = $this->LE.$this->LE; } } } $mime[] = sprintf("--%s--%s", $boundary, $this->LE); return implode("", $mime); } /** * Encodes attachment in requested format. * Returns an empty string on failure. * @param string $path The full path to the file * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * @throws phpmailerException * @see EncodeFile() * @access protected * @return string */ protected function EncodeFile($path, $encoding = 'base64') { try { if (!is_readable($path)) { throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE); } // if (!function_exists('get_magic_quotes')) { // function get_magic_quotes() { // return false; // } // } $magic_quotes = get_magic_quotes_runtime(); if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { set_magic_quotes_runtime(0); } else { ini_set('magic_quotes_runtime', 0); } } $file_buffer = file_get_contents($path); $file_buffer = $this->EncodeString($file_buffer, $encoding); if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { set_magic_quotes_runtime($magic_quotes); } else { ini_set('magic_quotes_runtime', $magic_quotes); } } return $file_buffer; } catch (Exception $e) { $this->SetError($e->getMessage()); return ''; } } /** * Encodes string to requested format. * Returns an empty string on failure. * @param string $str The text to encode * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * @access public * @return string */ public function EncodeString($str, $encoding = 'base64') { $encoded = ''; switch(strtolower($encoding)) { case 'base64': $encoded = chunk_split(base64_encode($str), 76, $this->LE); break; case '7bit': case '8bit': $encoded = $this->FixEOL($str); //Make sure it ends with a line break if (substr($encoded, -(strlen($this->LE))) != $this->LE) $encoded .= $this->LE; break; case 'binary': $encoded = $str; break; case 'quoted-printable': $encoded = $this->EncodeQP($str); break; default: $this->SetError($this->Lang('encoding') . $encoding); break; } return $encoded; } /** * Encode a header string to best (shortest) of Q, B, quoted or none. * @access public * @param string $str * @param string $position * @return string */ public function EncodeHeader($str, $position = 'text') { $x = 0; switch (strtolower($position)) { case 'phrase': if (!preg_match('/[\200-\377]/', $str)) { // Can't use addslashes as we don't know what value has magic_quotes_sybase $encoded = addcslashes($str, "\0..\37\177\\\""); if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { return ($encoded); } else { return ("\"$encoded\""); } } $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); break; case 'comment': $x = preg_match_all('/[()"]/', $str, $matches); // Fall-through case 'text': default: $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); break; } if ($x == 0) { return ($str); } $maxlen = 75 - 7 - strlen($this->CharSet); // Try to select the encoding which should produce the shortest output if (strlen($str)/3 < $x) { $encoding = 'B'; if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) { // Use a custom function which correctly encodes and wraps long // multibyte strings without breaking lines within a character $encoded = $this->Base64EncodeWrapMB($str, "\n"); } else { $encoded = base64_encode($str); $maxlen -= $maxlen % 4; $encoded = trim(chunk_split($encoded, $maxlen, "\n")); } } else { $encoding = 'Q'; $encoded = $this->EncodeQ($str, $position); $encoded = $this->WrapText($encoded, $maxlen, true); $encoded = str_replace('='.self::CRLF, "\n", trim($encoded)); } $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded); $encoded = trim(str_replace("\n", $this->LE, $encoded)); return $encoded; } /** * Checks if a string contains multibyte characters. * @access public * @param string $str multi-byte text to wrap encode * @return bool */ public function HasMultiBytes($str) { if (function_exists('mb_strlen')) { return (strlen($str) > mb_strlen($str, $this->CharSet)); } else { // Assume no multibytes (we can't handle without mbstring functions anyway) return false; } } /** * Correctly encodes and wraps long multibyte strings for mail headers * without breaking lines within a character. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php * @access public * @param string $str multi-byte text to wrap encode * @param string $lf string to use as linefeed/end-of-line * @return string */ public function Base64EncodeWrapMB($str, $lf=null) { $start = "=?".$this->CharSet."?B?"; $end = "?="; $encoded = ""; if ($lf === null) { $lf = $this->LE; } $mb_length = mb_strlen($str, $this->CharSet); // Each line must have length <= 75, including $start and $end $length = 75 - strlen($start) - strlen($end); // Average multi-byte ratio $ratio = $mb_length / strlen($str); // Base64 has a 4:3 ratio $offset = $avgLength = floor($length * $ratio * .75); for ($i = 0; $i < $mb_length; $i += $offset) { $lookBack = 0; do { $offset = $avgLength - $lookBack; $chunk = mb_substr($str, $i, $offset, $this->CharSet); $chunk = base64_encode($chunk); $lookBack++; } while (strlen($chunk) > $length); $encoded .= $chunk . $lf; } // Chomp the last linefeed $encoded = substr($encoded, 0, -strlen($lf)); return $encoded; } /** * Encode string to quoted-printable. * Only uses standard PHP, slow, but will always work * @access public * @param string $input * @param integer $line_max Number of chars allowed on a line before wrapping * @param bool $space_conv * @internal param string $string the text to encode * @return string */ public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) { $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); $lines = preg_split('/(?:\r\n|\r|\n)/', $input); $eol = "\r\n"; $escape = '='; $output = ''; while( list(, $line) = each($lines) ) { $linlen = strlen($line); $newline = ''; for($i = 0; $i < $linlen; $i++) { $c = substr( $line, $i, 1 ); $dec = ord( $c ); if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E $c = '=2E'; } if ( $dec == 32 ) { if ( $i == ( $linlen - 1 ) ) { // convert space at eol only $c = '=20'; } else if ( $space_conv ) { $c = '=20'; } } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required $h2 = (integer)floor($dec/16); $h1 = (integer)floor($dec%16); $c = $escape.$hex[$h2].$hex[$h1]; } if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay $newline = ''; // check if newline first character will be point or not if ( $dec == 46 ) { $c = '=2E'; } } $newline .= $c; } // end of for $output .= $newline.$eol; } // end of while return $output; } /** * Encode string to RFC2045 (6.7) quoted-printable format * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version * Also results in same content as you started with after decoding * @see EncodeQPphp() * @access public * @param string $string the text to encode * @param integer $line_max Number of chars allowed on a line before wrapping * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function * @return string * @author Marcus Bointon */ public function EncodeQP($string, $line_max = 76, $space_conv = false) { if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3) return quoted_printable_encode($string); } $filters = stream_get_filters(); if (!in_array('convert.*', $filters)) { //Got convert stream filter? return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation } $fp = fopen('php://temp/', 'r+'); $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE); $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params); fputs($fp, $string); rewind($fp); $out = stream_get_contents($fp); stream_filter_remove($s); $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange fclose($fp); return $out; } /** * Encode string to q encoding. * @link http://tools.ietf.org/html/rfc2047 * @param string $str the text to encode * @param string $position Where the text is going to be used, see the RFC for what that means * @access public * @return string */ public function EncodeQ($str, $position = 'text') { //There should not be any EOL in the string $pattern=""; $encoded = str_replace(array("\r", "\n"), '', $str); switch (strtolower($position)) { case 'phrase': $pattern = '^A-Za-z0-9!*+\/ -'; break; case 'comment': $pattern = '\(\)"'; //note that we dont break here! //for this reason we build the $pattern withoud including delimiters and [] case 'text': default: //Replace every high ascii, control =, ? and _ characters //We put \075 (=) as first value to make sure it's the first one in being converted, preventing double encode $pattern = '\075\000-\011\013\014\016-\037\077\137\177-\377' . $pattern; break; } if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { foreach (array_unique($matches[0]) as $char) { $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded); } } //Replace every spaces to _ (more readable than =20) return str_replace(' ', '_', $encoded); } /** * Adds a string or binary attachment (non-filesystem) to the list. * This method can be used to attach ascii or binary data, * such as a BLOB record from a database. * @param string $string String attachment data. * @param string $filename Name of the attachment. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @return void */ public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') { // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $filename, 2 => basename($filename), 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => 'attachment', 7 => 0 ); } /** * Adds an embedded attachment. This can include images, sounds, and * just about any other document. Make sure to set the $type to an * image type. For JPEG images use "image/jpeg" and for GIF images * use "image/gif". * @param string $path Path to the attachment. * @param string $cid Content ID of the attachment. Use this to identify * the Id for accessing the image in an HTML form. * @param string $name Overrides the attachment name. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @return bool */ public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { if ( !@is_file($path) ) { $this->SetError($this->Lang('file_access') . $path); return false; } $filename = basename($path); if ( $name == '' ) { $name = $filename; } // Append to $attachment array $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => 'inline', 7 => $cid ); return true; } /** * Adds an embedded stringified attachment. This can include images, sounds, and * just about any other document. Make sure to set the $type to an * image type. For JPEG images use "image/jpeg" and for GIF images * use "image/gif". * @param string $string The attachment. * @param string $cid Content ID of the attachment. Use this to identify * the Id for accessing the image in an HTML form. * @param string $name Overrides the attachment name. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @return bool */ public function AddStringEmbeddedImage($string, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $name, 2 => $name, 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => 'inline', 7 => $cid ); } /** * Returns true if an inline attachment is present. * @access public * @return bool */ public function InlineImageExists() { foreach($this->attachment as $attachment) { if ($attachment[6] == 'inline') { return true; } } return false; } /** * Returns true if an attachment (non-inline) is present. * @return bool */ public function AttachmentExists() { foreach($this->attachment as $attachment) { if ($attachment[6] == 'attachment') { return true; } } return false; } /** * Does this message have an alternative body set? * @return bool */ public function AlternativeExists() { return !empty($this->AltBody); } ///////////////////////////////////////////////// // CLASS METHODS, MESSAGE RESET ///////////////////////////////////////////////// /** * Clears all recipients assigned in the TO array. Returns void. * @return void */ public function ClearAddresses() { foreach($this->to as $to) { unset($this->all_recipients[strtolower($to[0])]); } $this->to = array(); } /** * Clears all recipients assigned in the CC array. Returns void. * @return void */ public function ClearCCs() { foreach($this->cc as $cc) { unset($this->all_recipients[strtolower($cc[0])]); } $this->cc = array(); } /** * Clears all recipients assigned in the BCC array. Returns void. * @return void */ public function ClearBCCs() { foreach($this->bcc as $bcc) { unset($this->all_recipients[strtolower($bcc[0])]); } $this->bcc = array(); } /** * Clears all recipients assigned in the ReplyTo array. Returns void. * @return void */ public function ClearReplyTos() { $this->ReplyTo = array(); } /** * Clears all recipients assigned in the TO, CC and BCC * array. Returns void. * @return void */ public function ClearAllRecipients() { $this->to = array(); $this->cc = array(); $this->bcc = array(); $this->all_recipients = array(); } /** * Clears all previously set filesystem, string, and binary * attachments. Returns void. * @return void */ public function ClearAttachments() { $this->attachment = array(); } /** * Clears all custom headers. Returns void. * @return void */ public function ClearCustomHeaders() { $this->CustomHeader = array(); } ///////////////////////////////////////////////// // CLASS METHODS, MISCELLANEOUS ///////////////////////////////////////////////// /** * Adds the error message to the error container. * @access protected * @param string $msg * @return void */ protected function SetError($msg) { $this->error_count++; if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { $lasterror = $this->smtp->getError(); if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { $msg .= '

' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "

\n"; } } $this->ErrorInfo = $msg; } /** * Returns the proper RFC 822 formatted date. * @access public * @return string * @static */ public static function RFCDate() { $tz = date('Z'); $tzs = ($tz < 0) ? '-' : '+'; $tz = abs($tz); $tz = (int)($tz/3600)*100 + ($tz%3600)/60; $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz); return $result; } /** * Returns the server hostname or 'localhost.localdomain' if unknown. * @access protected * @return string */ protected function ServerHostname() { if (!empty($this->Hostname)) { $result = $this->Hostname; } elseif (isset($_SERVER['SERVER_NAME'])) { $result = $_SERVER['SERVER_NAME']; } else { $result = 'localhost.localdomain'; } return $result; } /** * Returns a message in the appropriate language. * @access protected * @param string $key * @return string */ protected function Lang($key) { if(count($this->language) < 1) { $this->SetLanguage('en'); // set the default language } if(isset($this->language[$key])) { return $this->language[$key]; } else { return 'Language string failed to load: ' . $key; } } /** * Returns true if an error occurred. * @access public * @return bool */ public function IsError() { return ($this->error_count > 0); } /** * Changes every end of line from CRLF, CR or LF to $this->LE. * @access public * @param string $str String to FixEOL * @return string */ public function FixEOL($str) { // condense down to \n $nstr = str_replace(array("\r\n", "\r"), "\n", $str); // Now convert LE as needed if ($this->LE !== "\n") { $nstr = str_replace("\n", $this->LE, $nstr); } return $nstr; } /** * Adds a custom header. $name value can be overloaded to contain * both header name and value (name:value) * @access public * @param string $name custom header name * @param string $value header value * @return void */ public function AddCustomHeader($name, $value=null) { if ($value === null) { // Value passed in as name:value $this->CustomHeader[] = explode(':', $name, 2); } else { $this->CustomHeader[] = array($name, $value); } } /** * Evaluates the message and returns modifications for inline images and backgrounds * @access public * @param string $message Text to be HTML modified * @param string $basedir baseline directory for path * @return string $message */ public function MsgHTML($message, $basedir = '') { preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images); if(isset($images[2])) { foreach($images[2] as $i => $url) { // do not change urls for absolute images (thanks to corvuscorax) if (!preg_match('#^[A-z]+://#', $url)) { $filename = basename($url); $directory = dirname($url); if ($directory == '.') { $directory = ''; } $cid = 'cid:' . md5($url); $ext = pathinfo($filename, PATHINFO_EXTENSION); $mimeType = self::_mime_types($ext); if ( strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; } if ( strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; } if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($url), $filename, 'base64', $mimeType) ) { $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"".$cid."\"", $message); } } } } $this->IsHTML(true); $this->Body = $message; if (empty($this->AltBody)) { $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message))); if (!empty($textMsg)) { $this->AltBody = html_entity_decode($textMsg, ENT_QUOTES, $this->CharSet); } } if (empty($this->AltBody)) { $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n"; } return $message; } /** * Gets the MIME type of the embedded or inline image * @param string $ext File extension * @access public * @return string MIME type of ext * @static */ public static function _mime_types($ext = '') { $mimes = array( 'xl' => 'application/excel', 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'bin' => 'application/macbinary', 'doc' => 'application/msword', 'word' => 'application/msword', 'class' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'dms' => 'application/octet-stream', 'exe' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'psd' => 'application/octet-stream', 'sea' => 'application/octet-stream', 'so' => 'application/octet-stream', 'oda' => 'application/oda', 'pdf' => 'application/pdf', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'wbxml' => 'application/vnd.wap.wbxml', 'wmlc' => 'application/vnd.wap.wmlc', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'gtar' => 'application/x-gtar', 'php3' => 'application/x-httpd-php', 'php4' => 'application/x-httpd-php', 'php' => 'application/x-httpd-php', 'phtml' => 'application/x-httpd-php', 'phps' => 'application/x-httpd-php-source', 'js' => 'application/x-javascript', 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'tar' => 'application/x-tar', 'tgz' => 'application/x-tar', 'xht' => 'application/xhtml+xml', 'xhtml' => 'application/xhtml+xml', 'zip' => 'application/zip', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'mpga' => 'audio/mpeg', 'aif' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'wav' => 'audio/x-wav', 'bmp' => 'image/bmp', 'gif' => 'image/gif', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'jpg' => 'image/jpeg', 'png' => 'image/png', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'eml' => 'message/rfc822', 'css' => 'text/css', 'html' => 'text/html', 'htm' => 'text/html', 'shtml' => 'text/html', 'log' => 'text/plain', 'text' => 'text/plain', 'txt' => 'text/plain', 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', 'xml' => 'text/xml', 'xsl' => 'text/xml', 'mpeg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mov' => 'video/quicktime', 'qt' => 'video/quicktime', 'rv' => 'video/vnd.rn-realvideo', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie' ); return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)]; } /** * Set (or reset) Class Objects (variables) * * Usage Example: * $page->set('X-Priority', '3'); * * @access public * @param string $name Parameter Name * @param mixed $value Parameter Value * NOTE: will not work with arrays, there are no arrays to set/reset * @throws phpmailerException * @return bool * @todo Should this not be using __set() magic function? */ public function set($name, $value = '') { try { if (isset($this->$name) ) { $this->$name = $value; } else { throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL); } } catch (Exception $e) { $this->SetError($e->getMessage()); if ($e->getCode() == self::STOP_CRITICAL) { return false; } } return true; } /** * Strips newlines to prevent header injection. * @access public * @param string $str String * @return string */ public function SecureHeader($str) { return trim(str_replace(array("\r", "\n"), '', $str)); } /** * Set the private key file and password to sign the message. * * @access public * @param $cert_filename * @param string $key_filename Parameter File Name * @param string $key_pass Password for private key */ public function Sign($cert_filename, $key_filename, $key_pass) { $this->sign_cert_file = $cert_filename; $this->sign_key_file = $key_filename; $this->sign_key_pass = $key_pass; } /** * Set the private key file and password to sign the message. * * @access public * @param string $txt * @return string */ public function DKIM_QP($txt) { $line = ''; for ($i = 0; $i < strlen($txt); $i++) { $ord = ord($txt[$i]); if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) { $line .= $txt[$i]; } else { $line .= "=".sprintf("%02X", $ord); } } return $line; } /** * Generate DKIM signature * * @access public * @param string $s Header * @return string */ public function DKIM_Sign($s) { $privKeyStr = file_get_contents($this->DKIM_private); if ($this->DKIM_passphrase != '') { $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); } else { $privKey = $privKeyStr; } if (openssl_sign($s, $signature, $privKey)) { return base64_encode($signature); } return ''; } /** * Generate DKIM Canonicalization Header * * @access public * @param string $s Header * @return string */ public function DKIM_HeaderC($s) { $s = preg_replace("/\r\n\s+/", " ", $s); $lines = explode("\r\n", $s); foreach ($lines as $key => $line) { list($heading, $value) = explode(":", $line, 2); $heading = strtolower($heading); $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value } $s = implode("\r\n", $lines); return $s; } /** * Generate DKIM Canonicalization Body * * @access public * @param string $body Message Body * @return string */ public function DKIM_BodyC($body) { if ($body == '') return "\r\n"; // stabilize line endings $body = str_replace("\r\n", "\n", $body); $body = str_replace("\n", "\r\n", $body); // END stabilize line endings while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { $body = substr($body, 0, strlen($body) - 2); } return $body; } /** * Create the DKIM header, body, as new header * * @access public * @param string $headers_line Header lines * @param string $subject Subject * @param string $body Body * @return string */ public function DKIM_Add($headers_line, $subject, $body) { $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body $DKIMquery = 'dns/txt'; // Query method $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) $subject_header = "Subject: $subject"; $headers = explode($this->LE, $headers_line); $from_header = ""; $to_header = ""; foreach($headers as $header) { if (strpos($header, 'From:') === 0) { $from_header = $header; } elseif (strpos($header, 'To:') === 0) { $to_header = $header; } } $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable $body = $this->DKIM_BodyC($body); $DKIMlen = strlen($body) ; // Length of body $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";"; $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n". "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n". "\th=From:To:Subject;\r\n". "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n". "\tz=$from\r\n". "\t|$to\r\n". "\t|$subject;\r\n". "\tbh=" . $DKIMb64 . ";\r\n". "\tb="; $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs); $signed = $this->DKIM_Sign($toSign); return "X-PHPMAILER-DKIM: code.google.com/a/apache-extras.org/p/phpmailer/\r\n".$dkimhdrs.$signed."\r\n"; } /** * Perform callback * @param boolean $isSent * @param string $to * @param string $cc * @param string $bcc * @param string $subject * @param string $body * @param string $from */ protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from=null) { if (!empty($this->action_function) && is_callable($this->action_function)) { $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from); call_user_func_array($this->action_function, $params); } } } /** * Exception handler for PHPMailer * @package PHPMailer */ class phpmailerException extends Exception { /** * Prettify error message output * @return string */ public function errorMessage() { $errorMsg = '' . $this->getMessage() . "
\n"; return $errorMsg; } } ?> PKY[__ .htaccessnuW+A Order Allow,Deny Deny from all PKY[!z;; loader.phpnuW+A path map. * * @var array * @since 12.3 */ protected static $namespaces = array(); /** * Method to discover classes of a given type in a given path. * * @param string $classPrefix The class name prefix to use for discovery. * @param string $parentPath Full path to the parent folder for the classes to discover. * @param boolean $force True to overwrite the autoload path value for the class if it already exists. * @param boolean $recurse Recurse through all child directories as well as the parent path. * * @return void * * @since 11.1 */ public static function discover($classPrefix, $parentPath, $force = true, $recurse = false) { try { if ($recurse) { $iterator = new RecursiveIteratorIterator( new RecursiveDirectoryIterator($parentPath), RecursiveIteratorIterator::SELF_FIRST ); } else { $iterator = new DirectoryIterator($parentPath); } /* @type $file DirectoryIterator */ foreach ($iterator as $file) { $fileName = $file->getFilename(); // Only load for php files. if ($file->isFile() && $file->getExtension() == 'php') { // Get the class name and full path for each file. $class = strtolower($classPrefix . preg_replace('#\.php$#', '', $fileName)); // Register the class with the autoloader if not already registered or the force flag is set. if (empty(self::$classes[$class]) || $force) { self::register($class, $file->getPath() . '/' . $fileName); } } } } catch (UnexpectedValueException $e) { // Exception will be thrown if the path is not a directory. Ignore it. } } /** * Method to get the list of registered classes and their respective file paths for the autoloader. * * @return array The array of class => path values for the autoloader. * * @since 11.1 */ public static function getClassList() { return self::$classes; } /** * Method to get the list of registered namespaces. * * @return array The array of namespace => path values for the autoloader. * * @since 12.3 */ public static function getNamespaces() { return self::$namespaces; } /** * Loads a class from specified directories. * * @param string $key The class name to look for (dot notation). * @param string $base Search this directory for the class. * * @return boolean True on success. * * @since 11.1 */ public static function import($key, $base = null) { // Only import the library if not already attempted. if (!isset(self::$imported[$key])) { // Setup some variables. $success = false; $parts = explode('.', $key); $class = array_pop($parts); $base = (!empty($base)) ? $base : __DIR__; $path = str_replace('.', DIRECTORY_SEPARATOR, $key); // Handle special case for helper classes. if ($class == 'helper') { $class = ucfirst(array_pop($parts)) . ucfirst($class); } // Standard class. else { $class = ucfirst($class); } // If we are importing a library from the Joomla namespace set the class to autoload. if (strpos($path, 'joomla') === 0) { // Since we are in the Joomla namespace prepend the classname with J. $class = 'J' . $class; // Only register the class for autoloading if the file exists. if (is_file($base . '/' . $path . '.php')) { self::$classes[strtolower($class)] = $base . '/' . $path . '.php'; $success = true; } } /* * If we are not importing a library from the Joomla namespace directly include the * file since we cannot assert the file/folder naming conventions. */ else { // If the file exists attempt to include it. if (is_file($base . '/' . $path . '.php')) { $success = (bool) include_once $base . '/' . $path . '.php'; } } // Add the import key to the memory cache container. self::$imported[$key] = $success; } return self::$imported[$key]; } /** * Load the file for a class. * * @param string $class The class to be loaded. * * @return boolean True on success * * @since 11.1 */ public static function load($class) { // Sanitize class name. $class = strtolower($class); // If the class already exists do nothing. if (class_exists($class, false)) { return true; } // If the class is registered include the file. if (isset(self::$classes[$class])) { include_once self::$classes[$class]; return true; } return false; } /** * Directly register a class to the autoload list. * * @param string $class The class name to register. * @param string $path Full path to the file that holds the class to register. * @param boolean $force True to overwrite the autoload path value for the class if it already exists. * * @return void * * @since 11.1 */ public static function register($class, $path, $force = true) { // Sanitize class name. $class = strtolower($class); // Only attempt to register the class if the name and file exist. if (!empty($class) && is_file($path)) { // Register the class with the autoloader if not already registered or the force flag is set. if (empty(self::$classes[$class]) || $force) { self::$classes[$class] = $path; } } } /** * Register a class prefix with lookup path. This will allow developers to register library * packages with different class prefixes to the system autoloader. More than one lookup path * may be registered for the same class prefix, but if this method is called with the reset flag * set to true then any registered lookups for the given prefix will be overwritten with the current * lookup path. When loaded, prefix paths are searched in a "last in, first out" order. * * @param string $prefix The class prefix to register. * @param string $path Absolute file path to the library root where classes with the given prefix can be found. * @param boolean $reset True to reset the prefix with only the given lookup path. * @param boolean $prepend If true, push the path to the beginning of the prefix lookup paths array. * * @return void * * @throws RuntimeException * * @since 12.1 */ public static function registerPrefix($prefix, $path, $reset = false, $prepend = false) { // Verify the library path exists. if (!file_exists($path)) { throw new RuntimeException('Library path ' . $path . ' cannot be found.', 500); } // If the prefix is not yet registered or we have an explicit reset flag then set set the path. if (!isset(self::$prefixes[$prefix]) || $reset) { self::$prefixes[$prefix] = array($path); } // Otherwise we want to simply add the path to the prefix. else { if ($prepend) { array_unshift(self::$prefixes[$prefix], $path); } else { self::$prefixes[$prefix][] = $path; } } } /** * Offers the ability for "just in time" usage of `class_alias()`. * You cannot overwrite an existing alias. * * @param string $alias The alias name to register. * @param string $original The original class to alias. * * @return boolean True if registration was successful. False if the alias already exists. * * @since 3.2 */ public static function registerAlias($alias, $original) { if (!isset(self::$classAliases[$alias])) { self::$classAliases[$alias] = $original; return true; } return false; } /** * Register a namespace to the autoloader. When loaded, namespace paths are searched in a "last in, first out" order. * * @param string $namespace A case sensitive Namespace to register. * @param string $path A case sensitive absolute file path to the library root where classes of the given namespace can be found. * @param boolean $reset True to reset the namespace with only the given lookup path. * @param boolean $prepend If true, push the path to the beginning of the namespace lookup paths array. * * @return void * * @throws RuntimeException * * @since 12.3 */ public static function registerNamespace($namespace, $path, $reset = false, $prepend = false) { // Verify the library path exists. if (!file_exists($path)) { throw new RuntimeException('Library path ' . $path . ' cannot be found.', 500); } // If the namespace is not yet registered or we have an explicit reset flag then set the path. if (!isset(self::$namespaces[$namespace]) || $reset) { self::$namespaces[$namespace] = array($path); } // Otherwise we want to simply add the path to the namespace. else { if ($prepend) { array_unshift(self::$namespaces[$namespace], $path); } else { self::$namespaces[$namespace][] = $path; } } } /** * Method to setup the autoloaders for the Joomla Platform. * Since the SPL autoloaders are called in a queue we will add our explicit * class-registration based loader first, then fall back on the autoloader based on conventions. * This will allow people to register a class in a specific location and override platform libraries * as was previously possible. * * @param boolean $enablePsr True to enable autoloading based on PSR-0. * @param boolean $enablePrefixes True to enable prefix based class loading (needed to auto load the Joomla core). * @param boolean $enableClasses True to enable class map based class loading (needed to auto load the Joomla core). * * @return void * * @since 12.3 */ public static function setup($enablePsr = true, $enablePrefixes = true, $enableClasses = true) { if ($enableClasses) { // Register the class map based autoloader. spl_autoload_register(array('JLoader', 'load')); } if ($enablePrefixes) { // Register the J prefix and base path for Joomla platform libraries. self::registerPrefix('J', JPATH_PLATFORM . '/joomla'); // Register the prefix autoloader. spl_autoload_register(array('JLoader', '_autoload')); } if ($enablePsr) { // Register the PSR-0 based autoloader. spl_autoload_register(array('JLoader', 'loadByPsr0')); spl_autoload_register(array('JLoader', 'loadByAlias')); } } /** * Method to autoload classes that are namespaced to the PSR-0 standard. * * @param string $class The fully qualified class name to autoload. * * @return boolean True on success, false otherwise. * * @since 13.1 */ public static function loadByPsr0($class) { // Remove the root backslash if present. if ($class[0] == '\\') { $class = substr($class, 1); } // Find the location of the last NS separator. $pos = strrpos($class, '\\'); // If one is found, we're dealing with a NS'd class. if ($pos !== false) { $classPath = str_replace('\\', DIRECTORY_SEPARATOR, substr($class, 0, $pos)) . DIRECTORY_SEPARATOR; $className = substr($class, $pos + 1); } // If not, no need to parse path. else { $classPath = null; $className = $class; } $classPath .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php'; // Loop through registered namespaces until we find a match. foreach (self::$namespaces as $ns => $paths) { if (strpos($class, $ns) === 0) { // Loop through paths registered to this namespace until we find a match. foreach ($paths as $path) { $classFilePath = $path . DIRECTORY_SEPARATOR . $classPath; // We check for class_exists to handle case-sensitive file systems if (file_exists($classFilePath) && !class_exists($class, false)) { return (bool) include_once $classFilePath; } } } } return false; } /** * Method to autoload classes that have been aliased using the registerAlias method. * * @param string $class The fully qualified class name to autoload. * * @return boolean True on success, false otherwise. * * @since 3.2 */ public static function loadByAlias($class) { // Remove the root backslash if present. if ($class[0] == '\\') { $class = substr($class, 1); } if (isset(self::$classAliases[$class])) { class_alias(self::$classAliases[$class], $class); } } /** * Autoload a class based on name. * * @param string $class The class to be loaded. * * @return boolean True if the class was loaded, false otherwise. * * @since 11.3 */ private static function _autoload($class) { foreach (self::$prefixes as $prefix => $lookup) { $chr = strlen($prefix) < strlen($class) ? $class[strlen($prefix)] : 0; if (strpos($class, $prefix) === 0 && ($chr === strtoupper($chr))) { return self::_load(substr($class, strlen($prefix)), $lookup); } } return false; } /** * Load a class based on name and lookup array. * * @param string $class The class to be loaded (wihtout prefix). * @param array $lookup The array of base paths to use for finding the class file. * * @return boolean True if the class was loaded, false otherwise. * * @since 12.1 */ private static function _load($class, $lookup) { // Split the class name into parts separated by camelCase. $parts = preg_split('/(?<=[a-z0-9])(?=[A-Z])/x', $class); // If there is only one part we want to duplicate that part for generating the path. $parts = (count($parts) === 1) ? array($parts[0], $parts[0]) : $parts; foreach ($lookup as $base) { // Generate the path based on the class name parts. $path = $base . '/' . implode('/', array_map('strtolower', $parts)) . '.php'; // Load the file if it exists. if (file_exists($path)) { return include $path; } } return false; } } /** * Global application exit. * * This function provides a single exit point for the platform. * * @param mixed $message Exit code or string. Defaults to zero. * * @return void * * @codeCoverageIgnore * @since 11.1 */ function jexit($message = 0) { exit($message); } /** * Intelligent file importer. * * @param string $path A dot syntax path. * * @return boolean True on success. * * @since 11.1 */ function jimport($path) { return JLoader::import($path); } PKY[El8I## import.phpnuW+AgetColumnAlias('asset_id'); if (in_array($asset_id_field, $table->getKnownFields())) { if (!empty($table->$asset_id_field)) { $currentAssetId = $table->$asset_id_field; } // The asset id field is managed privately by this class. if ($table->isAssetsTracked()) { unset($table->$asset_id_field); } } // Create the object used for inserting/udpating data to the database $fields = $table->getTableFields(); // Let's remove the asset_id field, since we unset the property above and we would get a PHP notice if (isset($fields[$asset_id_field])) { unset($fields[$asset_id_field]); } // Asset Tracking if (in_array($asset_id_field, $table->getKnownFields()) && $table->isAssetsTracked()) { $parentId = $table->getAssetParentId(); try{ $name = $table->getAssetName(); } catch(Exception $e) { $table->setError($e->getMessage()); return false; } $title = $table->getAssetTitle(); $asset = JTable::getInstance('Asset'); $asset->loadByName($name); // Re-inject the asset id. $this->$asset_id_field = $asset->id; // Check for an error. $error = $asset->getError(); // Since we are using JTable, there is no way to mock it and test for failures :( // @codeCoverageIgnoreStart if ($error) { $table->setError($error); return false; } // @codeCoverageIgnoreEnd // Specify how a new or moved node asset is inserted into the tree. // Since we're unsetting the table field before, this statement is always true... if (empty($table->$asset_id_field) || $asset->parent_id != $parentId) { $asset->setLocation($parentId, 'last-child'); } // Prepare the asset to be stored. $asset->parent_id = $parentId; $asset->name = $name; $asset->title = $title; if ($table->getRules() instanceof JAccessRules) { $asset->rules = (string) $table->getRules(); } // Since we are using JTable, there is no way to mock it and test for failures :( // @codeCoverageIgnoreStart if (!$asset->check() || !$asset->store()) { $table->setError($asset->getError()); return false; } // @codeCoverageIgnoreEnd // Create an asset_id or heal one that is corrupted. if (empty($table->$asset_id_field) || (($currentAssetId != $table->$asset_id_field) && !empty($table->$asset_id_field))) { // Update the asset_id field in this table. $table->$asset_id_field = (int) $asset->id; $k = $table->getKeyName(); $db = $table->getDbo(); $query = $db->getQuery(true) ->update($db->qn($table->getTableName())) ->set($db->qn($asset_id_field).' = ' . (int) $table->$asset_id_field) ->where($db->qn($k) . ' = ' . (int) $table->$k); $db->setQuery($query)->execute(); } $result = true; } return $result; } /** * The event which runs after binding data to the table * * @param FOFTable &$table The table which calls this event * @param object|array &$src The data to bind * * @return boolean True on success */ public function onAfterBind(&$table, &$src) { // Set rules for assets enabled tables if ($table->isAssetsTracked()) { // Bind the rules. if (isset($src['rules']) && is_array($src['rules'])) { // We have to manually remove any empty value, since they will be converted to int, // and "Inherited" values will become "Denied". Joomla is doing this manually, too. // @todo Should we move this logic inside the setRules method? $rules = array(); foreach ($src['rules'] as $action => $ids) { // Build the rules array. $rules[$action] = array(); foreach ($ids as $id => $p) { if ($p !== '') { $rules[$action][$id] = ($p == '1' || $p == 'true') ? true : false; } } } $table->setRules($rules); } } return true; } /** * The event which runs before deleting a record * * @param FOFTable &$table The table which calls this event * @param integer $oid The PK value of the record to delete * * @return boolean True to allow the deletion */ public function onBeforeDelete(&$table, $oid) { // If tracking assets, remove the asset first. if ($table->isAssetsTracked()) { $k = $table->getKeyName(); // If the table is not loaded, let's try to load it with the id if(!$table->$k) { $table->load($oid); } // If I have an invalid assetName I have to stop try { $name = $table->getAssetName(); } catch(Exception $e) { $table->setError($e->getMessage()); return false; } // Do NOT touch JTable here -- we are loading the core asset table which is a JTable, not a FOFTable $asset = JTable::getInstance('Asset'); if ($asset->loadByName($name)) { // Since we are using JTable, there is no way to mock it and test for failures :( // @codeCoverageIgnoreStart if (!$asset->delete()) { $table->setError($asset->getError()); return false; } // @codeCoverageIgnoreEnd } else { // I'll simply return true even if I couldn't load the asset. In this way I can still // delete a broken record return true; } } return true; } } PKY[賚fof/table/behavior/tags.phpnuW+AhasTags()) { if ((!empty($src['tags']) && $src['tags'][0] != '')) { $table->newTags = $src['tags']; } // Check if the content type exists, and create it if it does not $this->checkContentType($table, $options); $tagsTable = clone($table); $tagsHelper = new JHelperTags(); $tagsHelper->typeAlias = $table->getAssetKey(); // TODO: This little guy here fails because JHelperTags // need a JTable object to work, while our is FOFTable // Need probably to write our own FOFHelperTags // Thank you com_tags if (!$tagsHelper->postStoreProcess($tagsTable)) { $table->setError('Error storing tags'); return false; } } return true; } /** * The event which runs before storing (saving) data to the database * * @param FOFTable &$table The table which calls this event * @param boolean $updateNulls Should nulls be saved as nulls (true) or just skipped over (false)? * * @return boolean True to allow saving */ public function onBeforeStore(&$table, $updateNulls) { if ($table->hasTags()) { $tagsHelper = new JHelperTags(); $tagsHelper->typeAlias = $table->getAssetKey(); // TODO: JHelperTags sucks in Joomla! 3.1, it requires that tags are // stored in the metadata property. Not our case, therefore we need // to add it in a fake object. We sent a PR to Joomla! CMS to fix // that. Once it's accepted, we'll have to remove the attrocity // here... $tagsTable = clone($table); $tagsHelper->preStoreProcess($tagsTable); } } /** * The event which runs after deleting a record * * @param FOFTable &$table The table which calls this event * @param integer $oid The PK value of the record which was deleted * * @return boolean True to allow the deletion without errors */ public function onAfterDelete(&$table, $oid) { // If this resource has tags, delete the tags first if ($table->hasTags()) { $tagsHelper = new JHelperTags(); $tagsHelper->typeAlias = $table->getAssetKey(); if (!$tagsHelper->deleteTagData($table, $oid)) { $table->setError('Error deleting Tags'); return false; } } } /** * Check if a UCM content type exists for this resource, and * create it if it does not */ protected function checkContentType(&$table, $options) { $contentType = new JTableContenttype($table->getDbo()); $alias = $table->getContentType(); // Fetch the extension name $component = $options['component']; $component = JComponentHelper::getComponent($component); // Fetch the name using the menu item $query = $table->getDbo()->getQuery(true); $query->select('title')->from('#__menu')->where('component_id = ' . (int) $component->id); $table->getDbo()->setQuery($query); $component_name = JText::_($table->getDbo()->loadResult()); $name = $component_name . ' ' . ucfirst($options['view']); // Create a new content type for our resource if (!$contentType->load(array('type_alias' => $alias))) { $contentType->type_title = $name; $contentType->type_alias = $alias; $contentType->table = json_encode( array( 'special' => array( 'dbtable' => $table->getTableName(), 'key' => $table->getKeyName(), 'type' => $name, 'prefix' => $options['table_prefix'], 'config' => 'array()' ), 'common' => array( 'dbtable' => '#__ucm_content', 'key' => 'ucm_id', 'type' => 'CoreContent', 'prefix' => 'JTable', 'config' => 'array()' ) ) ); $contentType->field_mappings = json_encode( array( 'common' => array( 0 => array( "core_content_item_id" => $table->getKeyName(), "core_title" => $this->getUcmCoreAlias($table, 'title'), "core_state" => $this->getUcmCoreAlias($table, 'enabled'), "core_alias" => $this->getUcmCoreAlias($table, 'alias'), "core_created_time" => $this->getUcmCoreAlias($table, 'created_on'), "core_modified_time" => $this->getUcmCoreAlias($table, 'created_by'), "core_body" => $this->getUcmCoreAlias($table, 'body'), "core_hits" => $this->getUcmCoreAlias($table, 'hits'), "core_publish_up" => $this->getUcmCoreAlias($table, 'publish_up'), "core_publish_down" => $this->getUcmCoreAlias($table, 'publish_down'), "core_access" => $this->getUcmCoreAlias($table, 'access'), "core_params" => $this->getUcmCoreAlias($table, 'params'), "core_featured" => $this->getUcmCoreAlias($table, 'featured'), "core_metadata" => $this->getUcmCoreAlias($table, 'metadata'), "core_language" => $this->getUcmCoreAlias($table, 'language'), "core_images" => $this->getUcmCoreAlias($table, 'images'), "core_urls" => $this->getUcmCoreAlias($table, 'urls'), "core_version" => $this->getUcmCoreAlias($table, 'version'), "core_ordering" => $this->getUcmCoreAlias($table, 'ordering'), "core_metakey" => $this->getUcmCoreAlias($table, 'metakey'), "core_metadesc" => $this->getUcmCoreAlias($table, 'metadesc'), "core_catid" => $this->getUcmCoreAlias($table, 'cat_id'), "core_xreference" => $this->getUcmCoreAlias($table, 'xreference'), "asset_id" => $this->getUcmCoreAlias($table, 'asset_id') ) ), 'special' => array( 0 => array( ) ) ) ); $contentType->router = ''; $contentType->store(); } } /** * Utility methods that fetches the column name for the field. * If it does not exists, returns a "null" string * * @return string The column name */ protected function getUcmCoreAlias($table, $alias) { $alias = $table->getColumnAlias($alias); if (in_array($alias, $table->getKnownFields())) { return $alias; } return "null"; } }PKY[W+@fof/table/behavior.phpnuW+APKY[׀n!fof/table/dispatcher/behavior.phpnuW+A array(), 'parent' => array(), 'children' => array(), 'multiple' => array(), ); /** * Holds the default relations' keys * * @var array */ private $defaultRelation = array( 'child' => null, 'parent' => null, 'children' => null, 'multiple' => null, ); /** * The table these relations are attached to * * @var FOFTable */ private $table = null; /** * The name of the component used by our attached table * * @var string */ private $componentName = 'joomla'; /** * The type (table name without prefix and component name) of our attached table * * @var string */ private $tableType = ''; /** * Create a relations object based on the provided FOFTable instance * * @param FOFTable $table The table instance used to initialise the relations */ public function __construct(FOFTable $table) { // Store the table $this->table = $table; // Get the table's type from its name $tableName = $table->getTableName(); $tableName = str_replace('#__', '', $tableName); $type = explode("_", $tableName); if (count($type) == 1) { $this->tableType = array_pop($type); } else { $this->componentName = array_shift($type); $this->tableType = array_pop($type); } $this->tableType = FOFInflector::singularize($this->tableType); $tableKey = $table->getKeyName(); unset($type); // Scan all table keys and look for foo_bar_id fields. These fields are used to populate parent relations. foreach ($table->getKnownFields() as $field) { // Skip the table key name if ($field == $tableKey) { continue; } if (substr($field, -3) != '_id') { continue; } $parts = explode('_', $field); // If the component type of the field is not set assume 'joomla' if (count($parts) == 2) { array_unshift($parts, 'joomla'); } // Sanity check if (count($parts) != 3) { continue; } // Make sure we skip any references back to ourselves (should be redundant, due to key field check above) if ($parts[1] == $this->tableType) { continue; } // Default item name: the name of the table, singular $itemName = FOFInflector::singularize($parts[1]); // Prefix the item name with the component name if we refer to a different component if ($parts[0] != $this->componentName) { $itemName = $parts[0] . '_' . $itemName; } // Figure out the table class $tableClass = ucfirst($parts[0]) . 'Table' . ucfirst($parts[1]); $default = empty($this->relations['parent']); $this->addParentRelation($itemName, $tableClass, $field, $field, $default); } // Get the relations from the configuration provider $key = $table->getConfigProviderKey() . '.relations'; $configRelations = $table->getConfigProvider()->get($key, array()); if (!empty($configRelations)) { foreach ($configRelations as $relation) { if (empty($relation['type'])) { continue; } if (isset($relation['pivotTable'])) { $this->addMultipleRelation($relation['itemName'], $relation['tableClass'], $relation['localKey'], $relation['ourPivotKey'], $relation['theirPivotKey'], $relation['remoteKey'], $relation['pivotTable'], $relation['default']); } else { $method = 'add' . ucfirst($relation['type']). 'Relation'; if (!method_exists($this, $method)) { continue; } $this->$method($relation['itemName'], $relation['tableClass'], $relation['localKey'], $relation['remoteKey'], $relation['default']); } } } } /** * Add a 1:1 forward (child) relation. This adds relations for the getChild() method. * * In other words: does a table HAVE ONE child * * Parent and child relations works the same way. We have them separated as it makes more sense for us humans to * read code like $item->getParent() and $item->getChild() than $item->getRelatedObject('someRandomKeyName') * * @param string $itemName is how it will be known locally to the getRelatedItem method (singular) * @param string $tableClass if skipped it is defined automatically as ComponentnameTableItemname * @param string $localKey is the column containing our side of the FK relation, default: our primary key * @param string $remoteKey is the remote table's FK column, default: componentname_itemname_id * @param boolean $default add as the default child relation? * * @return void */ public function addChildRelation($itemName, $tableClass = null, $localKey = null, $remoteKey = null, $default = true) { $itemName = $this->normaliseItemName($itemName, false); if (empty($localKey)) { $localKey = $this->table->getKeyName(); } $this->addBespokeSimpleRelation('child', $itemName, $tableClass, $localKey, $remoteKey, $default); } /** * Defining an inverse 1:1 (parent) relation. You must specify at least the $tableClass or the $localKey. * This adds relations for the getParent() method. * * In other words: does a table BELONG TO ONE parent * * Parent and child relations works the same way. We have them separated as it makes more sense for us humans to * read code like $item->getParent() and $item->getChild() than $item->getRelatedObject('someRandomKeyName') * * @param string $itemName is how it will be known locally to the getRelatedItem method (singular) * @param string $tableClass if skipped it is defined automatically as ComponentnameTableItemname * @param string $localKey is the column containing our side of the FK relation, default: componentname_itemname_id * @param string $remoteKey is the remote table's FK column, default: componentname_itemname_id * @param boolean $default Is this the default parent relationship? * * @return void */ public function addParentRelation($itemName, $tableClass = null, $localKey = null, $remoteKey = null, $default = true) { $itemName = $this->normaliseItemName($itemName, false); $this->addBespokeSimpleRelation('parent', $itemName, $tableClass, $localKey, $remoteKey, $default); } /** * Defining a forward 1:∞ (children) relation. This adds relations to the getChildren() method. * * In other words: does a table HAVE MANY children? * * The children relation works very much the same as the parent and child relation. The difference is that the * parent and child relations return a single table object, whereas the children relation returns an iterator to * many objects. * * @param string $itemName is how it will be known locally to the getRelatedItems method (plural) * @param string $tableClass if skipped it is defined automatically as ComponentnameTableItemname * @param string $localKey is the column containing our side of the FK relation, default: our primary key * @param string $remoteKey is the remote table's FK column, default: componentname_itemname_id * @param boolean $default is this the default children relationship? * * @return void */ public function addChildrenRelation($itemName, $tableClass = null, $localKey = null, $remoteKey = null, $default = true) { $itemName = $this->normaliseItemName($itemName, true); if (empty($localKey)) { $localKey = $this->table->getKeyName(); } $this->addBespokeSimpleRelation('children', $itemName, $tableClass, $localKey, $remoteKey, $default); } /** * Defining a ∞:∞ (multiple) relation. This adds relations to the getMultiple() method. * * In other words: is a table RELATED TO MANY other records? * * @param string $itemName is how it will be known locally to the getRelatedItems method (plural) * @param string $tableClass if skipped it is defined automatically as ComponentnameTableItemname * @param string $localKey is the column containing our side of the FK relation, default: our primary key field name * @param string $ourPivotKey is the column containing our side of the FK relation in the pivot table, default: $localKey * @param string $theirPivotKey is the column containing the other table's side of the FK relation in the pivot table, default $remoteKey * @param string $remoteKey is the remote table's FK column, default: componentname_itemname_id * @param string $glueTable is the name of the glue (pivot) table, default: #__componentname_thisclassname_itemname with plural items (e.g. #__foobar_users_roles) * @param boolean $default is this the default multiple relation? */ public function addMultipleRelation($itemName, $tableClass = null, $localKey = null, $ourPivotKey = null, $theirPivotKey = null, $remoteKey = null, $glueTable = null, $default = true) { $itemName = $this->normaliseItemName($itemName, true); if (empty($localKey)) { $localKey = $this->table->getKeyName(); } $this->addBespokePivotRelation('multiple', $itemName, $tableClass, $localKey, $remoteKey, $ourPivotKey, $theirPivotKey, $glueTable, $default); } /** * Removes a previously defined relation by name. You can optionally specify the relation type. * * @param string $itemName The name of the relation to remove * @param string $type [optional] The relation type (child, parent, children, ...) * * @return void */ public function removeRelation($itemName, $type = null) { $types = array_keys($this->relations); if (in_array($type, $types)) { $types = array($type); } foreach ($types as $type) { foreach ($this->relations[$type] as $relations) { if (array_key_exists($itemName, $relations)) { unset ($this->relations[$type][$itemName]); return; } } } } /** * Removes all existing relations * * @param string $type The type or relations to remove, omit to remove all relation types * * @return void */ public function clearRelations($type = null) { $types = array_keys($this->relations); if (in_array($type, $types)) { $types = array($type); } foreach ($types as $type) { $this->relations[$type] = array(); } } /** * Does the named relation exist? You can optionally specify the type. * * @param string $itemName The name of the relation to check * @param string $type [optional] The relation type (child, parent, children, ...) * * @return boolean */ public function hasRelation($itemName, $type = null) { $types = array_keys($this->relations); if (in_array($type, $types)) { $types = array($type); } foreach ($types as $type) { foreach ($this->relations[$type] as $relations) { if (array_key_exists($itemName, $relations)) { return true; } } } return false; } /** * Get the definition of a relation * * @param string $itemName The name of the relation to check * @param string $type [optional] The relation type (child, parent, children, ...) * * @return array * * @throws RuntimeException When the relation is not found */ public function getRelation($itemName, $type) { $types = array_keys($this->relations); if (in_array($type, $types)) { $types = array($type); } foreach ($types as $type) { foreach ($this->relations[$type] as $relations) { if (array_key_exists($itemName, $relations)) { $temp = $relations[$itemName]; $temp['type'] = $type; return $temp; } } } throw new RuntimeException("Relation $itemName not found in table {$this->tableType}", 500); } /** * Gets the item referenced by a named relation. You can optionally specify the type. Only single item relation * types will be searched. * * @param string $itemName The name of the relation to use * @param string $type [optional] The relation type (child, parent) * * @return FOFTable * * @throws RuntimeException If the named relation doesn't exist or isn't supposed to return single items */ public function getRelatedItem($itemName, $type = null) { if (empty($type)) { $relation = $this->getRelation($itemName, $type); $type = $relation['type']; } switch ($type) { case 'parent': return $this->getParent($itemName); break; case 'child': return $this->getChild($itemName); break; default: throw new RuntimeException("Invalid relation type $type for returning a single related item", 500); break; } } /** * Gets the iterator for the items referenced by a named relation. You can optionally specify the type. Only * multiple item relation types will be searched. * * @param string $itemName The name of the relation to use * @param string $type [optional] The relation type (children, multiple) * * @return FOFDatabaseIterator * * @throws RuntimeException If the named relation doesn't exist or isn't supposed to return single items */ public function getRelatedItems($itemName, $type = null) { if (empty($type)) { $relation = $this->getRelation($itemName, $type); $type = $relation['type']; } switch ($type) { case 'children': return $this->getChildren($itemName); break; case 'multiple': return $this->getMultiple($itemName); break; case 'siblings': return $this->getSiblings($itemName); break; default: throw new RuntimeException("Invalid relation type $type for returning a collection of related items", 500); break; } } /** * Gets a parent item * * @param string $itemName [optional] The name of the relation to use, skip to use the default parent relation * * @return FOFTable * * @throws RuntimeException When the relation is not found */ public function getParent($itemName = null) { if (empty($itemName)) { $itemName = $this->defaultRelation['parent']; } if (empty($itemName)) { throw new RuntimeException(sprintf('Default parent relation for %s not found', $this->table->getTableName()), 500); } if (!isset($this->relations['parent'][$itemName])) { throw new RuntimeException(sprintf('Parent relation %s for %s not found', $itemName, $this->table->getTableName()), 500); } return $this->getTableFromRelation($this->relations['parent'][$itemName]); } /** * Gets a child item * * @param string $itemName [optional] The name of the relation to use, skip to use the default child relation * * @return FOFTable * * @throws RuntimeException When the relation is not found */ public function getChild($itemName = null) { if (empty($itemName)) { $itemName = $this->defaultRelation['child']; } if (empty($itemName)) { throw new RuntimeException(sprintf('Default child relation for %s not found', $this->table->getTableName()), 500); } if (!isset($this->relations['child'][$itemName])) { throw new RuntimeException(sprintf('Child relation %s for %s not found', $itemName, $this->table->getTableName()), 500); } return $this->getTableFromRelation($this->relations['child'][$itemName]); } /** * Gets an iterator for the children items * * @param string $itemName [optional] The name of the relation to use, skip to use the default children relation * * @return FOFDatabaseIterator * * @throws RuntimeException When the relation is not found */ public function getChildren($itemName = null) { if (empty($itemName)) { $itemName = $this->defaultRelation['children']; } if (empty($itemName)) { throw new RuntimeException(sprintf('Default children relation for %s not found', $this->table->getTableName()), 500); } if (!isset($this->relations['children'][$itemName])) { throw new RuntimeException(sprintf('Children relation %s for %s not found', $itemName, $this->table->getTableName()), 500); } return $this->getIteratorFromRelation($this->relations['children'][$itemName]); } /** * Gets an iterator for the sibling items. This relation is inferred from the parent relation. It returns all * elements on the same table which have the same parent. * * @param string $itemName [optional] The name of the relation to use, skip to use the default children relation * * @return FOFDatabaseIterator * * @throws RuntimeException When the relation is not found */ public function getSiblings($itemName = null) { if (empty($itemName)) { $itemName = $this->defaultRelation['parent']; } if (empty($itemName)) { throw new RuntimeException(sprintf('Default siblings relation for %s not found', $this->table->getTableName()), 500); } if (!isset($this->relations['parent'][$itemName])) { throw new RuntimeException(sprintf('Sibling relation %s for %s not found', $itemName, $this->table->getTableName()), 500); } // Get my table class $tableName = $this->table->getTableName(); $tableName = str_replace('#__', '', $tableName); $tableNameParts = explode('_', $tableName, 2); $tableClass = ucfirst($tableNameParts[0]) . 'Table' . ucfirst(FOFInflector::singularize($tableNameParts[1])); $parentRelation = $this->relations['parent'][$itemName]; $relation = array( 'tableClass' => $tableClass, 'localKey' => $parentRelation['localKey'], 'remoteKey' => $parentRelation['localKey'], ); return $this->getIteratorFromRelation($relation); } /** * Gets an iterator for the multiple items * * @param string $itemName [optional] The name of the relation to use, skip to use the default multiple relation * * @return FOFDatabaseIterator * * @throws RuntimeException When the relation is not found */ public function getMultiple($itemName = null) { if (empty($itemName)) { $itemName = $this->defaultRelation['multiple']; } if (empty($itemName)) { throw new RuntimeException(sprintf('Default multiple relation for %s not found', $this->table->getTableName()), 500); } if (!isset($this->relations['multiple'][$itemName])) { throw new RuntimeException(sprintf('Multiple relation %s for %s not found', $itemName, $this->table->getTableName()), 500); } return $this->getIteratorFromRelation($this->relations['multiple'][$itemName]); } /** * Returns a FOFTable object based on a given relation * * @param array $relation Relation definition * * @return FOFTable * * @throws RuntimeException */ private function getTableFromRelation($relation) { // Get a table object from the table class name $tableClass = $relation['tableClass']; $tableClassParts = FOFInflector::explode($tableClass); $table = FOFTable::getInstance($tableClassParts[2], ucfirst($tableClassParts[0]) . ucfirst($tableClassParts[1])); // Get the table name $tableName = $table->getTableName(); // Get the remote and local key names $remoteKey = $relation['remoteKey']; $localKey = $relation['localKey']; // Get the local key's value $value = $this->table->$localKey; // This is required to prevent one relation from killing the db cursor used in a different relation... $oldDb = $this->table->getDbo(); $oldDb->disconnect(); // YES, WE DO NEED TO DISCONNECT BEFORE WE CLONE THE DB OBJECT. ARGH! $db = clone $oldDb; $query = $db->getQuery(true) ->select('*') ->from($db->qn($tableName)) ->where($db->qn($remoteKey) . ' = ' . $db->q($value)); $db->setQuery($query, 0, 1); $data = $db->loadObject(); if (!is_object($data)) { throw new RuntimeException(sprintf('Cannot load item from relation against table %s column %s', $tableName, $remoteKey), 500); } $table->bind($data); return $table; } /** * Returns a FOFDatabaseIterator based on a given relation * * @param array $relation Relation definition * * @return FOFDatabaseIterator * * @throws RuntimeException */ private function getIteratorFromRelation($relation) { // Get a table object from the table class name $tableClass = $relation['tableClass']; $tableClassParts = FOFInflector::explode($tableClass); $table = FOFTable::getInstance($tableClassParts[2], ucfirst($tableClassParts[0]) . ucfirst($tableClassParts[1])); // Get the table name $tableName = $table->getTableName(); // Get the remote and local key names $remoteKey = $relation['remoteKey']; $localKey = $relation['localKey']; // Get the local key's value $value = $this->table->$localKey; // This is required to prevent one relation from killing the db cursor used in a different relation... $oldDb = $this->table->getDbo(); $oldDb->disconnect(); // YES, WE DO NEED TO DISCONNECT BEFORE WE CLONE THE DB OBJECT. ARGH! $db = clone $oldDb; // Begin the query $query = $db->getQuery(true) ->select('*') ->from($db->qn($tableName)); // Do we have a pivot table? $hasPivot = array_key_exists('pivotTable', $relation); // If we don't have pivot it's a straightforward query if (!$hasPivot) { $query ->where($db->qn($remoteKey) . ' = ' . $db->q($value)); } // If we have a pivot table we have to do a subquery else { $subQuery = $db->getQuery(true) ->select($db->qn($relation['theirPivotKey'])) ->from($db->qn($relation['pivotTable'])) ->where($db->qn($relation['ourPivotKey']) . ' = ' . $db->q($value)); $query->where($db->qn($remoteKey) . ' IN (' . $subQuery . ')'); } $db->setQuery($query); $cursor = $db->execute(); $iterator = FOFDatabaseIterator::getIterator($db->name, $cursor, null, $tableClass); return $iterator; } /** * Add any bespoke relation which doesn't involve a pivot table. * * @param string $relationType The type of the relationship (parent, child, children) * @param string $itemName is how it will be known locally to the getRelatedItems method * @param string $tableClass if skipped it is defined automatically as ComponentnameTableItemname * @param string $localKey is the column containing our side of the FK relation, default: componentname_itemname_id * @param string $remoteKey is the remote table's FK column, default: componentname_itemname_id * @param boolean $default is this the default children relationship? * * @return void */ private function addBespokeSimpleRelation($relationType, $itemName, $tableClass, $localKey, $remoteKey, $default) { $ourPivotKey = null; $theirPivotKey = null; $pivotTable = null; $this->normaliseParameters(false, $itemName, $tableClass, $localKey, $remoteKey, $ourPivotKey, $theirPivotKey, $pivotTable); $this->relations[$relationType][$itemName] = array( 'tableClass' => $tableClass, 'localKey' => $localKey, 'remoteKey' => $remoteKey, ); if ($default) { $this->defaultRelation[$relationType] = $itemName; } } /** * Add any bespoke relation which involves a pivot table. * * @param string $relationType The type of the relationship (multiple) * @param string $itemName is how it will be known locally to the getRelatedItems method * @param string $tableClass if skipped it is defined automatically as ComponentnameTableItemname * @param string $localKey is the column containing our side of the FK relation, default: componentname_itemname_id * @param string $remoteKey is the remote table's FK column, default: componentname_itemname_id * @param string $ourPivotKey is the column containing our side of the FK relation in the pivot table, default: $localKey * @param string $theirPivotKey is the column containing the other table's side of the FK relation in the pivot table, default $remoteKey * @param string $pivotTable is the name of the glue (pivot) table, default: #__componentname_thisclassname_itemname with plural items (e.g. #__foobar_users_roles) * @param boolean $default is this the default children relationship? * * @return void */ private function addBespokePivotRelation($relationType, $itemName, $tableClass, $localKey, $remoteKey, $ourPivotKey, $theirPivotKey, $pivotTable, $default) { $this->normaliseParameters(true, $itemName, $tableClass, $localKey, $remoteKey, $ourPivotKey, $theirPivotKey, $pivotTable); $this->relations[$relationType][$itemName] = array( 'tableClass' => $tableClass, 'localKey' => $localKey, 'remoteKey' => $remoteKey, 'ourPivotKey' => $ourPivotKey, 'theirPivotKey' => $theirPivotKey, 'pivotTable' => $pivotTable, ); if ($default) { $this->defaultRelation[$relationType] = $itemName; } } /** * Normalise the parameters of a relation, guessing missing values * * @param boolean $pivot Is this a many to many relation involving a pivot table? * @param string $itemName is how it will be known locally to the getRelatedItems method (plural) * @param string $tableClass if skipped it is defined automatically as ComponentnameTableItemname * @param string $localKey is the column containing our side of the FK relation, default: componentname_itemname_id * @param string $remoteKey is the remote table's FK column, default: componentname_itemname_id * @param string $ourPivotKey is the column containing our side of the FK relation in the pivot table, default: $localKey * @param string $theirPivotKey is the column containing the other table's side of the FK relation in the pivot table, default $remoteKey * @param string $pivotTable is the name of the glue (pivot) table, default: #__componentname_thisclassname_itemname with plural items (e.g. #__foobar_users_roles) * * @return void */ private function normaliseParameters($pivot = false, &$itemName, &$tableClass, &$localKey, &$remoteKey, &$ourPivotKey, &$theirPivotKey, &$pivotTable) { // Get a default table class if none is provided if (empty($tableClass)) { $tableClassParts = explode('_', $itemName, 3); if (count($tableClassParts) == 1) { array_unshift($tableClassParts, $this->componentName); } if ($tableClassParts[0] == 'joomla') { $tableClassParts[0] = 'J'; } $tableClass = ucfirst($tableClassParts[0]) . 'Table' . ucfirst(FOFInflector::singularize($tableClassParts[1])); } // Make sure we have both a local and remote key if (empty($localKey) && empty($remoteKey)) { $tableClassParts = FOFInflector::explode($tableClass); $localKey = $tableClassParts[0] . '_' . $tableClassParts[2] . '_id'; $remoteKey = $localKey; } elseif (empty($localKey) && !empty($remoteKey)) { $localKey = $remoteKey; } elseif (!empty($localKey) && empty($remoteKey)) { $remoteKey = $localKey; } // If we don't have a pivot table nullify the relevant variables and return if (!$pivot) { $ourPivotKey = null; $theirPivotKey = null; $pivotTable = null; return; } if (empty($ourPivotKey)) { $ourPivotKey = $localKey; } if (empty($theirPivotKey)) { $theirPivotKey = $remoteKey; } if (empty($pivotTable)) { $pivotTable = '#__' . strtolower($this->componentName) . '_' . strtolower(FOFInflector::pluralize($this->tableType)) . '_'; $itemNameParts = explode('_', $itemName); $lastPart = array_pop($itemNameParts); $pivotTable .= strtolower($lastPart); } } /** * Normalises the format of a relation name * * @param string $itemName The raw relation name * @param boolean $pluralise Should I pluralise the name? If not, I will singularise it * * @return string The normalised relation key name */ private function normaliseItemName($itemName, $pluralise = false) { // Explode the item name $itemNameParts = explode('_', $itemName); // If we have multiple parts the first part is considered to be the component name if (count($itemNameParts) > 1) { $prefix = array_shift($itemNameParts); } else { $prefix = null; } // If we still have multiple parts we need to pluralise/singularise the last part and join everything in // CamelCase format if (count($itemNameParts) > 1) { $name = array_pop($itemNameParts); $name = $pluralise ? FOFInflector::pluralize($name) : FOFInflector::singularize($name); $itemNameParts[] = $name; $itemName = FOFInflector::implode($itemNameParts); } // Otherwise we singularise/pluralise the remaining part else { $name = array_pop($itemNameParts); $itemName = $pluralise ? FOFInflector::pluralize($name) : FOFInflector::singularize($name); } if (!empty($prefix)) { $itemName = $prefix . '_' . $itemName; } return $itemName; } }PKY[ M Mfof/table/table.phpnuW+AgetCmd('option', ''); $tmpInput->set('option', $option); $config['input'] = $tmpInput; if (!in_array($prefix, array('Table', 'JTable'))) { preg_match('/(.*)Table$/', $prefix, $m); $option = 'com_' . strtolower($m[1]); } if (array_key_exists('option', $config)) { $option = $config['option']; } $config['option'] = $option; if (!array_key_exists('view', $config)) { $config['view'] = $config['input']->getCmd('view', 'cpanel'); } if (is_null($type)) { if ($prefix == 'JTable') { $prefix = 'Table'; } $type = $config['view']; } $type = preg_replace('/[^A-Z0-9_\.-]/i', '', $type); $tableClass = $prefix . ucfirst($type); $config['_table_type'] = $type; $config['_table_class'] = $tableClass; $configProvider = new FOFConfigProvider; $configProviderKey = $option . '.views.' . FOFInflector::singularize($type) . '.config.'; if (!array_key_exists($tableClass, self::$instances)) { if (!class_exists($tableClass)) { $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($config['option']); $searchPaths = array( $componentPaths['main'] . '/tables', $componentPaths['admin'] . '/tables' ); if (array_key_exists('tablepath', $config)) { array_unshift($searchPaths, $config['tablepath']); } $altPath = $configProvider->get($configProviderKey . 'table_path', null); if ($altPath) { array_unshift($searchPaths, $componentPaths['admin'] . '/' . $altPath); } $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); $path = $filesystem->pathFind( $searchPaths, strtolower($type) . '.php' ); if ($path) { require_once $path; } } if (!class_exists($tableClass)) { $tableClass = 'FOFTable'; } $component = str_replace('com_', '', $config['option']); $tbl_common = $component . '_'; if (!array_key_exists('tbl', $config)) { $config['tbl'] = strtolower('#__' . $tbl_common . strtolower(FOFInflector::pluralize($type))); } $altTbl = $configProvider->get($configProviderKey . 'tbl', null); if ($altTbl) { $config['tbl'] = $altTbl; } if (!array_key_exists('tbl_key', $config)) { $keyName = FOFInflector::singularize($type); $config['tbl_key'] = strtolower($tbl_common . $keyName . '_id'); } $altTblKey = $configProvider->get($configProviderKey . 'tbl_key', null); if ($altTblKey) { $config['tbl_key'] = $altTblKey; } if (!array_key_exists('db', $config)) { $config['db'] = FOFPlatform::getInstance()->getDbo(); } // Assign the correct table alias if (array_key_exists('table_alias', $config)) { $table_alias = $config['table_alias']; } else { $configProviderTableAliasKey = $option . '.tables.' . FOFInflector::singularize($type) . '.tablealias'; $table_alias = $configProvider->get($configProviderTableAliasKey, false ); } // Can we use the FOF cache? if (!array_key_exists('use_table_cache', $config)) { $config['use_table_cache'] = FOFPlatform::getInstance()->isGlobalFOFCacheEnabled(); } $alt_use_table_cache = $configProvider->get($configProviderKey . 'use_table_cache', null); if (!is_null($alt_use_table_cache)) { $config['use_table_cache'] = $alt_use_table_cache; } // Create a new table instance $instance = new $tableClass($config['tbl'], $config['tbl_key'], $config['db'], $config); $instance->setInput($tmpInput); $instance->setTablePrefix($prefix); $instance->setTableAlias($table_alias); // Determine and set the asset key for this table $assetKey = 'com_' . $component . '.' . strtolower(FOFInflector::singularize($type)); $assetKey = $configProvider->get($configProviderKey . 'asset_key', $assetKey); $instance->setAssetKey($assetKey); if (array_key_exists('trigger_events', $config)) { $instance->setTriggerEvents($config['trigger_events']); } if (version_compare(JVERSION, '3.1', 'ge')) { if (array_key_exists('has_tags', $config)) { $instance->setHasTags($config['has_tags']); } $altHasTags = $configProvider->get($configProviderKey . 'has_tags', null); if ($altHasTags) { $instance->setHasTags($altHasTags); } } else { $instance->setHasTags(false); } $configProviderFieldmapKey = $option . '.tables.' . FOFInflector::singularize($type) . '.field'; $aliases = $configProvider->get($configProviderFieldmapKey, $instance->_columnAlias); $instance->_columnAlias = array_merge($instance->_columnAlias, $aliases); self::$instances[$tableClass] = $instance; } return self::$instances[$tableClass]; } /** * Force an instance inside class cache. Setting arguments to null nukes all or part of the cache * * @param string|null $key TableClass to replace. Set it to null to nuke the entire cache * @param FOFTable|null $instance Instance to replace. Set it to null to nuke $key instances * * @return bool Did I correctly switch the instance? */ public static function forceInstance($key = null, $instance = null) { if(is_null($key)) { self::$instances = array(); return true; } elseif($key && isset(self::$instances[$key])) { // I'm forcing an instance, but it's not a FOFTable, abort! abort! if(!$instance || ($instance && $instance instanceof FOFTable)) { self::$instances[$key] = $instance; return true; } } return false; } /** * Class Constructor. * * @param string $table Name of the database table to model. * @param string $key Name of the primary key field in the table. * @param JDatabaseDriver &$db Database driver * @param array $config The configuration parameters array */ public function __construct($table, $key, &$db, $config = array()) { $this->_tbl = $table; $this->_tbl_key = $key; $this->_db = $db; // Make sure the use FOF cache information is in the config if (!array_key_exists('use_table_cache', $config)) { $config['use_table_cache'] = FOFPlatform::getInstance()->isGlobalFOFCacheEnabled(); } $this->config = $config; // Load the configuration provider $this->configProvider = new FOFConfigProvider; // Load the behavior dispatcher $this->tableDispatcher = new FOFTableDispatcherBehavior; // Initialise the table properties. if ($fields = $this->getTableFields()) { // Do I have anything joined? $j_fields = $this->getQueryJoinFields(); if ($j_fields) { $fields = array_merge($fields, $j_fields); } $this->setKnownFields(array_keys($fields), true); $this->reset(); } else { $this->_tableExists = false; } // Get the input if (array_key_exists('input', $config)) { if ($config['input'] instanceof FOFInput) { $this->input = $config['input']; } else { $this->input = new FOFInput($config['input']); } } else { $this->input = new FOFInput; } // Set the $name/$_name variable $component = $this->input->getCmd('option', 'com_foobar'); if (array_key_exists('option', $config)) { $component = $config['option']; } $this->input->set('option', $component); // Apply table behaviors $type = explode("_", $this->_tbl); $type = $type[count($type) - 1]; $this->_configProviderKey = $component . '.tables.' . FOFInflector::singularize($type); $configKey = $this->_configProviderKey . '.behaviors'; if (isset($config['behaviors'])) { $behaviors = (array) $config['behaviors']; } elseif ($behaviors = $this->configProvider->get($configKey, null)) { $behaviors = explode(',', $behaviors); } else { $behaviors = $this->default_behaviors; } if (is_array($behaviors) && count($behaviors)) { foreach ($behaviors as $behavior) { $this->addBehavior($behavior); } } // If we are tracking assets, make sure an access field exists and initially set the default. $asset_id_field = $this->getColumnAlias('asset_id'); $access_field = $this->getColumnAlias('access'); if (in_array($asset_id_field, $this->getKnownFields())) { JLoader::import('joomla.access.rules'); $this->_trackAssets = true; } // If the access property exists, set the default. if (in_array($access_field, $this->getKnownFields())) { $this->$access_field = (int) FOFPlatform::getInstance()->getConfig()->get('access'); } $this->config = $config; } /** * Replace the entire known fields array * * @param array $fields A simple array of known field names * @param boolean $initialise Should we initialise variables to null? * * @return void */ public function setKnownFields($fields, $initialise = false) { $this->knownFields = $fields; if ($initialise) { foreach ($this->knownFields as $field) { $this->$field = null; } } } /** * Get the known fields array * * @return array */ public function getKnownFields() { return $this->knownFields; } /** * Add a field to the known fields array * * @param string $field The name of the field to add * @param boolean $initialise Should we initialise the variable to null? * * @return void */ public function addKnownField($field, $initialise = false) { if (!in_array($field, $this->knownFields)) { $this->knownFields[] = $field; if ($initialise) { $this->$field = null; } } } /** * Remove a field from the known fields array * * @param string $field The name of the field to remove * * @return void */ public function removeKnownField($field) { if (in_array($field, $this->knownFields)) { $pos = array_search($field, $this->knownFields); unset($this->knownFields[$pos]); } } /** * Adds a behavior to the table * * @param string $name The name of the behavior * @param array $config Optional Behavior configuration * * @return boolean */ public function addBehavior($name, $config = array()) { // First look for ComponentnameTableViewnameBehaviorName (e.g. FoobarTableItemsBehaviorTags) if (isset($this->config['option'])) { $option_name = str_replace('com_', '', $this->config['option']); $behaviorClass = $this->config['_table_class'] . 'Behavior' . ucfirst(strtolower($name)); if (class_exists($behaviorClass)) { $behavior = new $behaviorClass($this->tableDispatcher, $config); return true; } // Then look for ComponentnameTableBehaviorName (e.g. FoobarTableBehaviorTags) $option_name = str_replace('com_', '', $this->config['option']); $behaviorClass = ucfirst($option_name) . 'TableBehavior' . ucfirst(strtolower($name)); if (class_exists($behaviorClass)) { $behavior = new $behaviorClass($this->tableDispatcher, $config); return true; } } // Nothing found? Return false. $behaviorClass = 'FOFTableBehavior' . ucfirst(strtolower($name)); if (class_exists($behaviorClass) && $this->tableDispatcher) { $behavior = new $behaviorClass($this->tableDispatcher, $config); return true; } return false; } /** * Sets the events trigger switch state * * @param boolean $newState The new state of the switch (what else could it be?) * * @return void */ public function setTriggerEvents($newState = false) { $this->_trigger_events = $newState ? true : false; } /** * Gets the events trigger switch state * * @return boolean */ public function getTriggerEvents() { return $this->_trigger_events; } /** * Gets the has tags switch state * * @return bool */ public function hasTags() { return $this->_has_tags; } /** * Sets the has tags switch state * * @param bool $newState */ public function setHasTags($newState = false) { $this->_has_tags = false; // Tags are available only in 3.1+ if (version_compare(JVERSION, '3.1', 'ge')) { $this->_has_tags = $newState ? true : false; } } /** * Set the class prefix * * @param string $prefix The prefix */ public function setTablePrefix($prefix) { $this->_tablePrefix = $prefix; } /** * Sets fields to be skipped from automatic checks. * * @param array/string $skip Fields to be skipped by automatic checks * * @return void */ public function setSkipChecks($skip) { $this->_skipChecks = (array) $skip; } /** * Method to load a row from the database by primary key and bind the fields * to the FOFTable instance properties. * * @param mixed $keys An optional primary key value to load the row by, or an array of fields to match. If not * set the instance property value is used. * @param boolean $reset True to reset the default values before loading the new row. * * @return boolean True if successful. False if row not found. * * @throws RuntimeException * @throws UnexpectedValueException */ public function load($keys = null, $reset = true) { if (!$this->_tableExists) { $result = false; return $this->onAfterLoad($result); } if (empty($keys)) { // If empty, use the value of the current key $keyName = $this->_tbl_key; if (isset($this->$keyName)) { $keyValue = $this->$keyName; } else { $keyValue = null; } // If empty primary key there's is no need to load anything if (empty($keyValue)) { $result = true; return $this->onAfterLoad($result); } $keys = array($keyName => $keyValue); } elseif (!is_array($keys)) { // Load by primary key. $keys = array($this->_tbl_key => $keys); } if ($reset) { $this->reset(); } // Initialise the query. $query = $this->_db->getQuery(true); $query->select($this->_tbl . '.*'); $query->from($this->_tbl); // Joined fields are ok, since I initialized them in the constructor $fields = $this->getKnownFields(); foreach ($keys as $field => $value) { // Check that $field is in the table. if (!in_array($field, $fields)) { throw new UnexpectedValueException(sprintf('Missing field in table %s : %s.', $this->_tbl, $field)); } // Add the search tuple to the query. $query->where($this->_db->qn($this->_tbl . '.' . $field) . ' = ' . $this->_db->q($value)); } // Do I have any joined table? $j_query = $this->getQueryJoin(); if ($j_query) { if ($j_query->select && $j_query->select->getElements()) { //$query->select($this->normalizeSelectFields($j_query->select->getElements(), true)); $query->select($j_query->select->getElements()); } if ($j_query->join) { foreach ($j_query->join as $join) { $t = (string) $join; // Joomla doesn't provide any access to the "name" variable, so I have to work with strings... if (stripos($t, 'inner') !== false) { $query->innerJoin($join->getElements()); } elseif (stripos($t, 'left') !== false) { $query->leftJoin($join->getElements()); } elseif (stripos($t, 'right') !== false) { $query->rightJoin($join->getElements()); } elseif (stripos($t, 'outer') !== false) { $query->outerJoin($join->getElements()); } } } } $this->_db->setQuery($query); $row = $this->_db->loadAssoc(); // Check that we have a result. if (empty($row)) { $result = false; return $this->onAfterLoad($result); } // Bind the object with the row and return. $result = $this->bind($row); $this->onAfterLoad($result); return $result; } /** * Based on fields properties (nullable column), checks if the field is required or not * * @return boolean */ public function check() { if (!$this->_autoChecks) { return true; } $fields = $this->getTableFields(); // No fields? Why in the hell am I here? if(!$fields) { return false; } $result = true; $known = $this->getKnownFields(); $skipFields[] = $this->_tbl_key; if(in_array($this->getColumnAlias('hits'), $known)) $skipFields[] = $this->getColumnAlias('hits'); if(in_array($this->getColumnAlias('created_on'), $known)) $skipFields[] = $this->getColumnAlias('created_on'); if(in_array($this->getColumnAlias('created_by'), $known)) $skipFields[] = $this->getColumnAlias('created_by'); if(in_array($this->getColumnAlias('modified_on'), $known)) $skipFields[] = $this->getColumnAlias('modified_on'); if(in_array($this->getColumnAlias('modified_by'), $known)) $skipFields[] = $this->getColumnAlias('modified_by'); if(in_array($this->getColumnAlias('locked_by'), $known)) $skipFields[] = $this->getColumnAlias('locked_by'); if(in_array($this->getColumnAlias('locked_on'), $known)) $skipFields[] = $this->getColumnAlias('locked_on'); // Let's merge it with custom skips $skipFields = array_merge($skipFields, $this->_skipChecks); foreach ($fields as $field) { $fieldName = $field->Field; if (empty($fieldName)) { $fieldName = $field->column_name; } // Field is not nullable but it's null, set error if ($field->Null == 'NO' && $this->$fieldName == '' && !in_array($fieldName, $skipFields)) { $text = str_replace('#__', 'COM_', $this->getTableName()) . '_ERR_' . $fieldName; $this->setError(JText::_(strtoupper($text))); $result = false; } } return $result; } /** * Method to reset class properties to the defaults set in the class * definition. It will ignore the primary key as well as any private class * properties. * * @return void */ public function reset() { if (!$this->onBeforeReset()) { return false; } // Get the default values for the class from the table. $fields = $this->getTableFields(); $j_fields = $this->getQueryJoinFields(); if ($j_fields) { $fields = array_merge($fields, $j_fields); } foreach ($fields as $k => $v) { // If the property is not the primary key or private, reset it. if ($k != $this->_tbl_key && (strpos($k, '_') !== 0)) { $this->$k = $v->Default; } } if (!$this->onAfterReset()) { return false; } } /** * Clones the current object, after resetting it * * @return FOFTable */ public function getClone() { $clone = clone $this; $clone->reset(); $key = $this->getKeyName(); $clone->$key = null; return $clone; } /** * Generic check for whether dependencies exist for this object in the db schema * * @param integer $oid The primary key of the record to delete * @param array $joins Any joins to foreign table, used to determine if dependent records exist * * @return boolean True if the record can be deleted */ public function canDelete($oid = null, $joins = null) { $k = $this->_tbl_key; if ($oid) { $this->$k = intval($oid); } if (is_array($joins)) { $db = $this->_db; $query = $db->getQuery(true) ->select($db->qn('master') . '.' . $db->qn($k)) ->from($db->qn($this->_tbl) . ' AS ' . $db->qn('master')); $tableNo = 0; foreach ($joins as $table) { $tableNo++; $query->select( array( 'COUNT(DISTINCT ' . $db->qn('t' . $tableNo) . '.' . $db->qn($table['idfield']) . ') AS ' . $db->qn($table['idalias']) ) ); $query->join('LEFT', $db->qn($table['name']) . ' AS ' . $db->qn('t' . $tableNo) . ' ON ' . $db->qn('t' . $tableNo) . '.' . $db->qn($table['joinfield']) . ' = ' . $db->qn('master') . '.' . $db->qn($k) ); } $query->where($db->qn('master') . '.' . $db->qn($k) . ' = ' . $db->q($this->$k)); $query->group($db->qn('master') . '.' . $db->qn($k)); $this->_db->setQuery((string) $query); if (version_compare(JVERSION, '3.0', 'ge')) { try { $obj = $this->_db->loadObject(); } catch (JDatabaseException $e) { $this->setError($e->getMessage()); } } else { if (!$obj = $this->_db->loadObject()) { $this->setError($this->_db->getErrorMsg()); return false; } } $msg = array(); $i = 0; foreach ($joins as $table) { $k = $table['idalias']; if ($obj->$k > 0) { $msg[] = JText::_($table['label']); } $i++; } if (count($msg)) { $option = $this->input->getCmd('option', 'com_foobar'); $comName = str_replace('com_', '', $option); $tview = str_replace('#__' . $comName . '_', '', $this->_tbl); $prefix = $option . '_' . $tview . '_NODELETE_'; foreach ($msg as $key) { $this->setError(JText::_($prefix . $key)); } return false; } else { return true; } } return true; } /** * Method to bind an associative array or object to the FOFTable instance.This * method only binds properties that are publicly accessible and optionally * takes an array of properties to ignore when binding. * * @param mixed $src An associative array or object to bind to the FOFTable instance. * @param mixed $ignore An optional array or space separated list of properties to ignore while binding. * * @return boolean True on success. * * @throws InvalidArgumentException */ public function bind($src, $ignore = array()) { if (!$this->onBeforeBind($src)) { return false; } // If the source value is not an array or object return false. if (!is_object($src) && !is_array($src)) { throw new InvalidArgumentException(sprintf('%s::bind(*%s*)', get_class($this), gettype($src))); } // If the source value is an object, get its accessible properties. if (is_object($src)) { $src = get_object_vars($src); } // If the ignore value is a string, explode it over spaces. if (!is_array($ignore)) { $ignore = explode(' ', $ignore); } // Bind the source value, excluding the ignored fields. foreach ($this->getKnownFields() as $k) { // Only process fields not in the ignore array. if (!in_array($k, $ignore)) { if (isset($src[$k])) { $this->$k = $src[$k]; } } } $result = $this->onAfterBind($src); return $result; } /** * Method to store a row in the database from the FOFTable instance properties. * If a primary key value is set the row with that primary key value will be * updated with the instance property values. If no primary key value is set * a new row will be inserted into the database with the properties from the * FOFTable instance. * * @param boolean $updateNulls True to update fields even if they are null. * * @return boolean True on success. */ public function store($updateNulls = false) { if (!$this->onBeforeStore($updateNulls)) { return false; } $k = $this->_tbl_key; if ($this->$k == 0) { $this->$k = null; } // Create the object used for inserting/updating data to the database $fields = $this->getTableFields(); $properties = $this->getKnownFields(); $keys = array(); foreach ($properties as $property) { // 'input' property is a reserved name if (isset($fields[$property])) { $keys[] = $property; } } $updateObject = array(); foreach ($keys as $key) { $updateObject[$key] = $this->$key; } $updateObject = (object)$updateObject; // If a primary key exists update the object, otherwise insert it. if ($this->$k) { $result = $this->_db->updateObject($this->_tbl, $updateObject, $this->_tbl_key, $updateNulls); } else { $result = $this->_db->insertObject($this->_tbl, $updateObject, $this->_tbl_key); } if ($result !== true) { $this->setError($this->_db->getErrorMsg()); return false; } $this->bind($updateObject); if ($this->_locked) { $this->_unlock(); } $result = $this->onAfterStore(); return $result; } /** * Method to move a row in the ordering sequence of a group of rows defined by an SQL WHERE clause. * Negative numbers move the row up in the sequence and positive numbers move it down. * * @param integer $delta The direction and magnitude to move the row in the ordering sequence. * @param string $where WHERE clause to use for limiting the selection of rows to compact the * ordering values. * * @return mixed Boolean True on success. * * @throws UnexpectedValueException */ public function move($delta, $where = '') { if (!$this->onBeforeMove($delta, $where)) { return false; } // If there is no ordering field set an error and return false. $ordering_field = $this->getColumnAlias('ordering'); if (!in_array($ordering_field, $this->getKnownFields())) { throw new UnexpectedValueException(sprintf('%s does not support ordering.', $this->_tbl)); } // If the change is none, do nothing. if (empty($delta)) { $result = $this->onAfterMove(); return $result; } $k = $this->_tbl_key; $row = null; $query = $this->_db->getQuery(true); // If the table is not loaded, return false if (empty($this->$k)) { return false; } // Select the primary key and ordering values from the table. $query->select(array($this->_db->qn($this->_tbl_key), $this->_db->qn($ordering_field))); $query->from($this->_tbl); // If the movement delta is negative move the row up. if ($delta < 0) { $query->where($this->_db->qn($ordering_field) . ' < ' . $this->_db->q((int) $this->$ordering_field)); $query->order($this->_db->qn($ordering_field) . ' DESC'); } // If the movement delta is positive move the row down. elseif ($delta > 0) { $query->where($this->_db->qn($ordering_field) . ' > ' . $this->_db->q((int) $this->$ordering_field)); $query->order($this->_db->qn($ordering_field) . ' ASC'); } // Add the custom WHERE clause if set. if ($where) { $query->where($where); } // Select the first row with the criteria. $this->_db->setQuery($query, 0, 1); $row = $this->_db->loadObject(); // If a row is found, move the item. if (!empty($row)) { // Update the ordering field for this instance to the row's ordering value. $query = $this->_db->getQuery(true); $query->update($this->_tbl); $query->set($this->_db->qn($ordering_field) . ' = ' . $this->_db->q((int) $row->$ordering_field)); $query->where($this->_tbl_key . ' = ' . $this->_db->q($this->$k)); $this->_db->setQuery($query); $this->_db->execute(); // Update the ordering field for the row to this instance's ordering value. $query = $this->_db->getQuery(true); $query->update($this->_tbl); $query->set($this->_db->qn($ordering_field) . ' = ' . $this->_db->q((int) $this->$ordering_field)); $query->where($this->_tbl_key . ' = ' . $this->_db->q($row->$k)); $this->_db->setQuery($query); $this->_db->execute(); // Update the instance value. $this->$ordering_field = $row->$ordering_field; } else { // Update the ordering field for this instance. $query = $this->_db->getQuery(true); $query->update($this->_tbl); $query->set($this->_db->qn($ordering_field) . ' = ' . $this->_db->q((int) $this->$ordering_field)); $query->where($this->_tbl_key . ' = ' . $this->_db->q($this->$k)); $this->_db->setQuery($query); $this->_db->execute(); } $result = $this->onAfterMove(); return $result; } /** * Change the ordering of the records of the table * * @param string $where The WHERE clause of the SQL used to fetch the order * * @return boolean True is successful * * @throws UnexpectedValueException */ public function reorder($where = '') { if (!$this->onBeforeReorder($where)) { return false; } // If there is no ordering field set an error and return false. $order_field = $this->getColumnAlias('ordering'); if (!in_array($order_field, $this->getKnownFields())) { throw new UnexpectedValueException(sprintf('%s does not support ordering.', $this->_tbl_key)); } $k = $this->_tbl_key; // Get the primary keys and ordering values for the selection. $query = $this->_db->getQuery(true); $query->select($this->_tbl_key . ', ' . $this->_db->qn($order_field)); $query->from($this->_tbl); $query->where($this->_db->qn($order_field) . ' >= ' . $this->_db->q(0)); $query->order($this->_db->qn($order_field)); // Setup the extra where and ordering clause data. if ($where) { $query->where($where); } $this->_db->setQuery($query); $rows = $this->_db->loadObjectList(); // Compact the ordering values. foreach ($rows as $i => $row) { // Make sure the ordering is a positive integer. if ($row->$order_field >= 0) { // Only update rows that are necessary. if ($row->$order_field != $i + 1) { // Update the row ordering field. $query = $this->_db->getQuery(true); $query->update($this->_tbl); $query->set($this->_db->qn($order_field) . ' = ' . $this->_db->q($i + 1)); $query->where($this->_tbl_key . ' = ' . $this->_db->q($row->$k)); $this->_db->setQuery($query); $this->_db->execute(); } } } $result = $this->onAfterReorder(); return $result; } /** * Check out (lock) a record * * @param integer $userId The locking user's ID * @param integer $oid The primary key value of the record to lock * * @return boolean True on success */ public function checkout($userId, $oid = null) { $fldLockedBy = $this->getColumnAlias('locked_by'); $fldLockedOn = $this->getColumnAlias('locked_on'); if (!(in_array($fldLockedBy, $this->getKnownFields()) || in_array($fldLockedOn, $this->getKnownFields()))) { return true; } $k = $this->_tbl_key; if ($oid !== null) { $this->$k = $oid; } // No primary key defined, stop here if (!$this->$k) { return false; } $date = FOFPlatform::getInstance()->getDate(); $time = $date->toSql(); $query = $this->_db->getQuery(true) ->update($this->_db->qn($this->_tbl)) ->set( array( $this->_db->qn($fldLockedBy) . ' = ' . $this->_db->q((int) $userId), $this->_db->qn($fldLockedOn) . ' = ' . $this->_db->q($time) ) ) ->where($this->_db->qn($this->_tbl_key) . ' = ' . $this->_db->q($this->$k)); $this->_db->setQuery((string) $query); $this->$fldLockedBy = $userId; $this->$fldLockedOn = $time; return $this->_db->execute(); } /** * Check in (unlock) a record * * @param integer $oid The primary key value of the record to unlock * * @return boolean True on success */ public function checkin($oid = null) { $fldLockedBy = $this->getColumnAlias('locked_by'); $fldLockedOn = $this->getColumnAlias('locked_on'); if (!(in_array($fldLockedBy, $this->getKnownFields()) || in_array($fldLockedOn, $this->getKnownFields()))) { return true; } $k = $this->_tbl_key; if ($oid !== null) { $this->$k = $oid; } if ($this->$k == null) { return false; } $query = $this->_db->getQuery(true) ->update($this->_db->qn($this->_tbl)) ->set( array( $this->_db->qn($fldLockedBy) . ' = 0', $this->_db->qn($fldLockedOn) . ' = ' . $this->_db->q($this->_db->getNullDate()) ) ) ->where($this->_db->qn($this->_tbl_key) . ' = ' . $this->_db->q($this->$k)); $this->_db->setQuery((string) $query); $this->$fldLockedBy = 0; $this->$fldLockedOn = ''; return $this->_db->execute(); } /** * Is a record locked? * * @param integer $with The userid to preform the match with. If an item is checked * out by this user the function will return false. * @param integer $unused_against Junk inherited from JTable; ignore * * @throws UnexpectedValueException * * @return boolean True if the record is locked by another user */ public function isCheckedOut($with = 0, $unused_against = null) { $against = null; $fldLockedBy = $this->getColumnAlias('locked_by'); $k = $this->_tbl_key; // If no primary key is given, return false. if ($this->$k === null) { throw new UnexpectedValueException('Null primary key not allowed.'); } if (isset($this) && is_a($this, 'FOFTable') && !$against) { $against = $this->get($fldLockedBy); } // Item is not checked out, or being checked out by the same user if (!$against || $against == $with) { return false; } $session = JTable::getInstance('session'); return $session->exists($against); } /** * Copy (duplicate) one or more records * * @param integer|array $cid The primary key value (or values) or the record(s) to copy * * @return boolean True on success */ public function copy($cid = null) { //We have to cast the id as array, or the helper function will return an empty set if($cid) { $cid = (array) $cid; } FOFUtilsArray::toInteger($cid); $k = $this->_tbl_key; if (count($cid) < 1) { if ($this->$k) { $cid = array($this->$k); } else { $this->setError("No items selected."); return false; } } $created_by = $this->getColumnAlias('created_by'); $created_on = $this->getColumnAlias('created_on'); $modified_by = $this->getColumnAlias('modified_by'); $modified_on = $this->getColumnAlias('modified_on'); $locked_byName = $this->getColumnAlias('locked_by'); $checkin = in_array($locked_byName, $this->getKnownFields()); foreach ($cid as $item) { // Prevent load with id = 0 if (!$item) { continue; } $this->load($item); if ($checkin) { // We're using the checkin and the record is used by someone else if ($this->isCheckedOut($item)) { continue; } } // TODO Should we notify the user that we had a problem with this record? if (!$this->onBeforeCopy($item)) { continue; } $this->$k = null; $this->$created_by = null; $this->$created_on = null; $this->$modified_on = null; $this->$modified_by = null; // Let's fire the event only if everything is ok // TODO Should we notify the user that we had a problem with this record? if ($this->store()) { // TODO Should we notify the user that we had a problem with this record? $this->onAfterCopy($item); } $this->reset(); } return true; } /** * Publish or unpublish records * * @param integer|array $cid The primary key value(s) of the item(s) to publish/unpublish * @param integer $publish 1 to publish an item, 0 to unpublish * @param integer $user_id The user ID of the user (un)publishing the item. * * @return boolean True on success, false on failure (e.g. record is locked) */ public function publish($cid = null, $publish = 1, $user_id = 0) { $enabledName = $this->getColumnAlias('enabled'); $locked_byName = $this->getColumnAlias('locked_by'); // Mhm... you called the publish method on a table without publish support... if(!in_array($enabledName, $this->getKnownFields())) { return false; } //We have to cast the id as array, or the helper function will return an empty set if($cid) { $cid = (array) $cid; } FOFUtilsArray::toInteger($cid); $user_id = (int) $user_id; $publish = (int) $publish; $k = $this->_tbl_key; if (count($cid) < 1) { if ($this->$k) { $cid = array($this->$k); } else { $this->setError("No items selected."); return false; } } if (!$this->onBeforePublish($cid, $publish)) { return false; } $query = $this->_db->getQuery(true) ->update($this->_db->qn($this->_tbl)) ->set($this->_db->qn($enabledName) . ' = ' . (int) $publish); $checkin = in_array($locked_byName, $this->getKnownFields()); if ($checkin) { $query->where( ' (' . $this->_db->qn($locked_byName) . ' = 0 OR ' . $this->_db->qn($locked_byName) . ' = ' . (int) $user_id . ')', 'AND' ); } //Why this crazy statement? // TODO Rewrite this statment using IN. Check if it work in SQLServer and PostgreSQL $cids = $this->_db->qn($k) . ' = ' . implode(' OR ' . $this->_db->qn($k) . ' = ', $cid); $query->where('(' . $cids . ')'); $this->_db->setQuery((string) $query); if (version_compare(JVERSION, '3.0', 'ge')) { try { $this->_db->execute(); } catch (JDatabaseException $e) { $this->setError($e->getMessage()); } } else { if (!$this->_db->execute()) { $this->setError($this->_db->getErrorMsg()); return false; } } if (count($cid) == 1 && $checkin) { if ($this->_db->getAffectedRows() == 1) { // TODO should we check for its return value? $this->checkin($cid[0]); if ($this->$k == $cid[0]) { $this->$enabledName = $publish; } } } $this->setError(''); return true; } /** * Delete a record * * @param integer $oid The primary key value of the item to delete * * @throws UnexpectedValueException * * @return boolean True on success */ public function delete($oid = null) { if ($oid) { $this->load($oid); } $k = $this->_tbl_key; $pk = (!$oid) ? $this->$k : $oid; // If no primary key is given, return false. if (!$pk) { throw new UnexpectedValueException('Null primary key not allowed.'); } // Execute the logic only if I have a primary key, otherwise I could have weird results if (!$this->onBeforeDelete($oid)) { return false; } // Delete the row by primary key. $query = $this->_db->getQuery(true); $query->delete(); $query->from($this->_tbl); $query->where($this->_tbl_key . ' = ' . $this->_db->q($pk)); $this->_db->setQuery($query); // @TODO Check for a database error. $this->_db->execute(); $result = $this->onAfterDelete($oid); return $result; } /** * Register a hit on a record * * @param integer $oid The primary key value of the record * @param boolean $log Should I log the hit? * * @return boolean True on success */ public function hit($oid = null, $log = false) { if (!$this->onBeforeHit($oid, $log)) { return false; } // If there is no hits field, just return true. $hits_field = $this->getColumnAlias('hits'); if (!in_array($hits_field, $this->getKnownFields())) { return true; } $k = $this->_tbl_key; $pk = ($oid) ? $oid : $this->$k; // If no primary key is given, return false. if (!$pk) { $result = false; } else { // Check the row in by primary key. $query = $this->_db->getQuery(true) ->update($this->_tbl) ->set($this->_db->qn($hits_field) . ' = (' . $this->_db->qn($hits_field) . ' + 1)') ->where($this->_tbl_key . ' = ' . $this->_db->q($pk)); $this->_db->setQuery($query)->execute(); // In order to update the table object, I have to load the table if(!$this->$k) { $query = $this->_db->getQuery(true) ->select($this->_db->qn($hits_field)) ->from($this->_db->qn($this->_tbl)) ->where($this->_db->qn($this->_tbl_key) . ' = ' . $this->_db->q($pk)); $this->$hits_field = $this->_db->setQuery($query)->loadResult(); } else { // Set table values in the object. $this->$hits_field++; } $result = true; } if ($result) { $result = $this->onAfterHit($oid); } return $result; } /** * Export the item as a CSV line * * @param string $separator CSV separator. Tip: use "\t" to get a TSV file instead. * * @return string The CSV line */ public function toCSV($separator = ',') { $csv = array(); foreach (get_object_vars($this) as $k => $v) { if (!in_array($k, $this->getKnownFields())) { continue; } $csv[] = '"' . str_replace('"', '""', $v) . '"'; } $csv = implode($separator, $csv); return $csv; } /** * Exports the table in array format * * @return array */ public function getData() { $ret = array(); foreach (get_object_vars($this) as $k => $v) { if (!in_array($k, $this->getKnownFields())) { continue; } $ret[$k] = $v; } return $ret; } /** * Get the header for exporting item list to CSV * * @param string $separator CSV separator. Tip: use "\t" to get a TSV file instead. * * @return string The CSV file's header */ public function getCSVHeader($separator = ',') { $csv = array(); foreach (get_object_vars($this) as $k => $v) { if (!in_array($k, $this->getKnownFields())) { continue; } $csv[] = '"' . str_replace('"', '\"', $k) . '"'; } $csv = implode($separator, $csv); return $csv; } /** * Get the columns from a database table. * * @param string $tableName Table name. If null current table is used * * @return mixed An array of the field names, or false if an error occurs. */ public function getTableFields($tableName = null) { // Should I load the cached data? $useCache = array_key_exists('use_table_cache', $this->config) ? $this->config['use_table_cache'] : false; // Make sure we have a list of tables in this db if (empty(self::$tableCache)) { if ($useCache) { // Try to load table cache from a cache file $cacheData = FOFPlatform::getInstance()->getCache('tables', null); // Unserialise the cached data, or set the table cache to empty // if the cache data wasn't loaded. if (!is_null($cacheData)) { self::$tableCache = json_decode($cacheData, true); } else { self::$tableCache = array(); } } // This check is true if the cache data doesn't exist / is not loaded if (empty(self::$tableCache)) { self::$tableCache = $this->_db->getTableList(); if ($useCache) { FOFPlatform::getInstance()->setCache('tables', json_encode(self::$tableCache)); } } } // Make sure the cached table fields cache is loaded if (empty(self::$tableFieldCache)) { if ($useCache) { // Try to load table cache from a cache file $cacheData = FOFPlatform::getInstance()->getCache('tablefields', null); // Unserialise the cached data, or set to empty if the cache // data wasn't loaded. if (!is_null($cacheData)) { $decoded = json_decode($cacheData, true); $tableCache = array(); if (count($decoded)) { foreach ($decoded as $myTableName => $tableFields) { $temp = array(); if (is_array($tableFields)) { foreach($tableFields as $field => $def) { $temp[$field] = (object)$def; } $tableCache[$myTableName] = $temp; } elseif (is_object($tableFields) || is_bool($tableFields)) { $tableCache[$myTableName] = $tableFields; } } } self::$tableFieldCache = $tableCache; } else { self::$tableFieldCache = array(); } } } if (!$tableName) { $tableName = $this->_tbl; } // Try to load again column specifications if the table is not loaded OR if it's loaded and // the previous call returned an error if (!array_key_exists($tableName, self::$tableFieldCache) || (isset(self::$tableFieldCache[$tableName]) && !self::$tableFieldCache[$tableName])) { // Lookup the fields for this table only once. $name = $tableName; $prefix = $this->_db->getPrefix(); if (substr($name, 0, 3) == '#__') { $checkName = $prefix . substr($name, 3); } else { $checkName = $name; } if (!in_array($checkName, self::$tableCache)) { // The table doesn't exist. Return false. self::$tableFieldCache[$tableName] = false; } elseif (version_compare(JVERSION, '3.0', 'ge')) { $fields = $this->_db->getTableColumns($name, false); if (empty($fields)) { $fields = false; } self::$tableFieldCache[$tableName] = $fields; } else { $fields = $this->_db->getTableFields($name, false); if (!isset($fields[$name])) { $fields = false; } self::$tableFieldCache[$tableName] = $fields[$name]; } // PostgreSQL date type compatibility if (($this->_db->name == 'postgresql') && (self::$tableFieldCache[$tableName] != false)) { foreach (self::$tableFieldCache[$tableName] as $field) { if (strtolower($field->type) == 'timestamp without time zone') { if (stristr($field->Default, '\'::timestamp without time zone')) { list ($date, $junk) = explode('::', $field->Default, 2); $field->Default = trim($date, "'"); } } } } // Save the data for this table into the cache if ($useCache) { $cacheData = FOFPlatform::getInstance()->setCache('tablefields', json_encode(self::$tableFieldCache)); } } return self::$tableFieldCache[$tableName]; } public function getTableAlias() { return $this->_tableAlias; } public function setTableAlias($string) { $string = preg_replace('#[^A-Z0-9_]#i', '', $string); $this->_tableAlias = $string; } /** * Method to return the real name of a "special" column such as ordering, hits, published * etc etc. In this way you are free to follow your db naming convention and use the * built in Joomla functions. * * @param string $column Name of the "special" column (ie ordering, hits etc etc) * * @return string The string that identify the special */ public function getColumnAlias($column) { if (isset($this->_columnAlias[$column])) { $return = $this->_columnAlias[$column]; } else { $return = $column; } $return = preg_replace('#[^A-Z0-9_]#i', '', $return); return $return; } /** * Method to register a column alias for a "special" column. * * @param string $column The "special" column (ie ordering) * @param string $columnAlias The real column name (ie foo_ordering) * * @return void */ public function setColumnAlias($column, $columnAlias) { $column = strtolower($column); $column = preg_replace('#[^A-Z0-9_]#i', '', $column); $this->_columnAlias[$column] = $columnAlias; } /** * Get a JOIN query, used to join other tables * * @param boolean $asReference Return an object reference instead of a copy * * @return JDatabaseQuery Query used to join other tables */ public function getQueryJoin($asReference = false) { if ($asReference) { return $this->_queryJoin; } else { if ($this->_queryJoin) { return clone $this->_queryJoin; } else { return null; } } } /** * Sets the query with joins to other tables * * @param JDatabaseQuery $query The JOIN query to use * * @return void */ public function setQueryJoin(JDatabaseQuery $query) { $this->_queryJoin = $query; } /** * Extracts the fields from the join query * * @return array Fields contained in the join query */ protected function getQueryJoinFields() { $query = $this->getQueryJoin(); if (!$query) { return array(); } $tables = array(); $j_tables = array(); $j_fields = array(); // Get joined tables. Ignore FROM clause, since it should not be used (the starting point is the table "table") $joins = $query->join; foreach ($joins as $join) { $tables = array_merge($tables, $join->getElements()); } // Clean up table names foreach($tables as $table) { preg_match('#(.*)((\w)*(on|using))(.*)#i', $table, $matches); if($matches && isset($matches[1])) { // I always want the first part, no matter what $parts = explode(' ', $matches[1]); $t_table = $parts[0]; if($this->isQuoted($t_table)) { $t_table = substr($t_table, 1, strlen($t_table) - 2); } if(!in_array($t_table, $j_tables)) { $j_tables[] = $t_table; } } } // Do I have the current table inside the query join? Remove it (its fields are already ok) $find = array_search($this->getTableName(), $j_tables); if($find !== false) { unset($j_tables[$find]); } // Get table fields $fields = array(); foreach ($j_tables as $table) { $t_fields = $this->getTableFields($table); if ($t_fields) { $fields = array_merge($fields, $t_fields); } } // Remove any fields that aren't in the joined select $j_select = $query->select; if ($j_select && $j_select->getElements()) { $j_fields = $this->normalizeSelectFields($j_select->getElements()); } // I can intesect the keys $fields = array_intersect_key($fields, $j_fields); // Now I walk again the array to change the key of columns that have an alias foreach ($j_fields as $column => $alias) { if ($column != $alias) { $fields[$alias] = $fields[$column]; unset($fields[$column]); } } return $fields; } /** * Normalizes the fields, returning an associative array with all the fields. * Ie array('foobar as foo, bar') becomes array('foobar' => 'foo', 'bar' => 'bar') * * @param array $fields Array with column fields * * @return array Normalized array */ protected function normalizeSelectFields($fields) { $db = FOFPlatform::getInstance()->getDbo(); $return = array(); foreach ($fields as $field) { $t_fields = explode(',', $field); foreach ($t_fields as $t_field) { // Is there any alias? $parts = preg_split('#\sas\s#i', $t_field); // Do I have a table.column situation? Let's get the field name $tableField = explode('.', $parts[0]); if(isset($tableField[1])) { $column = trim($tableField[1]); } else { $column = trim($tableField[0]); } // Is this field quoted? If so, remove the quotes if($this->isQuoted($column)) { $column = substr($column, 1, strlen($column) - 2); } if(isset($parts[1])) { $alias = trim($parts[1]); // Is this field quoted? If so, remove the quotes if($this->isQuoted($alias)) { $alias = substr($alias, 1, strlen($alias) - 2); } } else { $alias = $column; } $return[$column] = $alias; } } return $return; } /** * Is the field quoted? * * @param string $column Column field * * @return bool Is the field quoted? */ protected function isQuoted($column) { // Empty string, un-quoted by definition if(!$column) { return false; } // I need some "magic". If the first char is not a letter, a number // an underscore or # (needed for table), then most likely the field is quoted preg_match_all('/^[a-z0-9_#]/i', $column, $matches); if(!$matches[0]) { return true; } return false; } /** * The event which runs before binding data to the table * * NOTE TO 3RD PARTY DEVELOPERS: * * When you override the following methods in your child classes, * be sure to call parent::method *AFTER* your code, otherwise the * plugin events do NOT get triggered * * Example: * protected function onAfterStore(){ * // Your code here * return parent::onAfterStore() && $your_result; * } * * Do not do it the other way around, e.g. return $your_result && parent::onAfterStore() * Due to PHP short-circuit boolean evaluation the parent::onAfterStore() * will not be called if $your_result is false. * * @param object|array &$from The data to bind * * @return boolean True on success */ protected function onBeforeBind(&$from) { // Call the behaviors $result = $this->tableDispatcher->trigger('onBeforeBind', array(&$this, &$from)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onBeforeBind' . ucfirst($name), array(&$this, &$from)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs after loading a record from the database * * @param boolean &$result Did the load succeeded? * * @return void */ protected function onAfterLoad(&$result) { // Call the behaviors $eventResult = $this->tableDispatcher->trigger('onAfterLoad', array(&$this, &$result)); if (in_array(false, $eventResult, true)) { // Behavior failed, return false $result = false; return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); FOFPlatform::getInstance()->runPlugins('onAfterLoad' . ucfirst($name), array(&$this, &$result)); } } /** * The event which runs before storing (saving) data to the database * * @param boolean $updateNulls Should nulls be saved as nulls (true) or just skipped over (false)? * * @return boolean True to allow saving */ protected function onBeforeStore($updateNulls) { // Do we have a "Created" set of fields? $created_on = $this->getColumnAlias('created_on'); $created_by = $this->getColumnAlias('created_by'); $modified_on = $this->getColumnAlias('modified_on'); $modified_by = $this->getColumnAlias('modified_by'); $locked_on = $this->getColumnAlias('locked_on'); $locked_by = $this->getColumnAlias('locked_by'); $title = $this->getColumnAlias('title'); $slug = $this->getColumnAlias('slug'); $hasCreatedOn = in_array($created_on, $this->getKnownFields()); $hasCreatedBy = in_array($created_by, $this->getKnownFields()); if ($hasCreatedOn && $hasCreatedBy) { $hasModifiedOn = in_array($modified_on, $this->getKnownFields()); $hasModifiedBy = in_array($modified_by, $this->getKnownFields()); $nullDate = $this->_db->getNullDate(); if (empty($this->$created_by) || ($this->$created_on == $nullDate) || empty($this->$created_on)) { $uid = FOFPlatform::getInstance()->getUser()->id; if ($uid) { $this->$created_by = FOFPlatform::getInstance()->getUser()->id; } $date = FOFPlatform::getInstance()->getDate('now', null, false); $this->$created_on = $date->toSql(); } elseif ($hasModifiedOn && $hasModifiedBy) { $uid = FOFPlatform::getInstance()->getUser()->id; if ($uid) { $this->$modified_by = FOFPlatform::getInstance()->getUser()->id; } $date = FOFPlatform::getInstance()->getDate('now', null, false); $this->$modified_on = $date->toSql(); } } // Do we have a set of title and slug fields? $hasTitle = in_array($title, $this->getKnownFields()); $hasSlug = in_array($slug, $this->getKnownFields()); if ($hasTitle && $hasSlug) { if (empty($this->$slug)) { // Create a slug from the title $this->$slug = FOFStringUtils::toSlug($this->$title); } else { // Filter the slug for invalid characters $this->$slug = FOFStringUtils::toSlug($this->$slug); } // Make sure we don't have a duplicate slug on this table $db = $this->getDbo(); $query = $db->getQuery(true) ->select($db->qn($slug)) ->from($this->_tbl) ->where($db->qn($slug) . ' = ' . $db->q($this->$slug)) ->where('NOT ' . $db->qn($this->_tbl_key) . ' = ' . $db->q($this->{$this->_tbl_key})); $db->setQuery($query); $existingItems = $db->loadAssocList(); $count = 0; $newSlug = $this->$slug; while (!empty($existingItems)) { $count++; $newSlug = $this->$slug . '-' . $count; $query = $db->getQuery(true) ->select($db->qn($slug)) ->from($this->_tbl) ->where($db->qn($slug) . ' = ' . $db->q($newSlug)) ->where('NOT '. $db->qn($this->_tbl_key) . ' = ' . $db->q($this->{$this->_tbl_key})); $db->setQuery($query); $existingItems = $db->loadAssocList(); } $this->$slug = $newSlug; } // Call the behaviors $result = $this->tableDispatcher->trigger('onBeforeStore', array(&$this, $updateNulls)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } // Execute onBeforeStore events in loaded plugins if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onBeforeStore' . ucfirst($name), array(&$this, $updateNulls)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs after binding data to the class * * @param object|array &$src The data to bind * * @return boolean True to allow binding without an error */ protected function onAfterBind(&$src) { // Call the behaviors $options = array( 'component' => $this->input->get('option'), 'view' => $this->input->get('view'), 'table_prefix' => $this->_tablePrefix ); $result = $this->tableDispatcher->trigger('onAfterBind', array(&$this, &$src, $options)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onAfterBind' . ucfirst($name), array(&$this, &$src)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs after storing (saving) data to the database * * @return boolean True to allow saving without an error */ protected function onAfterStore() { // Call the behaviors $result = $this->tableDispatcher->trigger('onAfterStore', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onAfterStore' . ucfirst($name), array(&$this)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs before moving a record * * @param boolean $updateNulls Should nulls be saved as nulls (true) or just skipped over (false)? * * @return boolean True to allow moving */ protected function onBeforeMove($updateNulls) { // Call the behaviors $result = $this->tableDispatcher->trigger('onBeforeMove', array(&$this, $updateNulls)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onBeforeMove' . ucfirst($name), array(&$this, $updateNulls)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs after moving a record * * @return boolean True to allow moving without an error */ protected function onAfterMove() { // Call the behaviors $result = $this->tableDispatcher->trigger('onAfterMove', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onAfterMove' . ucfirst($name), array(&$this)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs before reordering a table * * @param string $where The WHERE clause of the SQL query to run on reordering (record filter) * * @return boolean True to allow reordering */ protected function onBeforeReorder($where = '') { // Call the behaviors $result = $this->tableDispatcher->trigger('onBeforeReorder', array(&$this, $where)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onBeforeReorder' . ucfirst($name), array(&$this, $where)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs after reordering a table * * @return boolean True to allow the reordering to complete without an error */ protected function onAfterReorder() { // Call the behaviors $result = $this->tableDispatcher->trigger('onAfterReorder', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onAfterReorder' . ucfirst($name), array(&$this)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs before deleting a record * * @param integer $oid The PK value of the record to delete * * @return boolean True to allow the deletion */ protected function onBeforeDelete($oid) { // Call the behaviors $result = $this->tableDispatcher->trigger('onBeforeDelete', array(&$this, $oid)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onBeforeDelete' . ucfirst($name), array(&$this, $oid)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs after deleting a record * * @param integer $oid The PK value of the record which was deleted * * @return boolean True to allow the deletion without errors */ protected function onAfterDelete($oid) { // Call the behaviors $result = $this->tableDispatcher->trigger('onAfterDelete', array(&$this, $oid)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onAfterDelete' . ucfirst($name), array(&$this, $oid)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs before hitting a record * * @param integer $oid The PK value of the record to hit * @param boolean $log Should we log the hit? * * @return boolean True to allow the hit */ protected function onBeforeHit($oid, $log) { // Call the behaviors $result = $this->tableDispatcher->trigger('onBeforeHit', array(&$this, $oid, $log)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onBeforeHit' . ucfirst($name), array(&$this, $oid, $log)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs after hitting a record * * @param integer $oid The PK value of the record which was hit * * @return boolean True to allow the hitting without errors */ protected function onAfterHit($oid) { // Call the behaviors $result = $this->tableDispatcher->trigger('onAfterHit', array(&$this, $oid)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onAfterHit' . ucfirst($name), array(&$this, $oid)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The even which runs before copying a record * * @param integer $oid The PK value of the record being copied * * @return boolean True to allow the copy to take place */ protected function onBeforeCopy($oid) { // Call the behaviors $result = $this->tableDispatcher->trigger('onBeforeCopy', array(&$this, $oid)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onBeforeCopy' . ucfirst($name), array(&$this, $oid)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The even which runs after copying a record * * @param integer $oid The PK value of the record which was copied (not the new one) * * @return boolean True to allow the copy without errors */ protected function onAfterCopy($oid) { // Call the behaviors $result = $this->tableDispatcher->trigger('onAfterCopy', array(&$this, $oid)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onAfterCopy' . ucfirst($name), array(&$this, $oid)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs before a record is (un)published * * @param integer|array &$cid The PK IDs of the records being (un)published * @param integer $publish 1 to publish, 0 to unpublish * * @return boolean True to allow the (un)publish to proceed */ protected function onBeforePublish(&$cid, $publish) { // Call the behaviors $result = $this->tableDispatcher->trigger('onBeforePublish', array(&$this, &$cid, $publish)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onBeforePublish' . ucfirst($name), array(&$this, &$cid, $publish)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The event which runs after the object is reset to its default values. * * @return boolean True to allow the reset to complete without errors */ protected function onAfterReset() { // Call the behaviors $result = $this->tableDispatcher->trigger('onAfterReset', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onAfterReset' . ucfirst($name), array(&$this)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * The even which runs before the object is reset to its default values. * * @return boolean True to allow the reset to complete */ protected function onBeforeReset() { // Call the behaviors $result = $this->tableDispatcher->trigger('onBeforeReset', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } if ($this->_trigger_events) { $name = FOFInflector::pluralize($this->getKeyName()); $result = FOFPlatform::getInstance()->runPlugins('onBeforeReset' . ucfirst($name), array(&$this)); if (in_array(false, $result, true)) { return false; } else { return true; } } return true; } /** * Replace the input object of this table with the provided FOFInput object * * @param FOFInput $input The new input object * * @return void */ public function setInput(FOFInput $input) { $this->input = $input; } /** * Get the columns from database table. * * @return mixed An array of the field names, or false if an error occurs. * * @deprecated 2.1 */ public function getFields() { return $this->getTableFields(); } /** * Add a filesystem path where FOFTable should search for table class files. * You may either pass a string or an array of paths. * * @param mixed $path A filesystem path or array of filesystem paths to add. * * @return array An array of filesystem paths to find FOFTable classes in. */ public static function addIncludePath($path = null) { // If the internal paths have not been initialised, do so with the base table path. if (empty(self::$_includePaths)) { self::$_includePaths = array(__DIR__); } // Convert the passed path(s) to add to an array. settype($path, 'array'); // If we have new paths to add, do so. if (!empty($path) && !in_array($path, self::$_includePaths)) { // Check and add each individual new path. foreach ($path as $dir) { // Sanitize path. $dir = trim($dir); // Add to the front of the list so that custom paths are searched first. array_unshift(self::$_includePaths, $dir); } } return self::$_includePaths; } /** * Loads the asset table related to this table. * This will help tests, too, since we can mock this function. * * @return bool|JTableAsset False on failure, otherwise JTableAsset */ protected function getAsset() { $name = $this->_getAssetName(); // Do NOT touch JTable here -- we are loading the core asset table which is a JTable, not a FOFTable $asset = JTable::getInstance('Asset'); if (!$asset->loadByName($name)) { return false; } return $asset; } /** * Method to compute the default name of the asset. * The default name is in the form table_name.id * where id is the value of the primary key of the table. * * @throws UnexpectedValueException * * @return string */ public function getAssetName() { $k = $this->_tbl_key; // If there is no assetKey defined, stop here, or we'll get a wrong name if(!$this->_assetKey || !$this->$k) { throw new UnexpectedValueException('Table must have an asset key defined and a value for the table id in order to track assets'); } return $this->_assetKey . '.' . (int) $this->$k; } /** * Method to compute the default name of the asset. * The default name is in the form table_name.id * where id is the value of the primary key of the table. * * @throws UnexpectedValueException * * @return string */ public function getAssetKey() { return $this->_assetKey; } /** * Method to return the title to use for the asset table. In * tracking the assets a title is kept for each asset so that there is some * context available in a unified access manager. Usually this would just * return $this->title or $this->name or whatever is being used for the * primary name of the row. If this method is not overridden, the asset name is used. * * @return string The string to use as the title in the asset table. */ public function getAssetTitle() { return $this->getAssetName(); } /** * Method to get the parent asset under which to register this one. * By default, all assets are registered to the ROOT node with ID, * which will default to 1 if none exists. * The extended class can define a table and id to lookup. If the * asset does not exist it will be created. * * @param FOFTable $table A FOFTable object for the asset parent. * @param integer $id Id to look up * * @return integer */ public function getAssetParentId($table = null, $id = null) { // For simple cases, parent to the asset root. $assets = JTable::getInstance('Asset', 'JTable', array('dbo' => $this->getDbo())); $rootId = $assets->getRootId(); if (!empty($rootId)) { return $rootId; } return 1; } /** * This method sets the asset key for the items of this table. Obviously, it * is only meant to be used when you have a table with an asset field. * * @param string $assetKey The name of the asset key to use * * @return void */ public function setAssetKey($assetKey) { $this->_assetKey = $assetKey; } /** * Method to get the database table name for the class. * * @return string The name of the database table being modeled. */ public function getTableName() { return $this->_tbl; } /** * Method to get the primary key field name for the table. * * @return string The name of the primary key for the table. */ public function getKeyName() { return $this->_tbl_key; } /** * Method to get the JDatabaseDriver object. * * @return JDatabaseDriver The internal database driver object. */ public function getDbo() { return $this->_db; } /** * Method to set the JDatabaseDriver object. * * @param JDatabaseDriver $db A JDatabaseDriver object to be used by the table object. * * @return boolean True on success. */ public function setDBO(JDatabaseDriver $db) { $this->_db = $db; return true; } /** * Method to set rules for the record. * * @param mixed $input A JAccessRules object, JSON string, or array. * * @return void */ public function setRules($input) { if ($input instanceof JAccessRules) { $this->_rules = $input; } else { $this->_rules = new JAccessRules($input); } } /** * Method to get the rules for the record. * * @return JAccessRules object */ public function getRules() { return $this->_rules; } /** * Method to check if the record is treated as an ACL asset * * @return boolean [description] */ public function isAssetsTracked() { return $this->_trackAssets; } /** * Method to manually set this record as ACL asset or not. * We have to do this since the automatic check is made in the constructor, but here we can't set any alias. * So, even if you have an alias for `asset_id`, it wouldn't be reconized and assets won't be tracked. * * @param $state */ public function setAssetsTracked($state) { $state = (bool) $state; if($state) { JLoader::import('joomla.access.rules'); } $this->_trackAssets = $state; } /** * Method to provide a shortcut to binding, checking and storing a FOFTable * instance to the database table. The method will check a row in once the * data has been stored and if an ordering filter is present will attempt to * reorder the table rows based on the filter. The ordering filter is an instance * property name. The rows that will be reordered are those whose value matches * the FOFTable instance for the property specified. * * @param mixed $src An associative array or object to bind to the FOFTable instance. * @param string $orderingFilter Filter for the order updating * @param mixed $ignore An optional array or space separated list of properties * to ignore while binding. * * @return boolean True on success. */ public function save($src, $orderingFilter = '', $ignore = '') { // Attempt to bind the source to the instance. if (!$this->bind($src, $ignore)) { return false; } // Run any sanity checks on the instance and verify that it is ready for storage. if (!$this->check()) { return false; } // Attempt to store the properties to the database table. if (!$this->store()) { return false; } // Attempt to check the row in, just in case it was checked out. if (!$this->checkin()) { return false; } // If an ordering filter is set, attempt reorder the rows in the table based on the filter and value. if ($orderingFilter) { $filterValue = $this->$orderingFilter; $this->reorder($orderingFilter ? $this->_db->qn($orderingFilter) . ' = ' . $this->_db->q($filterValue) : ''); } // Set the error to empty and return true. $this->setError(''); return true; } /** * Method to get the next ordering value for a group of rows defined by an SQL WHERE clause. * This is useful for placing a new item last in a group of items in the table. * * @param string $where WHERE clause to use for selecting the MAX(ordering) for the table. * * @return mixed Boolean false an failure or the next ordering value as an integer. */ public function getNextOrder($where = '') { // If there is no ordering field set an error and return false. $ordering = $this->getColumnAlias('ordering'); if (!in_array($ordering, $this->getKnownFields())) { throw new UnexpectedValueException(sprintf('%s does not support ordering.', get_class($this))); } // Get the largest ordering value for a given where clause. $query = $this->_db->getQuery(true); $query->select('MAX('.$this->_db->qn($ordering).')'); $query->from($this->_tbl); if ($where) { $query->where($where); } $this->_db->setQuery($query); $max = (int) $this->_db->loadResult(); // Return the largest ordering value + 1. return ($max + 1); } /** * Method to lock the database table for writing. * * @return boolean True on success. * * @throws RuntimeException */ protected function _lock() { $this->_db->lockTable($this->_tbl); $this->_locked = true; return true; } /** * Method to unlock the database table for writing. * * @return boolean True on success. */ protected function _unlock() { $this->_db->unlockTables(); $this->_locked = false; return true; } public function setConfig(array $config) { $this->config = $config; } /** * Get the content type for ucm * * @return string The content type alias */ public function getContentType() { $component = $this->input->get('option'); $view = FOFInflector::singularize($this->input->get('view')); $alias = $component . '.' . $view; return $alias; } /** * Returns the table relations object of the current table, lazy-loading it if necessary * * @return FOFTableRelations */ public function getRelations() { if (is_null($this->_relations)) { $this->_relations = new FOFTableRelations($this); } return $this->_relations; } /** * Gets a reference to the configuration parameters provider for this table * * @return FOFConfigProvider */ public function getConfigProvider() { return $this->configProvider; } /** * Returns the configuration parameters provider's key for this table * * @return string */ public function getConfigProviderKey() { return $this->_configProviderKey; } } PKY[kfof/less/less.phpnuW+A * Licensed under MIT or GPLv3, see LICENSE * * THIS IS THIRD PARTY CODE. Code comments are mostly useless placeholders to * stop phpcs from complaining... * * @package FrameworkOnFramework * @since 2.0 */ class FOFLess { public static $VERSION = "v0.3.9"; protected static $TRUE = array("keyword", "true"); protected static $FALSE = array("keyword", "false"); protected $libFunctions = array(); protected $registeredVars = array(); protected $preserveComments = false; /** * Prefix of abstract properties * * @var string */ public $vPrefix = '@'; /** * Prefix of abstract blocks * * @var string */ public $mPrefix = '$'; public $parentSelector = '&'; public $importDisabled = false; public $importDir = ''; protected $numberPrecision = null; /** * Set to the parser that generated the current line when compiling * so we know how to create error messages * * @var FOFLessParser */ protected $sourceParser = null; protected $sourceLoc = null; public static $defaultValue = array("keyword", ""); /** * Uniquely identify imports * * @var integer */ protected static $nextImportId = 0; /** * Attempts to find the path of an import url, returns null for css files * * @param string $url The URL of the import * * @return string|null */ protected function findImport($url) { foreach ((array) $this->importDir as $dir) { $full = $dir . (substr($dir, -1) != '/' ? '/' : '') . $url; if ($this->fileExists($file = $full . '.less') || $this->fileExists($file = $full)) { return $file; } } return null; } /** * Does file $name exists? It's a simple proxy to JFile for now * * @param string $name The file we check for existence * * @return boolean */ protected function fileExists($name) { /** FOF - BEGIN CHANGE * */ return FOFPlatform::getInstance()->getIntegrationObject('filesystem')->fileExists($name); /** FOF - END CHANGE * */ } /** * Compresslist * * @param array $items Items * @param string $delim Delimiter * * @return array */ public static function compressList($items, $delim) { if (!isset($items[1]) && isset($items[0])) { return $items[0]; } else { return array('list', $delim, $items); } } /** * Quote for regular expression * * @param string $what What to quote * * @return string Quoted string */ public static function preg_quote($what) { return preg_quote($what, '/'); } /** * Try import * * @param string $importPath Import path * @param stdObject $parentBlock Parent block * @param string $out Out * * @return boolean */ protected function tryImport($importPath, $parentBlock, $out) { if ($importPath[0] == "function" && $importPath[1] == "url") { $importPath = $this->flattenList($importPath[2]); } $str = $this->coerceString($importPath); if ($str === null) { return false; } $url = $this->compileValue($this->lib_e($str)); // Don't import if it ends in css if (substr_compare($url, '.css', -4, 4) === 0) { return false; } $realPath = $this->findImport($url); if ($realPath === null) { return false; } if ($this->importDisabled) { return array(false, "/* import disabled */"); } $this->addParsedFile($realPath); $parser = $this->makeParser($realPath); $root = $parser->parse(file_get_contents($realPath)); // Set the parents of all the block props foreach ($root->props as $prop) { if ($prop[0] == "block") { $prop[1]->parent = $parentBlock; } } /** * Copy mixins into scope, set their parents, bring blocks from import * into current block * TODO: need to mark the source parser these came from this file */ foreach ($root->children as $childName => $child) { if (isset($parentBlock->children[$childName])) { $parentBlock->children[$childName] = array_merge( $parentBlock->children[$childName], $child ); } else { $parentBlock->children[$childName] = $child; } } $pi = pathinfo($realPath); $dir = $pi["dirname"]; list($top, $bottom) = $this->sortProps($root->props, true); $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir); return array(true, $bottom, $parser, $dir); } /** * Compile Imported Props * * @param array $props Props * @param stdClass $block Block * @param string $out Out * @param FOFLessParser $sourceParser Source parser * @param string $importDir Import dir * * @return void */ protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir) { $oldSourceParser = $this->sourceParser; $oldImport = $this->importDir; // TODO: this is because the importDir api is stupid $this->importDir = (array) $this->importDir; array_unshift($this->importDir, $importDir); foreach ($props as $prop) { $this->compileProp($prop, $block, $out); } $this->importDir = $oldImport; $this->sourceParser = $oldSourceParser; } /** * Recursively compiles a block. * * A block is analogous to a CSS block in most cases. A single LESS document * is encapsulated in a block when parsed, but it does not have parent tags * so all of it's children appear on the root level when compiled. * * Blocks are made up of props and children. * * Props are property instructions, array tuples which describe an action * to be taken, eg. write a property, set a variable, mixin a block. * * The children of a block are just all the blocks that are defined within. * This is used to look up mixins when performing a mixin. * * Compiling the block involves pushing a fresh environment on the stack, * and iterating through the props, compiling each one. * * @param stdClass $block Block * * @see FOFLess::compileProp() * * @return void */ protected function compileBlock($block) { switch ($block->type) { case "root": $this->compileRoot($block); break; case null: $this->compileCSSBlock($block); break; case "media": $this->compileMedia($block); break; case "directive": $name = "@" . $block->name; if (!empty($block->value)) { $name .= " " . $this->compileValue($this->reduce($block->value)); } $this->compileNestedBlock($block, array($name)); break; default: $this->throwError("unknown block type: $block->type\n"); } } /** * Compile CSS block * * @param stdClass $block Block to compile * * @return void */ protected function compileCSSBlock($block) { $env = $this->pushEnv(); $selectors = $this->compileSelectors($block->tags); $env->selectors = $this->multiplySelectors($selectors); $out = $this->makeOutputBlock(null, $env->selectors); $this->scope->children[] = $out; $this->compileProps($block, $out); // Mixins carry scope with them! $block->scope = $env; $this->popEnv(); } /** * Compile media * * @param stdClass $media Media * * @return void */ protected function compileMedia($media) { $env = $this->pushEnv($media); $parentScope = $this->mediaParent($this->scope); $query = $this->compileMediaQuery($this->multiplyMedia($env)); $this->scope = $this->makeOutputBlock($media->type, array($query)); $parentScope->children[] = $this->scope; $this->compileProps($media, $this->scope); if (count($this->scope->lines) > 0) { $orphanSelelectors = $this->findClosestSelectors(); if (!is_null($orphanSelelectors)) { $orphan = $this->makeOutputBlock(null, $orphanSelelectors); $orphan->lines = $this->scope->lines; array_unshift($this->scope->children, $orphan); $this->scope->lines = array(); } } $this->scope = $this->scope->parent; $this->popEnv(); } /** * Media parent * * @param stdClass $scope Scope * * @return stdClass */ protected function mediaParent($scope) { while (!empty($scope->parent)) { if (!empty($scope->type) && $scope->type != "media") { break; } $scope = $scope->parent; } return $scope; } /** * Compile nested block * * @param stdClass $block Block * @param array $selectors Selectors * * @return void */ protected function compileNestedBlock($block, $selectors) { $this->pushEnv($block); $this->scope = $this->makeOutputBlock($block->type, $selectors); $this->scope->parent->children[] = $this->scope; $this->compileProps($block, $this->scope); $this->scope = $this->scope->parent; $this->popEnv(); } /** * Compile root * * @param stdClass $root Root * * @return void */ protected function compileRoot($root) { $this->pushEnv(); $this->scope = $this->makeOutputBlock($root->type); $this->compileProps($root, $this->scope); $this->popEnv(); } /** * Compile props * * @param type $block Something * @param type $out Something * * @return void */ protected function compileProps($block, $out) { foreach ($this->sortProps($block->props) as $prop) { $this->compileProp($prop, $block, $out); } } /** * Sort props * * @param type $props X * @param type $split X * * @return type */ protected function sortProps($props, $split = false) { $vars = array(); $imports = array(); $other = array(); foreach ($props as $prop) { switch ($prop[0]) { case "assign": if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix) { $vars[] = $prop; } else { $other[] = $prop; } break; case "import": $id = self::$nextImportId++; $prop[] = $id; $imports[] = $prop; $other[] = array("import_mixin", $id); break; default: $other[] = $prop; } } if ($split) { return array(array_merge($vars, $imports), $other); } else { return array_merge($vars, $imports, $other); } } /** * Compile media query * * @param type $queries Queries * * @return string */ protected function compileMediaQuery($queries) { $compiledQueries = array(); foreach ($queries as $query) { $parts = array(); foreach ($query as $q) { switch ($q[0]) { case "mediaType": $parts[] = implode(" ", array_slice($q, 1)); break; case "mediaExp": if (isset($q[2])) { $parts[] = "($q[1]: " . $this->compileValue($this->reduce($q[2])) . ")"; } else { $parts[] = "($q[1])"; } break; case "variable": $parts[] = $this->compileValue($this->reduce($q)); break; } } if (count($parts) > 0) { $compiledQueries[] = implode(" and ", $parts); } } $out = "@media"; if (!empty($parts)) { $out .= " " . implode($this->formatter->selectorSeparator, $compiledQueries); } return $out; } /** * Multiply media * * @param type $env X * @param type $childQueries X * * @return type */ protected function multiplyMedia($env, $childQueries = null) { if (is_null($env) || !empty($env->block->type) && $env->block->type != "media") { return $childQueries; } // Plain old block, skip if (empty($env->block->type)) { return $this->multiplyMedia($env->parent, $childQueries); } $out = array(); $queries = $env->block->queries; if (is_null($childQueries)) { $out = $queries; } else { foreach ($queries as $parent) { foreach ($childQueries as $child) { $out[] = array_merge($parent, $child); } } } return $this->multiplyMedia($env->parent, $out); } /** * Expand parent selectors * * @param type &$tag Tag * @param type $replace Replace * * @return type */ protected function expandParentSelectors(&$tag, $replace) { $parts = explode("$&$", $tag); $count = 0; foreach ($parts as &$part) { $part = str_replace($this->parentSelector, $replace, $part, $c); $count += $c; } $tag = implode($this->parentSelector, $parts); return $count; } /** * Find closest selectors * * @return array */ protected function findClosestSelectors() { $env = $this->env; $selectors = null; while ($env !== null) { if (isset($env->selectors)) { $selectors = $env->selectors; break; } $env = $env->parent; } return $selectors; } /** * Multiply $selectors against the nearest selectors in env * * @param array $selectors The selectors * * @return array */ protected function multiplySelectors($selectors) { // Find parent selectors $parentSelectors = $this->findClosestSelectors(); if (is_null($parentSelectors)) { // Kill parent reference in top level selector foreach ($selectors as &$s) { $this->expandParentSelectors($s, ""); } return $selectors; } $out = array(); foreach ($parentSelectors as $parent) { foreach ($selectors as $child) { $count = $this->expandParentSelectors($child, $parent); // Don't prepend the parent tag if & was used if ($count > 0) { $out[] = trim($child); } else { $out[] = trim($parent . ' ' . $child); } } } return $out; } /** * Reduces selector expressions * * @param array $selectors The selector expressions * * @return array */ protected function compileSelectors($selectors) { $out = array(); foreach ($selectors as $s) { if (is_array($s)) { list(, $value) = $s; $out[] = trim($this->compileValue($this->reduce($value))); } else { $out[] = $s; } } return $out; } /** * Equality check * * @param mixed $left Left operand * @param mixed $right Right operand * * @return boolean True if equal */ protected function eq($left, $right) { return $left == $right; } /** * Pattern match * * @param type $block X * @param type $callingArgs X * * @return boolean */ protected function patternMatch($block, $callingArgs) { /** * Match the guards if it has them * any one of the groups must have all its guards pass for a match */ if (!empty($block->guards)) { $groupPassed = false; foreach ($block->guards as $guardGroup) { foreach ($guardGroup as $guard) { $this->pushEnv(); $this->zipSetArgs($block->args, $callingArgs); $negate = false; if ($guard[0] == "negate") { $guard = $guard[1]; $negate = true; } $passed = $this->reduce($guard) == self::$TRUE; if ($negate) { $passed = !$passed; } $this->popEnv(); if ($passed) { $groupPassed = true; } else { $groupPassed = false; break; } } if ($groupPassed) { break; } } if (!$groupPassed) { return false; } } $numCalling = count($callingArgs); if (empty($block->args)) { return $block->isVararg || $numCalling == 0; } // No args $i = -1; // Try to match by arity or by argument literal foreach ($block->args as $i => $arg) { switch ($arg[0]) { case "lit": if (empty($callingArgs[$i]) || !$this->eq($arg[1], $callingArgs[$i])) { return false; } break; case "arg": // No arg and no default value if (!isset($callingArgs[$i]) && !isset($arg[2])) { return false; } break; case "rest": // Rest can be empty $i--; break 2; } } if ($block->isVararg) { // Not having enough is handled above return true; } else { $numMatched = $i + 1; // Greater than becuase default values always match return $numMatched >= $numCalling; } } /** * Pattern match all * * @param type $blocks X * @param type $callingArgs X * * @return type */ protected function patternMatchAll($blocks, $callingArgs) { $matches = null; foreach ($blocks as $block) { if ($this->patternMatch($block, $callingArgs)) { $matches[] = $block; } } return $matches; } /** * Attempt to find blocks matched by path and args * * @param array $searchIn Block to search in * @param string $path The path to search for * @param array $args Arguments * @param array $seen Your guess is as good as mine; that's third party code * * @return null */ protected function findBlocks($searchIn, $path, $args, $seen = array()) { if ($searchIn == null) { return null; } if (isset($seen[$searchIn->id])) { return null; } $seen[$searchIn->id] = true; $name = $path[0]; if (isset($searchIn->children[$name])) { $blocks = $searchIn->children[$name]; if (count($path) == 1) { $matches = $this->patternMatchAll($blocks, $args); if (!empty($matches)) { // This will return all blocks that match in the closest // scope that has any matching block, like lessjs return $matches; } } else { $matches = array(); foreach ($blocks as $subBlock) { $subMatches = $this->findBlocks($subBlock, array_slice($path, 1), $args, $seen); if (!is_null($subMatches)) { foreach ($subMatches as $sm) { $matches[] = $sm; } } } return count($matches) > 0 ? $matches : null; } } if ($searchIn->parent === $searchIn) { return null; } return $this->findBlocks($searchIn->parent, $path, $args, $seen); } /** * Sets all argument names in $args to either the default value * or the one passed in through $values * * @param array $args Arguments * @param array $values Values * * @return void */ protected function zipSetArgs($args, $values) { $i = 0; $assignedValues = array(); foreach ($args as $a) { if ($a[0] == "arg") { if ($i < count($values) && !is_null($values[$i])) { $value = $values[$i]; } elseif (isset($a[2])) { $value = $a[2]; } else { $value = null; } $value = $this->reduce($value); $this->set($a[1], $value); $assignedValues[] = $value; } $i++; } // Check for a rest $last = end($args); if ($last[0] == "rest") { $rest = array_slice($values, count($args) - 1); $this->set($last[1], $this->reduce(array("list", " ", $rest))); } $this->env->arguments = $assignedValues; } /** * Compile a prop and update $lines or $blocks appropriately * * @param array $prop Prop * @param stdClass $block Block * @param string $out Out * * @return void */ protected function compileProp($prop, $block, $out) { // Set error position context $this->sourceLoc = isset($prop[-1]) ? $prop[-1] : -1; switch ($prop[0]) { case 'assign': list(, $name, $value) = $prop; if ($name[0] == $this->vPrefix) { $this->set($name, $value); } else { $out->lines[] = $this->formatter->property($name, $this->compileValue($this->reduce($value))); } break; case 'block': list(, $child) = $prop; $this->compileBlock($child); break; case 'mixin': list(, $path, $args, $suffix) = $prop; $args = array_map(array($this, "reduce"), (array) $args); $mixins = $this->findBlocks($block, $path, $args); if ($mixins === null) { // Throw error here?? break; } foreach ($mixins as $mixin) { $haveScope = false; if (isset($mixin->parent->scope)) { $haveScope = true; $mixinParentEnv = $this->pushEnv(); $mixinParentEnv->storeParent = $mixin->parent->scope; } $haveArgs = false; if (isset($mixin->args)) { $haveArgs = true; $this->pushEnv(); $this->zipSetArgs($mixin->args, $args); } $oldParent = $mixin->parent; if ($mixin != $block) { $mixin->parent = $block; } foreach ($this->sortProps($mixin->props) as $subProp) { if ($suffix !== null && $subProp[0] == "assign" && is_string($subProp[1]) && $subProp[1]{0} != $this->vPrefix) { $subProp[2] = array( 'list', ' ', array($subProp[2], array('keyword', $suffix)) ); } $this->compileProp($subProp, $mixin, $out); } $mixin->parent = $oldParent; if ($haveArgs) { $this->popEnv(); } if ($haveScope) { $this->popEnv(); } } break; case 'raw': $out->lines[] = $prop[1]; break; case "directive": list(, $name, $value) = $prop; $out->lines[] = "@$name " . $this->compileValue($this->reduce($value)) . ';'; break; case "comment": $out->lines[] = $prop[1]; break; case "import"; list(, $importPath, $importId) = $prop; $importPath = $this->reduce($importPath); if (!isset($this->env->imports)) { $this->env->imports = array(); } $result = $this->tryImport($importPath, $block, $out); $this->env->imports[$importId] = $result === false ? array(false, "@import " . $this->compileValue($importPath) . ";") : $result; break; case "import_mixin": list(, $importId) = $prop; $import = $this->env->imports[$importId]; if ($import[0] === false) { $out->lines[] = $import[1]; } else { list(, $bottom, $parser, $importDir) = $import; $this->compileImportedProps($bottom, $block, $out, $parser, $importDir); } break; default: $this->throwError("unknown op: {$prop[0]}\n"); } } /** * Compiles a primitive value into a CSS property value. * * Values in lessphp are typed by being wrapped in arrays, their format is * typically: * * array(type, contents [, additional_contents]*) * * The input is expected to be reduced. This function will not work on * things like expressions and variables. * * @param array $value Value * * @return void */ protected function compileValue($value) { switch ($value[0]) { case 'list': // [1] - delimiter // [2] - array of values return implode($value[1], array_map(array($this, 'compileValue'), $value[2])); case 'raw_color': if (!empty($this->formatter->compressColors)) { return $this->compileValue($this->coerceColor($value)); } return $value[1]; case 'keyword': // [1] - the keyword return $value[1]; case 'number': // Format: [1] - the number -- [2] - the unit list(, $num, $unit) = $value; if ($this->numberPrecision !== null) { $num = round($num, $this->numberPrecision); } return $num . $unit; case 'string': // [1] - contents of string (includes quotes) list(, $delim, $content) = $value; foreach ($content as &$part) { if (is_array($part)) { $part = $this->compileValue($part); } } return $delim . implode($content) . $delim; case 'color': /** * Format: * * [1] - red component (either number or a %) * [2] - green component * [3] - blue component * [4] - optional alpha component */ list(, $r, $g, $b) = $value; $r = round($r); $g = round($g); $b = round($b); if (count($value) == 5 && $value[4] != 1) { // Return an rgba value return 'rgba(' . $r . ',' . $g . ',' . $b . ',' . $value[4] . ')'; } $h = sprintf("#%02x%02x%02x", $r, $g, $b); if (!empty($this->formatter->compressColors)) { // Converting hex color to short notation (e.g. #003399 to #039) if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) { $h = '#' . $h[1] . $h[3] . $h[5]; } } return $h; case 'function': list(, $name, $args) = $value; return $name . '(' . $this->compileValue($args) . ')'; default: // Assumed to be unit $this->throwError("unknown value type: $value[0]"); } } /** * Lib is number * * @param type $value X * * @return boolean */ protected function lib_isnumber($value) { return $this->toBool($value[0] == "number"); } /** * Lib is string * * @param type $value X * * @return boolean */ protected function lib_isstring($value) { return $this->toBool($value[0] == "string"); } /** * Lib is color * * @param type $value X * * @return boolean */ protected function lib_iscolor($value) { return $this->toBool($this->coerceColor($value)); } /** * Lib is keyword * * @param type $value X * * @return boolean */ protected function lib_iskeyword($value) { return $this->toBool($value[0] == "keyword"); } /** * Lib is pixel * * @param type $value X * * @return boolean */ protected function lib_ispixel($value) { return $this->toBool($value[0] == "number" && $value[2] == "px"); } /** * Lib is percentage * * @param type $value X * * @return boolean */ protected function lib_ispercentage($value) { return $this->toBool($value[0] == "number" && $value[2] == "%"); } /** * Lib is em * * @param type $value X * * @return boolean */ protected function lib_isem($value) { return $this->toBool($value[0] == "number" && $value[2] == "em"); } /** * Lib is rem * * @param type $value X * * @return boolean */ protected function lib_isrem($value) { return $this->toBool($value[0] == "number" && $value[2] == "rem"); } /** * LIb rgba hex * * @param type $color X * * @return boolean */ protected function lib_rgbahex($color) { $color = $this->coerceColor($color); if (is_null($color)) { $this->throwError("color expected for rgbahex"); } return sprintf("#%02x%02x%02x%02x", isset($color[4]) ? $color[4] * 255 : 255, $color[1], $color[2], $color[3]); } /** * Lib argb * * @param type $color X * * @return type */ protected function lib_argb($color) { return $this->lib_rgbahex($color); } /** * Utility func to unquote a string * * @param string $arg Arg * * @return string */ protected function lib_e($arg) { switch ($arg[0]) { case "list": $items = $arg[2]; if (isset($items[0])) { return $this->lib_e($items[0]); } return self::$defaultValue; case "string": $arg[1] = ""; return $arg; case "keyword": return $arg; default: return array("keyword", $this->compileValue($arg)); } } /** * Lib sprintf * * @param type $args X * * @return type */ protected function lib__sprintf($args) { if ($args[0] != "list") { return $args; } $values = $args[2]; $string = array_shift($values); $template = $this->compileValue($this->lib_e($string)); $i = 0; if (preg_match_all('/%[dsa]/', $template, $m)) { foreach ($m[0] as $match) { $val = isset($values[$i]) ? $this->reduce($values[$i]) : array('keyword', ''); // Lessjs compat, renders fully expanded color, not raw color if ($color = $this->coerceColor($val)) { $val = $color; } $i++; $rep = $this->compileValue($this->lib_e($val)); $template = preg_replace('/' . self::preg_quote($match) . '/', $rep, $template, 1); } } $d = $string[0] == "string" ? $string[1] : '"'; return array("string", $d, array($template)); } /** * Lib floor * * @param type $arg X * * @return array */ protected function lib_floor($arg) { $value = $this->assertNumber($arg); return array("number", floor($value), $arg[2]); } /** * Lib ceil * * @param type $arg X * * @return array */ protected function lib_ceil($arg) { $value = $this->assertNumber($arg); return array("number", ceil($value), $arg[2]); } /** * Lib round * * @param type $arg X * * @return array */ protected function lib_round($arg) { $value = $this->assertNumber($arg); return array("number", round($value), $arg[2]); } /** * Lib unit * * @param type $arg X * * @return array */ protected function lib_unit($arg) { if ($arg[0] == "list") { list($number, $newUnit) = $arg[2]; return array("number", $this->assertNumber($number), $this->compileValue($this->lib_e($newUnit))); } else { return array("number", $this->assertNumber($arg), ""); } } /** * Helper function to get arguments for color manipulation functions. * takes a list that contains a color like thing and a percentage * * @param array $args Args * * @return array */ protected function colorArgs($args) { if ($args[0] != 'list' || count($args[2]) < 2) { return array(array('color', 0, 0, 0), 0); } list($color, $delta) = $args[2]; $color = $this->assertColor($color); $delta = floatval($delta[1]); return array($color, $delta); } /** * Lib darken * * @param type $args X * * @return type */ protected function lib_darken($args) { list($color, $delta) = $this->colorArgs($args); $hsl = $this->toHSL($color); $hsl[3] = $this->clamp($hsl[3] - $delta, 100); return $this->toRGB($hsl); } /** * Lib lighten * * @param type $args X * * @return type */ protected function lib_lighten($args) { list($color, $delta) = $this->colorArgs($args); $hsl = $this->toHSL($color); $hsl[3] = $this->clamp($hsl[3] + $delta, 100); return $this->toRGB($hsl); } /** * Lib saturate * * @param type $args X * * @return type */ protected function lib_saturate($args) { list($color, $delta) = $this->colorArgs($args); $hsl = $this->toHSL($color); $hsl[2] = $this->clamp($hsl[2] + $delta, 100); return $this->toRGB($hsl); } /** * Lib desaturate * * @param type $args X * * @return type */ protected function lib_desaturate($args) { list($color, $delta) = $this->colorArgs($args); $hsl = $this->toHSL($color); $hsl[2] = $this->clamp($hsl[2] - $delta, 100); return $this->toRGB($hsl); } /** * Lib spin * * @param type $args X * * @return type */ protected function lib_spin($args) { list($color, $delta) = $this->colorArgs($args); $hsl = $this->toHSL($color); $hsl[1] = $hsl[1] + $delta % 360; if ($hsl[1] < 0) { $hsl[1] += 360; } return $this->toRGB($hsl); } /** * Lib fadeout * * @param type $args X * * @return type */ protected function lib_fadeout($args) { list($color, $delta) = $this->colorArgs($args); $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta / 100); return $color; } /** * Lib fadein * * @param type $args X * * @return type */ protected function lib_fadein($args) { list($color, $delta) = $this->colorArgs($args); $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta / 100); return $color; } /** * Lib hue * * @param type $color X * * @return type */ protected function lib_hue($color) { $hsl = $this->toHSL($this->assertColor($color)); return round($hsl[1]); } /** * Lib saturation * * @param type $color X * * @return type */ protected function lib_saturation($color) { $hsl = $this->toHSL($this->assertColor($color)); return round($hsl[2]); } /** * Lib lightness * * @param type $color X * * @return type */ protected function lib_lightness($color) { $hsl = $this->toHSL($this->assertColor($color)); return round($hsl[3]); } /** * Get the alpha of a color * Defaults to 1 for non-colors or colors without an alpha * * @param string $value Value * * @return string */ protected function lib_alpha($value) { if (!is_null($color = $this->coerceColor($value))) { return isset($color[4]) ? $color[4] : 1; } } /** * Set the alpha of the color * * @param array $args Args * * @return string */ protected function lib_fade($args) { list($color, $alpha) = $this->colorArgs($args); $color[4] = $this->clamp($alpha / 100.0); return $color; } /** * Third party code; your guess is as good as mine * * @param array $arg Arg * * @return string */ protected function lib_percentage($arg) { $num = $this->assertNumber($arg); return array("number", $num * 100, "%"); } /** * mixes two colors by weight * mix(@color1, @color2, @weight); * http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method * * @param array $args Args * * @return string */ protected function lib_mix($args) { if ($args[0] != "list" || count($args[2]) < 3) { $this->throwError("mix expects (color1, color2, weight)"); } list($first, $second, $weight) = $args[2]; $first = $this->assertColor($first); $second = $this->assertColor($second); $first_a = $this->lib_alpha($first); $second_a = $this->lib_alpha($second); $weight = $weight[1] / 100.0; $w = $weight * 2 - 1; $a = $first_a - $second_a; $w1 = (($w * $a == -1 ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2.0; $w2 = 1.0 - $w1; $new = array('color', $w1 * $first[1] + $w2 * $second[1], $w1 * $first[2] + $w2 * $second[2], $w1 * $first[3] + $w2 * $second[3], ); if ($first_a != 1.0 || $second_a != 1.0) { $new[] = $first_a * $weight + $second_a * ($weight - 1); } return $this->fixColor($new); } /** * Third party code; your guess is as good as mine * * @param array $arg Arg * * @return string */ protected function lib_contrast($args) { if ($args[0] != 'list' || count($args[2]) < 3) { return array(array('color', 0, 0, 0), 0); } list($inputColor, $darkColor, $lightColor) = $args[2]; $inputColor = $this->assertColor($inputColor); $darkColor = $this->assertColor($darkColor); $lightColor = $this->assertColor($lightColor); $hsl = $this->toHSL($inputColor); if ($hsl[3] > 50) { return $darkColor; } return $lightColor; } /** * Assert color * * @param type $value X * @param type $error X * * @return type */ protected function assertColor($value, $error = "expected color value") { $color = $this->coerceColor($value); if (is_null($color)) { $this->throwError($error); } return $color; } /** * Assert number * * @param type $value X * @param type $error X * * @return type */ protected function assertNumber($value, $error = "expecting number") { if ($value[0] == "number") { return $value[1]; } $this->throwError($error); } /** * To HSL * * @param type $color X * * @return type */ protected function toHSL($color) { if ($color[0] == 'hsl') { return $color; } $r = $color[1] / 255; $g = $color[2] / 255; $b = $color[3] / 255; $min = min($r, $g, $b); $max = max($r, $g, $b); $L = ($min + $max) / 2; if ($min == $max) { $S = $H = 0; } else { if ($L < 0.5) { $S = ($max - $min) / ($max + $min); } else { $S = ($max - $min) / (2.0 - $max - $min); } if ($r == $max) { $H = ($g - $b) / ($max - $min); } elseif ($g == $max) { $H = 2.0 + ($b - $r) / ($max - $min); } elseif ($b == $max) { $H = 4.0 + ($r - $g) / ($max - $min); } } $out = array('hsl', ($H < 0 ? $H + 6 : $H) * 60, $S * 100, $L * 100, ); if (count($color) > 4) { // Copy alpha $out[] = $color[4]; } return $out; } /** * To RGB helper * * @param type $comp X * @param type $temp1 X * @param type $temp2 X * * @return type */ protected function toRGB_helper($comp, $temp1, $temp2) { if ($comp < 0) { $comp += 1.0; } elseif ($comp > 1) { $comp -= 1.0; } if (6 * $comp < 1) { return $temp1 + ($temp2 - $temp1) * 6 * $comp; } if (2 * $comp < 1) { return $temp2; } if (3 * $comp < 2) { return $temp1 + ($temp2 - $temp1) * ((2 / 3) - $comp) * 6; } return $temp1; } /** * Converts a hsl array into a color value in rgb. * Expects H to be in range of 0 to 360, S and L in 0 to 100 * * @param type $color X * * @return type */ protected function toRGB($color) { if ($color == 'color') { return $color; } $H = $color[1] / 360; $S = $color[2] / 100; $L = $color[3] / 100; if ($S == 0) { $r = $g = $b = $L; } else { $temp2 = $L < 0.5 ? $L * (1.0 + $S) : $L + $S - $L * $S; $temp1 = 2.0 * $L - $temp2; $r = $this->toRGB_helper($H + 1 / 3, $temp1, $temp2); $g = $this->toRGB_helper($H, $temp1, $temp2); $b = $this->toRGB_helper($H - 1 / 3, $temp1, $temp2); } // $out = array('color', round($r*255), round($g*255), round($b*255)); $out = array('color', $r * 255, $g * 255, $b * 255); if (count($color) > 4) { // Copy alpha $out[] = $color[4]; } return $out; } /** * Clamp * * @param type $v X * @param type $max X * @param type $min X * * @return type */ protected function clamp($v, $max = 1, $min = 0) { return min($max, max($min, $v)); } /** * Convert the rgb, rgba, hsl color literals of function type * as returned by the parser into values of color type. * * @param type $func X * * @return type */ protected function funcToColor($func) { $fname = $func[1]; if ($func[2][0] != 'list') { // Need a list of arguments return false; } $rawComponents = $func[2][2]; if ($fname == 'hsl' || $fname == 'hsla') { $hsl = array('hsl'); $i = 0; foreach ($rawComponents as $c) { $val = $this->reduce($c); $val = isset($val[1]) ? floatval($val[1]) : 0; if ($i == 0) { $clamp = 360; } elseif ($i < 3) { $clamp = 100; } else { $clamp = 1; } $hsl[] = $this->clamp($val, $clamp); $i++; } while (count($hsl) < 4) { $hsl[] = 0; } return $this->toRGB($hsl); } elseif ($fname == 'rgb' || $fname == 'rgba') { $components = array(); $i = 1; foreach ($rawComponents as $c) { $c = $this->reduce($c); if ($i < 4) { if ($c[0] == "number" && $c[2] == "%") { $components[] = 255 * ($c[1] / 100); } else { $components[] = floatval($c[1]); } } elseif ($i == 4) { if ($c[0] == "number" && $c[2] == "%") { $components[] = 1.0 * ($c[1] / 100); } else { $components[] = floatval($c[1]); } } else { break; } $i++; } while (count($components) < 3) { $components[] = 0; } array_unshift($components, 'color'); return $this->fixColor($components); } return false; } /** * Reduce * * @param type $value X * @param type $forExpression X * * @return type */ protected function reduce($value, $forExpression = false) { switch ($value[0]) { case "interpolate": $reduced = $this->reduce($value[1]); $var = $this->compileValue($reduced); $res = $this->reduce(array("variable", $this->vPrefix . $var)); if (empty($value[2])) { $res = $this->lib_e($res); } return $res; case "variable": $key = $value[1]; if (is_array($key)) { $key = $this->reduce($key); $key = $this->vPrefix . $this->compileValue($this->lib_e($key)); } $seen = & $this->env->seenNames; if (!empty($seen[$key])) { $this->throwError("infinite loop detected: $key"); } $seen[$key] = true; $out = $this->reduce($this->get($key, self::$defaultValue)); $seen[$key] = false; return $out; case "list": foreach ($value[2] as &$item) { $item = $this->reduce($item, $forExpression); } return $value; case "expression": return $this->evaluate($value); case "string": foreach ($value[2] as &$part) { if (is_array($part)) { $strip = $part[0] == "variable"; $part = $this->reduce($part); if ($strip) { $part = $this->lib_e($part); } } } return $value; case "escape": list(, $inner) = $value; return $this->lib_e($this->reduce($inner)); case "function": $color = $this->funcToColor($value); if ($color) { return $color; } list(, $name, $args) = $value; if ($name == "%") { $name = "_sprintf"; } $f = isset($this->libFunctions[$name]) ? $this->libFunctions[$name] : array($this, 'lib_' . $name); if (is_callable($f)) { if ($args[0] == 'list') { $args = self::compressList($args[2], $args[1]); } $ret = call_user_func($f, $this->reduce($args, true), $this); if (is_null($ret)) { return array("string", "", array( $name, "(", $args, ")" )); } // Convert to a typed value if the result is a php primitive if (is_numeric($ret)) { $ret = array('number', $ret, ""); } elseif (!is_array($ret)) { $ret = array('keyword', $ret); } return $ret; } // Plain function, reduce args $value[2] = $this->reduce($value[2]); return $value; case "unary": list(, $op, $exp) = $value; $exp = $this->reduce($exp); if ($exp[0] == "number") { switch ($op) { case "+": return $exp; case "-": $exp[1] *= -1; return $exp; } } return array("string", "", array($op, $exp)); } if ($forExpression) { switch ($value[0]) { case "keyword": if ($color = $this->coerceColor($value)) { return $color; } break; case "raw_color": return $this->coerceColor($value); } } return $value; } /** * Coerce a value for use in color operation * * @param type $value X * * @return null */ protected function coerceColor($value) { switch ($value[0]) { case 'color': return $value; case 'raw_color': $c = array("color", 0, 0, 0); $colorStr = substr($value[1], 1); $num = hexdec($colorStr); $width = strlen($colorStr) == 3 ? 16 : 256; for ($i = 3; $i > 0; $i--) { // It's 3 2 1 $t = $num % $width; $num /= $width; $c[$i] = $t * (256 / $width) + $t * floor(16 / $width); } return $c; case 'keyword': $name = $value[1]; if (isset(self::$cssColors[$name])) { $rgba = explode(',', self::$cssColors[$name]); if (isset($rgba[3])) { return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]); } return array('color', $rgba[0], $rgba[1], $rgba[2]); } return null; } } /** * Make something string like into a string * * @param type $value X * * @return null */ protected function coerceString($value) { switch ($value[0]) { case "string": return $value; case "keyword": return array("string", "", array($value[1])); } return null; } /** * Turn list of length 1 into value type * * @param type $value X * * @return type */ protected function flattenList($value) { if ($value[0] == "list" && count($value[2]) == 1) { return $this->flattenList($value[2][0]); } return $value; } /** * To bool * * @param type $a X * * @return type */ protected function toBool($a) { if ($a) { return self::$TRUE; } else { return self::$FALSE; } } /** * Evaluate an expression * * @param type $exp X * * @return type */ protected function evaluate($exp) { list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp; $left = $this->reduce($left, true); $right = $this->reduce($right, true); if ($leftColor = $this->coerceColor($left)) { $left = $leftColor; } if ($rightColor = $this->coerceColor($right)) { $right = $rightColor; } $ltype = $left[0]; $rtype = $right[0]; // Operators that work on all types if ($op == "and") { return $this->toBool($left == self::$TRUE && $right == self::$TRUE); } if ($op == "=") { return $this->toBool($this->eq($left, $right)); } if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) { return $str; } // Type based operators $fname = "op_${ltype}_${rtype}"; if (is_callable(array($this, $fname))) { $out = $this->$fname($op, $left, $right); if (!is_null($out)) { return $out; } } // Make the expression look it did before being parsed $paddedOp = $op; if ($whiteBefore) { $paddedOp = " " . $paddedOp; } if ($whiteAfter) { $paddedOp .= " "; } return array("string", "", array($left, $paddedOp, $right)); } /** * String concatenate * * @param type $left X * @param string $right X * * @return string */ protected function stringConcatenate($left, $right) { if ($strLeft = $this->coerceString($left)) { if ($right[0] == "string") { $right[1] = ""; } $strLeft[2][] = $right; return $strLeft; } if ($strRight = $this->coerceString($right)) { array_unshift($strRight[2], $left); return $strRight; } } /** * Make sure a color's components don't go out of bounds * * @param type $c X * * @return int */ protected function fixColor($c) { foreach (range(1, 3) as $i) { if ($c[$i] < 0) { $c[$i] = 0; } if ($c[$i] > 255) { $c[$i] = 255; } } return $c; } /** * Op number color * * @param type $op X * @param type $lft X * @param type $rgt X * * @return type */ protected function op_number_color($op, $lft, $rgt) { if ($op == '+' || $op == '*') { return $this->op_color_number($op, $rgt, $lft); } } /** * Op color number * * @param type $op X * @param type $lft X * @param int $rgt X * * @return type */ protected function op_color_number($op, $lft, $rgt) { if ($rgt[0] == '%') { $rgt[1] /= 100; } return $this->op_color_color($op, $lft, array_fill(1, count($lft) - 1, $rgt[1])); } /** * Op color color * * @param type $op X * @param type $left X * @param type $right X * * @return type */ protected function op_color_color($op, $left, $right) { $out = array('color'); $max = count($left) > count($right) ? count($left) : count($right); foreach (range(1, $max - 1) as $i) { $lval = isset($left[$i]) ? $left[$i] : 0; $rval = isset($right[$i]) ? $right[$i] : 0; switch ($op) { case '+': $out[] = $lval + $rval; break; case '-': $out[] = $lval - $rval; break; case '*': $out[] = $lval * $rval; break; case '%': $out[] = $lval % $rval; break; case '/': if ($rval == 0) { $this->throwError("evaluate error: can't divide by zero"); } $out[] = $lval / $rval; break; default: $this->throwError('evaluate error: color op number failed on op ' . $op); } } return $this->fixColor($out); } /** * Lib red * * @param type $color X * * @return type */ public function lib_red($color) { $color = $this->coerceColor($color); if (is_null($color)) { $this->throwError('color expected for red()'); } return $color[1]; } /** * Lib green * * @param type $color X * * @return type */ public function lib_green($color) { $color = $this->coerceColor($color); if (is_null($color)) { $this->throwError('color expected for green()'); } return $color[2]; } /** * Lib blue * * @param type $color X * * @return type */ public function lib_blue($color) { $color = $this->coerceColor($color); if (is_null($color)) { $this->throwError('color expected for blue()'); } return $color[3]; } /** * Operator on two numbers * * @param type $op X * @param type $left X * @param type $right X * * @return type */ protected function op_number_number($op, $left, $right) { $unit = empty($left[2]) ? $right[2] : $left[2]; $value = 0; switch ($op) { case '+': $value = $left[1] + $right[1]; break; case '*': $value = $left[1] * $right[1]; break; case '-': $value = $left[1] - $right[1]; break; case '%': $value = $left[1] % $right[1]; break; case '/': if ($right[1] == 0) { $this->throwError('parse error: divide by zero'); } $value = $left[1] / $right[1]; break; case '<': return $this->toBool($left[1] < $right[1]); case '>': return $this->toBool($left[1] > $right[1]); case '>=': return $this->toBool($left[1] >= $right[1]); case '=<': return $this->toBool($left[1] <= $right[1]); default: $this->throwError('parse error: unknown number operator: ' . $op); } return array("number", $value, $unit); } /** * Make output block * * @param type $type X * @param type $selectors X * * @return stdclass */ protected function makeOutputBlock($type, $selectors = null) { $b = new stdclass; $b->lines = array(); $b->children = array(); $b->selectors = $selectors; $b->type = $type; $b->parent = $this->scope; return $b; } /** * The state of execution * * @param type $block X * * @return stdclass */ protected function pushEnv($block = null) { $e = new stdclass; $e->parent = $this->env; $e->store = array(); $e->block = $block; $this->env = $e; return $e; } /** * Pop something off the stack * * @return type */ protected function popEnv() { $old = $this->env; $this->env = $this->env->parent; return $old; } /** * Set something in the current env * * @param type $name X * @param type $value X * * @return void */ protected function set($name, $value) { $this->env->store[$name] = $value; } /** * Get the highest occurrence entry for a name * * @param type $name X * @param type $default X * * @return type */ protected function get($name, $default = null) { $current = $this->env; $isArguments = $name == $this->vPrefix . 'arguments'; while ($current) { if ($isArguments && isset($current->arguments)) { return array('list', ' ', $current->arguments); } if (isset($current->store[$name])) { return $current->store[$name]; } else { $current = isset($current->storeParent) ? $current->storeParent : $current->parent; } } return $default; } /** * Inject array of unparsed strings into environment as variables * * @param type $args X * * @return void * * @throws Exception */ protected function injectVariables($args) { $this->pushEnv(); /** FOF -- BEGIN CHANGE * */ $parser = new FOFLessParser($this, __METHOD__); /** FOF -- END CHANGE * */ foreach ($args as $name => $strValue) { if ($name{0} != '@') { $name = '@' . $name; } $parser->count = 0; $parser->buffer = (string) $strValue; if (!$parser->propertyValue($value)) { throw new Exception("failed to parse passed in variable $name: $strValue"); } $this->set($name, $value); } } /** * Initialize any static state, can initialize parser for a file * * @param type $fname X */ public function __construct($fname = null) { if ($fname !== null) { // Used for deprecated parse method $this->_parseFile = $fname; } } /** * Compile * * @param type $string X * @param type $name X * * @return type */ public function compile($string, $name = null) { $locale = setlocale(LC_NUMERIC, 0); setlocale(LC_NUMERIC, "C"); $this->parser = $this->makeParser($name); $root = $this->parser->parse($string); $this->env = null; $this->scope = null; $this->formatter = $this->newFormatter(); if (!empty($this->registeredVars)) { $this->injectVariables($this->registeredVars); } // Used for error messages $this->sourceParser = $this->parser; $this->compileBlock($root); ob_start(); $this->formatter->block($this->scope); $out = ob_get_clean(); setlocale(LC_NUMERIC, $locale); return $out; } /** * Compile file * * @param type $fname X * @param type $outFname X * * @return type * * @throws Exception */ public function compileFile($fname, $outFname = null) { if (!is_readable($fname)) { throw new Exception('load error: failed to find ' . $fname); } $pi = pathinfo($fname); $oldImport = $this->importDir; $this->importDir = (array) $this->importDir; $this->importDir[] = $pi['dirname'] . '/'; $this->allParsedFiles = array(); $this->addParsedFile($fname); $out = $this->compile(file_get_contents($fname), $fname); $this->importDir = $oldImport; if ($outFname !== null) { /** FOF - BEGIN CHANGE * */ return FOFPlatform::getInstance()->getIntegrationObject('filesystem')->fileWrite($outFname, $out); /** FOF - END CHANGE * */ } return $out; } /** * Compile only if changed input has changed or output doesn't exist * * @param type $in X * @param type $out X * * @return boolean */ public function checkedCompile($in, $out) { if (!is_file($out) || filemtime($in) > filemtime($out)) { $this->compileFile($in, $out); return true; } return false; } /** * Execute lessphp on a .less file or a lessphp cache structure * * The lessphp cache structure contains information about a specific * less file having been parsed. It can be used as a hint for future * calls to determine whether or not a rebuild is required. * * The cache structure contains two important keys that may be used * externally: * * compiled: The final compiled CSS * updated: The time (in seconds) the CSS was last compiled * * The cache structure is a plain-ol' PHP associative array and can * be serialized and unserialized without a hitch. * * @param mixed $in Input * @param bool $force Force rebuild? * * @return array lessphp cache structure */ public function cachedCompile($in, $force = false) { // Assume no root $root = null; if (is_string($in)) { $root = $in; } elseif (is_array($in) and isset($in['root'])) { if ($force or !isset($in['files'])) { /** * If we are forcing a recompile or if for some reason the * structure does not contain any file information we should * specify the root to trigger a rebuild. */ $root = $in['root']; } elseif (isset($in['files']) and is_array($in['files'])) { foreach ($in['files'] as $fname => $ftime) { if (!file_exists($fname) or filemtime($fname) > $ftime) { /** * One of the files we knew about previously has changed * so we should look at our incoming root again. */ $root = $in['root']; break; } } } } else { /** * TODO: Throw an exception? We got neither a string nor something * that looks like a compatible lessphp cache structure. */ return null; } if ($root !== null) { // If we have a root value which means we should rebuild. $out = array(); $out['root'] = $root; $out['compiled'] = $this->compileFile($root); $out['files'] = $this->allParsedFiles(); $out['updated'] = time(); return $out; } else { // No changes, pass back the structure // we were given initially. return $in; } } // // This is deprecated /** * Parse and compile buffer * * @param null $str X * @param type $initialVariables X * * @return type * * @throws Exception * * @deprecated 2.0 */ public function parse($str = null, $initialVariables = null) { if (is_array($str)) { $initialVariables = $str; $str = null; } $oldVars = $this->registeredVars; if ($initialVariables !== null) { $this->setVariables($initialVariables); } if ($str == null) { if (empty($this->_parseFile)) { throw new exception("nothing to parse"); } $out = $this->compileFile($this->_parseFile); } else { $out = $this->compile($str); } $this->registeredVars = $oldVars; return $out; } /** * Make parser * * @param type $name X * * @return FOFLessParser */ protected function makeParser($name) { /** FOF -- BEGIN CHANGE * */ $parser = new FOFLessParser($this, $name); /** FOF -- END CHANGE * */ $parser->writeComments = $this->preserveComments; return $parser; } /** * Set Formatter * * @param type $name X * * @return void */ public function setFormatter($name) { $this->formatterName = $name; } /** * New formatter * * @return FOFLessFormatterLessjs */ protected function newFormatter() { /** FOF -- BEGIN CHANGE * */ $className = "FOFLessFormatterLessjs"; /** FOF -- END CHANGE * */ if (!empty($this->formatterName)) { if (!is_string($this->formatterName)) return $this->formatterName; /** FOF -- BEGIN CHANGE * */ $className = "FOFLessFormatter" . ucfirst($this->formatterName); /** FOF -- END CHANGE * */ } return new $className; } /** * Set preserve comments * * @param type $preserve X * * @return void */ public function setPreserveComments($preserve) { $this->preserveComments = $preserve; } /** * Register function * * @param type $name X * @param type $func X * * @return void */ public function registerFunction($name, $func) { $this->libFunctions[$name] = $func; } /** * Unregister function * * @param type $name X * * @return void */ public function unregisterFunction($name) { unset($this->libFunctions[$name]); } /** * Set variables * * @param type $variables X * * @return void */ public function setVariables($variables) { $this->registeredVars = array_merge($this->registeredVars, $variables); } /** * Unset variable * * @param type $name X * * @return void */ public function unsetVariable($name) { unset($this->registeredVars[$name]); } /** * Set import dir * * @param type $dirs X * * @return void */ public function setImportDir($dirs) { $this->importDir = (array) $dirs; } /** * Add import dir * * @param type $dir X * * @return void */ public function addImportDir($dir) { $this->importDir = (array) $this->importDir; $this->importDir[] = $dir; } /** * All parsed files * * @return type */ public function allParsedFiles() { return $this->allParsedFiles; } /** * Add parsed file * * @param type $file X * * @return void */ protected function addParsedFile($file) { $this->allParsedFiles[realpath($file)] = filemtime($file); } /** * Uses the current value of $this->count to show line and line number * * @param type $msg X * * @return void */ protected function throwError($msg = null) { if ($this->sourceLoc >= 0) { $this->sourceParser->throwError($msg, $this->sourceLoc); } throw new exception($msg); } /** * Compile file $in to file $out if $in is newer than $out * Returns true when it compiles, false otherwise * * @param type $in X * @param type $out X * @param self $less X * * @return type */ public static function ccompile($in, $out, $less = null) { if ($less === null) { $less = new self; } return $less->checkedCompile($in, $out); } /** * Compile execute * * @param type $in X * @param type $force X * @param self $less X * * @return type */ public static function cexecute($in, $force = false, $less = null) { if ($less === null) { $less = new self; } return $less->cachedCompile($in, $force); } protected static $cssColors = array( 'aliceblue' => '240,248,255', 'antiquewhite' => '250,235,215', 'aqua' => '0,255,255', 'aquamarine' => '127,255,212', 'azure' => '240,255,255', 'beige' => '245,245,220', 'bisque' => '255,228,196', 'black' => '0,0,0', 'blanchedalmond' => '255,235,205', 'blue' => '0,0,255', 'blueviolet' => '138,43,226', 'brown' => '165,42,42', 'burlywood' => '222,184,135', 'cadetblue' => '95,158,160', 'chartreuse' => '127,255,0', 'chocolate' => '210,105,30', 'coral' => '255,127,80', 'cornflowerblue' => '100,149,237', 'cornsilk' => '255,248,220', 'crimson' => '220,20,60', 'cyan' => '0,255,255', 'darkblue' => '0,0,139', 'darkcyan' => '0,139,139', 'darkgoldenrod' => '184,134,11', 'darkgray' => '169,169,169', 'darkgreen' => '0,100,0', 'darkgrey' => '169,169,169', 'darkkhaki' => '189,183,107', 'darkmagenta' => '139,0,139', 'darkolivegreen' => '85,107,47', 'darkorange' => '255,140,0', 'darkorchid' => '153,50,204', 'darkred' => '139,0,0', 'darksalmon' => '233,150,122', 'darkseagreen' => '143,188,143', 'darkslateblue' => '72,61,139', 'darkslategray' => '47,79,79', 'darkslategrey' => '47,79,79', 'darkturquoise' => '0,206,209', 'darkviolet' => '148,0,211', 'deeppink' => '255,20,147', 'deepskyblue' => '0,191,255', 'dimgray' => '105,105,105', 'dimgrey' => '105,105,105', 'dodgerblue' => '30,144,255', 'firebrick' => '178,34,34', 'floralwhite' => '255,250,240', 'forestgreen' => '34,139,34', 'fuchsia' => '255,0,255', 'gainsboro' => '220,220,220', 'ghostwhite' => '248,248,255', 'gold' => '255,215,0', 'goldenrod' => '218,165,32', 'gray' => '128,128,128', 'green' => '0,128,0', 'greenyellow' => '173,255,47', 'grey' => '128,128,128', 'honeydew' => '240,255,240', 'hotpink' => '255,105,180', 'indianred' => '205,92,92', 'indigo' => '75,0,130', 'ivory' => '255,255,240', 'khaki' => '240,230,140', 'lavender' => '230,230,250', 'lavenderblush' => '255,240,245', 'lawngreen' => '124,252,0', 'lemonchiffon' => '255,250,205', 'lightblue' => '173,216,230', 'lightcoral' => '240,128,128', 'lightcyan' => '224,255,255', 'lightgoldenrodyellow' => '250,250,210', 'lightgray' => '211,211,211', 'lightgreen' => '144,238,144', 'lightgrey' => '211,211,211', 'lightpink' => '255,182,193', 'lightsalmon' => '255,160,122', 'lightseagreen' => '32,178,170', 'lightskyblue' => '135,206,250', 'lightslategray' => '119,136,153', 'lightslategrey' => '119,136,153', 'lightsteelblue' => '176,196,222', 'lightyellow' => '255,255,224', 'lime' => '0,255,0', 'limegreen' => '50,205,50', 'linen' => '250,240,230', 'magenta' => '255,0,255', 'maroon' => '128,0,0', 'mediumaquamarine' => '102,205,170', 'mediumblue' => '0,0,205', 'mediumorchid' => '186,85,211', 'mediumpurple' => '147,112,219', 'mediumseagreen' => '60,179,113', 'mediumslateblue' => '123,104,238', 'mediumspringgreen' => '0,250,154', 'mediumturquoise' => '72,209,204', 'mediumvioletred' => '199,21,133', 'midnightblue' => '25,25,112', 'mintcream' => '245,255,250', 'mistyrose' => '255,228,225', 'moccasin' => '255,228,181', 'navajowhite' => '255,222,173', 'navy' => '0,0,128', 'oldlace' => '253,245,230', 'olive' => '128,128,0', 'olivedrab' => '107,142,35', 'orange' => '255,165,0', 'orangered' => '255,69,0', 'orchid' => '218,112,214', 'palegoldenrod' => '238,232,170', 'palegreen' => '152,251,152', 'paleturquoise' => '175,238,238', 'palevioletred' => '219,112,147', 'papayawhip' => '255,239,213', 'peachpuff' => '255,218,185', 'peru' => '205,133,63', 'pink' => '255,192,203', 'plum' => '221,160,221', 'powderblue' => '176,224,230', 'purple' => '128,0,128', 'red' => '255,0,0', 'rosybrown' => '188,143,143', 'royalblue' => '65,105,225', 'saddlebrown' => '139,69,19', 'salmon' => '250,128,114', 'sandybrown' => '244,164,96', 'seagreen' => '46,139,87', 'seashell' => '255,245,238', 'sienna' => '160,82,45', 'silver' => '192,192,192', 'skyblue' => '135,206,235', 'slateblue' => '106,90,205', 'slategray' => '112,128,144', 'slategrey' => '112,128,144', 'snow' => '255,250,250', 'springgreen' => '0,255,127', 'steelblue' => '70,130,180', 'tan' => '210,180,140', 'teal' => '0,128,128', 'thistle' => '216,191,216', 'tomato' => '255,99,71', 'transparent' => '0,0,0,0', 'turquoise' => '64,224,208', 'violet' => '238,130,238', 'wheat' => '245,222,179', 'white' => '255,255,255', 'whitesmoke' => '245,245,245', 'yellow' => '255,255,0', 'yellowgreen' => '154,205,50' ); } PKY[k66fof/less/index.htmlnuW+APKY[Ҁefof/less/parser/parser.phpnuW+A * Licensed under MIT or GPLv3, see LICENSE * * Responsible for taking a string of LESS code and converting it into a syntax tree * * @since 2.0 */ class FOFLessParser { // Used to uniquely identify blocks protected static $nextBlockId = 0; protected static $precedence = array( '=<' => 0, '>=' => 0, '=' => 0, '<' => 0, '>' => 0, '+' => 1, '-' => 1, '*' => 2, '/' => 2, '%' => 2, ); protected static $whitePattern; protected static $commentMulti; protected static $commentSingle = "//"; protected static $commentMultiLeft = "/*"; protected static $commentMultiRight = "*/"; // Regex string to match any of the operators protected static $operatorString; // These properties will supress division unless it's inside parenthases protected static $supressDivisionProps = array('/border-radius$/i', '/^font$/i'); protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document"); protected $lineDirectives = array("charset"); /** * if we are in parens we can be more liberal with whitespace around * operators because it must evaluate to a single value and thus is less * ambiguous. * * Consider: * property1: 10 -5; // is two numbers, 10 and -5 * property2: (10 -5); // should evaluate to 5 */ protected $inParens = false; // Caches preg escaped literals protected static $literalCache = array(); /** * Constructor * * @param [type] $lessc [description] * @param string $sourceName [description] */ public function __construct($lessc, $sourceName = null) { $this->eatWhiteDefault = true; // Reference to less needed for vPrefix, mPrefix, and parentSelector $this->lessc = $lessc; // Name used for error messages $this->sourceName = $sourceName; $this->writeComments = false; if (!self::$operatorString) { self::$operatorString = '(' . implode('|', array_map(array('FOFLess', 'preg_quote'), array_keys(self::$precedence))) . ')'; $commentSingle = FOFLess::preg_quote(self::$commentSingle); $commentMultiLeft = FOFLess::preg_quote(self::$commentMultiLeft); $commentMultiRight = FOFLess::preg_quote(self::$commentMultiRight); self::$commentMulti = $commentMultiLeft . '.*?' . $commentMultiRight; self::$whitePattern = '/' . $commentSingle . '[^\n]*\s*|(' . self::$commentMulti . ')\s*|\s+/Ais'; } } /** * Parse text * * @param string $buffer [description] * * @return [type] [description] */ public function parse($buffer) { $this->count = 0; $this->line = 1; // Block stack $this->env = null; $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer); $this->pushSpecialBlock("root"); $this->eatWhiteDefault = true; $this->seenComments = array(); /* * trim whitespace on head * if (preg_match('/^\s+/', $this->buffer, $m)) { * $this->line += substr_count($m[0], "\n"); * $this->buffer = ltrim($this->buffer); * } */ $this->whitespace(); // Parse the entire file $lastCount = $this->count; while (false !== $this->parseChunk()); if ($this->count != strlen($this->buffer)) { $this->throwError(); } // TODO report where the block was opened if (!is_null($this->env->parent)) { throw new exception('parse error: unclosed block'); } return $this->env; } /** * Parse a single chunk off the head of the buffer and append it to the * current parse environment. * Returns false when the buffer is empty, or when there is an error. * * This function is called repeatedly until the entire document is * parsed. * * This parser is most similar to a recursive descent parser. Single * functions represent discrete grammatical rules for the language, and * they are able to capture the text that represents those rules. * * Consider the function lessc::keyword(). (all parse functions are * structured the same) * * The function takes a single reference argument. When calling the * function it will attempt to match a keyword on the head of the buffer. * If it is successful, it will place the keyword in the referenced * argument, advance the position in the buffer, and return true. If it * fails then it won't advance the buffer and it will return false. * * All of these parse functions are powered by lessc::match(), which behaves * the same way, but takes a literal regular expression. Sometimes it is * more convenient to use match instead of creating a new function. * * Because of the format of the functions, to parse an entire string of * grammatical rules, you can chain them together using &&. * * But, if some of the rules in the chain succeed before one fails, then * the buffer position will be left at an invalid state. In order to * avoid this, lessc::seek() is used to remember and set buffer positions. * * Before parsing a chain, use $s = $this->seek() to remember the current * position into $s. Then if a chain fails, use $this->seek($s) to * go back where we started. * * @return boolean */ protected function parseChunk() { if (empty($this->buffer)) { return false; } $s = $this->seek(); // Setting a property if ($this->keyword($key) && $this->assign() && $this->propertyValue($value, $key) && $this->end()) { $this->append(array('assign', $key, $value), $s); return true; } else { $this->seek($s); } // Look for special css blocks if ($this->literal('@', false)) { $this->count--; // Media if ($this->literal('@media')) { if (($this->mediaQueryList($mediaQueries) || true) && $this->literal('{')) { $media = $this->pushSpecialBlock("media"); $media->queries = is_null($mediaQueries) ? array() : $mediaQueries; return true; } else { $this->seek($s); return false; } } if ($this->literal("@", false) && $this->keyword($dirName)) { if ($this->isDirective($dirName, $this->blockDirectives)) { if (($this->openString("{", $dirValue, null, array(";")) || true) && $this->literal("{")) { $dir = $this->pushSpecialBlock("directive"); $dir->name = $dirName; if (isset($dirValue)) { $dir->value = $dirValue; } return true; } } elseif ($this->isDirective($dirName, $this->lineDirectives)) { if ($this->propertyValue($dirValue) && $this->end()) { $this->append(array("directive", $dirName, $dirValue)); return true; } } } $this->seek($s); } // Setting a variable if ($this->variable($var) && $this->assign() && $this->propertyValue($value) && $this->end()) { $this->append(array('assign', $var, $value), $s); return true; } else { $this->seek($s); } if ($this->import($importValue)) { $this->append($importValue, $s); return true; } // Opening parametric mixin if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) && ($this->guards($guards) || true) && $this->literal('{')) { $block = $this->pushBlock($this->fixTags(array($tag))); $block->args = $args; $block->isVararg = $isVararg; if (!empty($guards)) { $block->guards = $guards; } return true; } else { $this->seek($s); } // Opening a simple block if ($this->tags($tags) && $this->literal('{')) { $tags = $this->fixTags($tags); $this->pushBlock($tags); return true; } else { $this->seek($s); } // Closing a block if ($this->literal('}', false)) { try { $block = $this->pop(); } catch (exception $e) { $this->seek($s); $this->throwError($e->getMessage()); } $hidden = false; if (is_null($block->type)) { $hidden = true; if (!isset($block->args)) { foreach ($block->tags as $tag) { if (!is_string($tag) || $tag{0} != $this->lessc->mPrefix) { $hidden = false; break; } } } foreach ($block->tags as $tag) { if (is_string($tag)) { $this->env->children[$tag][] = $block; } } } if (!$hidden) { $this->append(array('block', $block), $s); } // This is done here so comments aren't bundled into he block that was just closed $this->whitespace(); return true; } // Mixin if ($this->mixinTags($tags) && ($this->argumentValues($argv) || true) && ($this->keyword($suffix) || true) && $this->end()) { $tags = $this->fixTags($tags); $this->append(array('mixin', $tags, $argv, $suffix), $s); return true; } else { $this->seek($s); } // Spare ; if ($this->literal(';')) { return true; } // Got nothing, throw error return false; } /** * [isDirective description] * * @param string $dirname [description] * @param [type] $directives [description] * * @return boolean */ protected function isDirective($dirname, $directives) { // TODO: cache pattern in parser $pattern = implode("|", array_map(array("FOFLess", "preg_quote"), $directives)); $pattern = '/^(-[a-z-]+-)?(' . $pattern . ')$/i'; return preg_match($pattern, $dirname); } /** * [fixTags description] * * @param [type] $tags [description] * * @return [type] [description] */ protected function fixTags($tags) { // Move @ tags out of variable namespace foreach ($tags as &$tag) { if ($tag{0} == $this->lessc->vPrefix) { $tag[0] = $this->lessc->mPrefix; } } return $tags; } /** * a list of expressions * * @param [type] &$exps [description] * * @return boolean */ protected function expressionList(&$exps) { $values = array(); while ($this->expression($exp)) { $values[] = $exp; } if (count($values) == 0) { return false; } $exps = FOFLess::compressList($values, ' '); return true; } /** * Attempt to consume an expression. * * @param string &$out [description] * * @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code * * @return boolean */ protected function expression(&$out) { if ($this->value($lhs)) { $out = $this->expHelper($lhs, 0); // Look for / shorthand if (!empty($this->env->supressedDivision)) { unset($this->env->supressedDivision); $s = $this->seek(); if ($this->literal("/") && $this->value($rhs)) { $out = array("list", "", array($out, array("keyword", "/"), $rhs)); } else { $this->seek($s); } } return true; } return false; } /** * Recursively parse infix equation with $lhs at precedence $minP * * @param type $lhs [description] * @param type $minP [description] * * @return string */ protected function expHelper($lhs, $minP) { $this->inExp = true; $ss = $this->seek(); while (true) { $whiteBefore = isset($this->buffer[$this->count - 1]) && ctype_space($this->buffer[$this->count - 1]); // If there is whitespace before the operator, then we require // whitespace after the operator for it to be an expression $needWhite = $whiteBefore && !$this->inParens; if ($this->match(self::$operatorString . ($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP) { if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision)) { foreach (self::$supressDivisionProps as $pattern) { if (preg_match($pattern, $this->env->currentProperty)) { $this->env->supressedDivision = true; break 2; } } } $whiteAfter = isset($this->buffer[$this->count - 1]) && ctype_space($this->buffer[$this->count - 1]); if (!$this->value($rhs)) { break; } // Peek for next operator to see what to do with rhs if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) { $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]); } $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter); $ss = $this->seek(); continue; } break; } $this->seek($ss); return $lhs; } /** * Consume a list of values for a property * * @param [type] &$value [description] * @param [type] $keyName [description] * * @return boolean */ public function propertyValue(&$value, $keyName = null) { $values = array(); if ($keyName !== null) { $this->env->currentProperty = $keyName; } $s = null; while ($this->expressionList($v)) { $values[] = $v; $s = $this->seek(); if (!$this->literal(',')) { break; } } if ($s) { $this->seek($s); } if ($keyName !== null) { unset($this->env->currentProperty); } if (count($values) == 0) { return false; } $value = FOFLess::compressList($values, ', '); return true; } /** * [parenValue description] * * @param [type] &$out [description] * * @return boolean */ protected function parenValue(&$out) { $s = $this->seek(); // Speed shortcut if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(") { return false; } $inParens = $this->inParens; if ($this->literal("(") && ($this->inParens = true) && $this->expression($exp) && $this->literal(")")) { $out = $exp; $this->inParens = $inParens; return true; } else { $this->inParens = $inParens; $this->seek($s); } return false; } /** * a single value * * @param [type] &$value [description] * * @return boolean */ protected function value(&$value) { $s = $this->seek(); // Speed shortcut if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-") { // Negation if ($this->literal("-", false) &&(($this->variable($inner) && $inner = array("variable", $inner)) || $this->unit($inner) || $this->parenValue($inner))) { $value = array("unary", "-", $inner); return true; } else { $this->seek($s); } } if ($this->parenValue($value)) { return true; } if ($this->unit($value)) { return true; } if ($this->color($value)) { return true; } if ($this->func($value)) { return true; } if ($this->string($value)) { return true; } if ($this->keyword($word)) { $value = array('keyword', $word); return true; } // Try a variable if ($this->variable($var)) { $value = array('variable', $var); return true; } // Unquote string (should this work on any type? if ($this->literal("~") && $this->string($str)) { $value = array("escape", $str); return true; } else { $this->seek($s); } // Css hack: \0 if ($this->literal('\\') && $this->match('([0-9]+)', $m)) { $value = array('keyword', '\\' . $m[1]); return true; } else { $this->seek($s); } return false; } /** * an import statement * * @param [type] &$out [description] * * @return boolean */ protected function import(&$out) { $s = $this->seek(); if (!$this->literal('@import')) { return false; } /* * @import "something.css" media; * @import url("something.css") media; * @import url(something.css) media; */ if ($this->propertyValue($value)) { $out = array("import", $value); return true; } } /** * [mediaQueryList description] * * @param [type] &$out [description] * * @return boolean */ protected function mediaQueryList(&$out) { if ($this->genericList($list, "mediaQuery", ",", false)) { $out = $list[2]; return true; } return false; } /** * [mediaQuery description] * * @param [type] &$out [description] * * @return [type] [description] */ protected function mediaQuery(&$out) { $s = $this->seek(); $expressions = null; $parts = array(); if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType)) { $prop = array("mediaType"); if (isset($only)) { $prop[] = "only"; } if (isset($not)) { $prop[] = "not"; } $prop[] = $mediaType; $parts[] = $prop; } else { $this->seek($s); } if (!empty($mediaType) && !$this->literal("and")) { // ~ } else { $this->genericList($expressions, "mediaExpression", "and", false); if (is_array($expressions)) { $parts = array_merge($parts, $expressions[2]); } } if (count($parts) == 0) { $this->seek($s); return false; } $out = $parts; return true; } /** * [mediaExpression description] * * @param [type] &$out [description] * * @return boolean */ protected function mediaExpression(&$out) { $s = $this->seek(); $value = null; if ($this->literal("(") && $this->keyword($feature) && ($this->literal(":") && $this->expression($value) || true) && $this->literal(")")) { $out = array("mediaExp", $feature); if ($value) { $out[] = $value; } return true; } elseif ($this->variable($variable)) { $out = array('variable', $variable); return true; } $this->seek($s); return false; } /** * An unbounded string stopped by $end * * @param [type] $end [description] * @param [type] &$out [description] * @param [type] $nestingOpen [description] * @param [type] $rejectStrs [description] * * @return boolean */ protected function openString($end, &$out, $nestingOpen = null, $rejectStrs = null) { $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; $stop = array("'", '"', "@{", $end); $stop = array_map(array("FOFLess", "preg_quote"), $stop); // $stop[] = self::$commentMulti; if (!is_null($rejectStrs)) { $stop = array_merge($stop, $rejectStrs); } $patt = '(.*?)(' . implode("|", $stop) . ')'; $nestingLevel = 0; $content = array(); while ($this->match($patt, $m, false)) { if (!empty($m[1])) { $content[] = $m[1]; if ($nestingOpen) { $nestingLevel += substr_count($m[1], $nestingOpen); } } $tok = $m[2]; $this->count -= strlen($tok); if ($tok == $end) { if ($nestingLevel == 0) { break; } else { $nestingLevel--; } } if (($tok == "'" || $tok == '"') && $this->string($str)) { $content[] = $str; continue; } if ($tok == "@{" && $this->interpolation($inter)) { $content[] = $inter; continue; } if (in_array($tok, $rejectStrs)) { $count = null; break; } $content[] = $tok; $this->count += strlen($tok); } $this->eatWhiteDefault = $oldWhite; if (count($content) == 0) return false; // Trim the end if (is_string(end($content))) { $content[count($content) - 1] = rtrim(end($content)); } $out = array("string", "", $content); return true; } /** * [string description] * * @param [type] &$out [description] * * @return boolean */ protected function string(&$out) { $s = $this->seek(); if ($this->literal('"', false)) { $delim = '"'; } elseif ($this->literal("'", false)) { $delim = "'"; } else { return false; } $content = array(); // Look for either ending delim , escape, or string interpolation $patt = '([^\n]*?)(@\{|\\\\|' . FOFLess::preg_quote($delim) . ')'; $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; while ($this->match($patt, $m, false)) { $content[] = $m[1]; if ($m[2] == "@{") { $this->count -= strlen($m[2]); if ($this->interpolation($inter, false)) { $content[] = $inter; } else { $this->count += strlen($m[2]); // Ignore it $content[] = "@{"; } } elseif ($m[2] == '\\') { $content[] = $m[2]; if ($this->literal($delim, false)) { $content[] = $delim; } } else { $this->count -= strlen($delim); // Delim break; } } $this->eatWhiteDefault = $oldWhite; if ($this->literal($delim)) { $out = array("string", $delim, $content); return true; } $this->seek($s); return false; } /** * [interpolation description] * * @param [type] &$out [description] * * @return boolean */ protected function interpolation(&$out) { $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = true; $s = $this->seek(); if ($this->literal("@{") && $this->openString("}", $interp, null, array("'", '"', ";")) && $this->literal("}", false)) { $out = array("interpolate", $interp); $this->eatWhiteDefault = $oldWhite; if ($this->eatWhiteDefault) { $this->whitespace(); } return true; } $this->eatWhiteDefault = $oldWhite; $this->seek($s); return false; } /** * [unit description] * * @param [type] &$unit [description] * * @return boolean */ protected function unit(&$unit) { // Speed shortcut if (isset($this->buffer[$this->count])) { $char = $this->buffer[$this->count]; if (!ctype_digit($char) && $char != ".") { return false; } } if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) { $unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]); return true; } return false; } /** * a # color * * @param [type] &$out [description] * * @return boolean */ protected function color(&$out) { if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) { if (strlen($m[1]) > 7) { $out = array("string", "", array($m[1])); } else { $out = array("raw_color", $m[1]); } return true; } return false; } /** * Consume a list of property values delimited by ; and wrapped in () * * @param [type] &$args [description] * @param [type] $delim [description] * * @return boolean */ protected function argumentValues(&$args, $delim = ',') { $s = $this->seek(); if (!$this->literal('(')) { return false; } $values = array(); while (true) { if ($this->expressionList($value)) { $values[] = $value; } if (!$this->literal($delim)) { break; } else { if ($value == null) { $values[] = null; } $value = null; } } if (!$this->literal(')')) { $this->seek($s); return false; } $args = $values; return true; } /** * Consume an argument definition list surrounded by () * each argument is a variable name with optional value * or at the end a ... or a variable named followed by ... * * @param [type] &$args [description] * @param [type] &$isVararg [description] * @param [type] $delim [description] * * @return boolean */ protected function argumentDef(&$args, &$isVararg, $delim = ',') { $s = $this->seek(); if (!$this->literal('(')) return false; $values = array(); $isVararg = false; while (true) { if ($this->literal("...")) { $isVararg = true; break; } if ($this->variable($vname)) { $arg = array("arg", $vname); $ss = $this->seek(); if ($this->assign() && $this->expressionList($value)) { $arg[] = $value; } else { $this->seek($ss); if ($this->literal("...")) { $arg[0] = "rest"; $isVararg = true; } } $values[] = $arg; if ($isVararg) { break; } continue; } if ($this->value($literal)) { $values[] = array("lit", $literal); } if (!$this->literal($delim)) { break; } } if (!$this->literal(')')) { $this->seek($s); return false; } $args = $values; return true; } /** * Consume a list of tags * This accepts a hanging delimiter * * @param [type] &$tags [description] * @param [type] $simple [description] * @param [type] $delim [description] * * @return boolean */ protected function tags(&$tags, $simple = false, $delim = ',') { $tags = array(); while ($this->tag($tt, $simple)) { $tags[] = $tt; if (!$this->literal($delim)) { break; } } if (count($tags) == 0) { return false; } return true; } /** * List of tags of specifying mixin path * Optionally separated by > (lazy, accepts extra >) * * @param [type] &$tags [description] * * @return boolean */ protected function mixinTags(&$tags) { $s = $this->seek(); $tags = array(); while ($this->tag($tt, true)) { $tags[] = $tt; $this->literal(">"); } if (count($tags) == 0) { return false; } return true; } /** * A bracketed value (contained within in a tag definition) * * @param [type] &$value [description] * * @return boolean */ protected function tagBracket(&$value) { // Speed shortcut if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") { return false; } $s = $this->seek(); if ($this->literal('[') && $this->to(']', $c, true) && $this->literal(']', false)) { $value = '[' . $c . ']'; // Whitespace? if ($this->whitespace()) { $value .= " "; } // Escape parent selector, (yuck) $value = str_replace($this->lessc->parentSelector, "$&$", $value); return true; } $this->seek($s); return false; } /** * [tagExpression description] * * @param [type] &$value [description] * * @return boolean */ protected function tagExpression(&$value) { $s = $this->seek(); if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) { $value = array('exp', $exp); return true; } $this->seek($s); return false; } /** * A single tag * * @param [type] &$tag [description] * @param boolean $simple [description] * * @return boolean */ protected function tag(&$tag, $simple = false) { if ($simple) { $chars = '^@,:;{}\][>\(\) "\''; } else { $chars = '^@,;{}["\''; } $s = $this->seek(); if (!$simple && $this->tagExpression($tag)) { return true; } $hasExpression = false; $parts = array(); while ($this->tagBracket($first)) { $parts[] = $first; } $oldWhite = $this->eatWhiteDefault; $this->eatWhiteDefault = false; while (true) { if ($this->match('([' . $chars . '0-9][' . $chars . ']*)', $m)) { $parts[] = $m[1]; if ($simple) { break; } while ($this->tagBracket($brack)) { $parts[] = $brack; } continue; } if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") { if ($this->interpolation($interp)) { $hasExpression = true; // Don't unescape $interp[2] = true; $parts[] = $interp; continue; } if ($this->literal("@")) { $parts[] = "@"; continue; } } // For keyframes if ($this->unit($unit)) { $parts[] = $unit[1]; $parts[] = $unit[2]; continue; } break; } $this->eatWhiteDefault = $oldWhite; if (!$parts) { $this->seek($s); return false; } if ($hasExpression) { $tag = array("exp", array("string", "", $parts)); } else { $tag = trim(implode($parts)); } $this->whitespace(); return true; } /** * A css function * * @param [type] &$func [description] * * @return boolean */ protected function func(&$func) { $s = $this->seek(); if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) { $fname = $m[1]; $sPreArgs = $this->seek(); $args = array(); while (true) { $ss = $this->seek(); // This ugly nonsense is for ie filter properties if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) { $args[] = array("string", "", array($name, "=", $value)); } else { $this->seek($ss); if ($this->expressionList($value)) { $args[] = $value; } } if (!$this->literal(',')) { break; } } $args = array('list', ',', $args); if ($this->literal(')')) { $func = array('function', $fname, $args); return true; } elseif ($fname == 'url') { // Couldn't parse and in url? treat as string $this->seek($sPreArgs); if ($this->openString(")", $string) && $this->literal(")")) { $func = array('function', $fname, $string); return true; } } } $this->seek($s); return false; } /** * Consume a less variable * * @param [type] &$name [description] * * @return boolean */ protected function variable(&$name) { $s = $this->seek(); if ($this->literal($this->lessc->vPrefix, false) && ($this->variable($sub) || $this->keyword($name))) { if (!empty($sub)) { $name = array('variable', $sub); } else { $name = $this->lessc->vPrefix . $name; } return true; } $name = null; $this->seek($s); return false; } /** * Consume an assignment operator * Can optionally take a name that will be set to the current property name * * @param string $name [description] * * @return boolean */ protected function assign($name = null) { if ($name) { $this->currentProperty = $name; } return $this->literal(':') || $this->literal('='); } /** * Consume a keyword * * @param [type] &$word [description] * * @return boolean */ protected function keyword(&$word) { if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) { $word = $m[1]; return true; } return false; } /** * Consume an end of statement delimiter * * @return boolean */ protected function end() { if ($this->literal(';')) { return true; } elseif ($this->count == strlen($this->buffer) || $this->buffer{$this->count} == '}') { // If there is end of file or a closing block next then we don't need a ; return true; } return false; } /** * [guards description] * * @param [type] &$guards [description] * * @return boolean */ protected function guards(&$guards) { $s = $this->seek(); if (!$this->literal("when")) { $this->seek($s); return false; } $guards = array(); while ($this->guardGroup($g)) { $guards[] = $g; if (!$this->literal(",")) { break; } } if (count($guards) == 0) { $guards = null; $this->seek($s); return false; } return true; } /** * A bunch of guards that are and'd together * * @param [type] &$guardGroup [description] * * @todo rename to guardGroup * * @return boolean */ protected function guardGroup(&$guardGroup) { $s = $this->seek(); $guardGroup = array(); while ($this->guard($guard)) { $guardGroup[] = $guard; if (!$this->literal("and")) { break; } } if (count($guardGroup) == 0) { $guardGroup = null; $this->seek($s); return false; } return true; } /** * [guard description] * * @param [type] &$guard [description] * * @return boolean */ protected function guard(&$guard) { $s = $this->seek(); $negate = $this->literal("not"); if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) { $guard = $exp; if ($negate) { $guard = array("negate", $guard); } return true; } $this->seek($s); return false; } /* raw parsing functions */ /** * [literal description] * * @param [type] $what [description] * @param [type] $eatWhitespace [description] * * @return boolean */ protected function literal($what, $eatWhitespace = null) { if ($eatWhitespace === null) { $eatWhitespace = $this->eatWhiteDefault; } // Shortcut on single letter if (!isset($what[1]) && isset($this->buffer[$this->count])) { if ($this->buffer[$this->count] == $what) { if (!$eatWhitespace) { $this->count++; return true; } } else { return false; } } if (!isset(self::$literalCache[$what])) { self::$literalCache[$what] = FOFLess::preg_quote($what); } return $this->match(self::$literalCache[$what], $m, $eatWhitespace); } /** * [genericList description] * * @param [type] &$out [description] * @param [type] $parseItem [description] * @param string $delim [description] * @param boolean $flatten [description] * * @return boolean */ protected function genericList(&$out, $parseItem, $delim = "", $flatten = true) { $s = $this->seek(); $items = array(); while ($this->$parseItem($value)) { $items[] = $value; if ($delim) { if (!$this->literal($delim)) { break; } } } if (count($items) == 0) { $this->seek($s); return false; } if ($flatten && count($items) == 1) { $out = $items[0]; } else { $out = array("list", $delim, $items); } return true; } /** * Advance counter to next occurrence of $what * $until - don't include $what in advance * $allowNewline, if string, will be used as valid char set * * @param [type] $what [description] * @param [type] &$out [description] * @param boolean $until [description] * @param boolean $allowNewline [description] * * @return boolean */ protected function to($what, &$out, $until = false, $allowNewline = false) { if (is_string($allowNewline)) { $validChars = $allowNewline; } else { $validChars = $allowNewline ? "." : "[^\n]"; } if (!$this->match('(' . $validChars . '*?)' . FOFLess::preg_quote($what), $m, !$until)) { return false; } if ($until) { // Give back $what $this->count -= strlen($what); } $out = $m[1]; return true; } /** * Try to match something on head of buffer * * @param [type] $regex [description] * @param [type] &$out [description] * @param [type] $eatWhitespace [description] * * @return boolean */ protected function match($regex, &$out, $eatWhitespace = null) { if ($eatWhitespace === null) { $eatWhitespace = $this->eatWhiteDefault; } $r = '/' . $regex . ($eatWhitespace && !$this->writeComments ? '\s*' : '') . '/Ais'; if (preg_match($r, $this->buffer, $out, null, $this->count)) { $this->count += strlen($out[0]); if ($eatWhitespace && $this->writeComments) { $this->whitespace(); } return true; } return false; } /** * Watch some whitespace * * @return boolean */ protected function whitespace() { if ($this->writeComments) { $gotWhite = false; while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) { if (isset($m[1]) && empty($this->commentsSeen[$this->count])) { $this->append(array("comment", $m[1])); $this->commentsSeen[$this->count] = true; } $this->count += strlen($m[0]); $gotWhite = true; } return $gotWhite; } else { $this->match("", $m); return strlen($m[0]) > 0; } } /** * Match something without consuming it * * @param [type] $regex [description] * @param [type] &$out [description] * @param [type] $from [description] * * @return boolean */ protected function peek($regex, &$out = null, $from = null) { if (is_null($from)) { $from = $this->count; } $r = '/' . $regex . '/Ais'; $result = preg_match($r, $this->buffer, $out, null, $from); return $result; } /** * Seek to a spot in the buffer or return where we are on no argument * * @param [type] $where [description] * * @return boolean */ protected function seek($where = null) { if ($where === null) { return $this->count; } else { $this->count = $where; } return true; } /* misc functions */ /** * [throwError description] * * @param string $msg [description] * @param [type] $count [description] * * @return void */ public function throwError($msg = "parse error", $count = null) { $count = is_null($count) ? $this->count : $count; $line = $this->line + substr_count(substr($this->buffer, 0, $count), "\n"); if (!empty($this->sourceName)) { $loc = "$this->sourceName on line $line"; } else { $loc = "line: $line"; } // TODO this depends on $this->count if ($this->peek("(.*?)(\n|$)", $m, $count)) { throw new exception("$msg: failed at `$m[1]` $loc"); } else { throw new exception("$msg: $loc"); } } /** * [pushBlock description] * * @param [type] $selectors [description] * @param [type] $type [description] * * @return stdClass */ protected function pushBlock($selectors = null, $type = null) { $b = new stdclass; $b->parent = $this->env; $b->type = $type; $b->id = self::$nextBlockId++; // TODO: kill me from here $b->isVararg = false; $b->tags = $selectors; $b->props = array(); $b->children = array(); $this->env = $b; return $b; } /** * Push a block that doesn't multiply tags * * @param [type] $type [description] * * @return stdClass */ protected function pushSpecialBlock($type) { return $this->pushBlock(null, $type); } /** * Append a property to the current block * * @param [type] $prop [description] * @param [type] $pos [description] * * @return void */ protected function append($prop, $pos = null) { if ($pos !== null) { $prop[-1] = $pos; } $this->env->props[] = $prop; } /** * Pop something off the stack * * @return [type] [description] */ protected function pop() { $old = $this->env; $this->env = $this->env->parent; return $old; } /** * Remove comments from $text * * @param [type] $text [description] * * @todo: make it work for all functions, not just url * * @return [type] [description] */ protected function removeComments($text) { $look = array( 'url(', '//', '/*', '"', "'" ); $out = ''; $min = null; while (true) { // Find the next item foreach ($look as $token) { $pos = strpos($text, $token); if ($pos !== false) { if (!isset($min) || $pos < $min[1]) { $min = array($token, $pos); } } } if (is_null($min)) break; $count = $min[1]; $skip = 0; $newlines = 0; switch ($min[0]) { case 'url(': if (preg_match('/url\(.*?\)/', $text, $m, 0, $count)) { $count += strlen($m[0]) - strlen($min[0]); } break; case '"': case "'": if (preg_match('/' . $min[0] . '.*?' . $min[0] . '/', $text, $m, 0, $count)) { $count += strlen($m[0]) - 1; } break; case '//': $skip = strpos($text, "\n", $count); if ($skip === false) { $skip = strlen($text) - $count; } else { $skip -= $count; } break; case '/*': if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) { $skip = strlen($m[0]); $newlines = substr_count($m[0], "\n"); } break; } if ($skip == 0) { $count += strlen($min[0]); } $out .= substr($text, 0, $count) . str_repeat("\n", $newlines); $text = substr($text, $count + $skip); $min = null; } return $out . $text; } } PKY[k66fof/less/parser/index.htmlnuW+APKY[Z;;fof/less/formatter/joomla.phpnuW+A * Licensed under MIT or GPLv3, see LICENSE * * @package FrameworkOnFramework * @since 2.1 */ class FOFLessFormatterJoomla extends FOFLessFormatterClassic { public $disableSingle = true; public $breakSelectors = true; public $assignSeparator = ": "; public $selectorSeparator = ","; public $indentChar = "\t"; } PKY[k66fof/less/formatter/index.htmlnuW+APKY[Y:?fof/less/formatter/lessjs.phpnuW+A * Licensed under MIT or GPLv3, see LICENSE * * @package FrameworkOnFramework * @since 2.0 */ class FOFLessFormatterLessjs extends FOFLessFormatterClassic { public $disableSingle = true; public $breakSelectors = true; public $assignSeparator = ": "; public $selectorSeparator = ","; } PKY[Bv`!fof/less/formatter/compressed.phpnuW+A * Licensed under MIT or GPLv3, see LICENSE * * @package FrameworkOnFramework * @since 2.0 */ class FOFLessFormatterCompressed extends FOFLessFormatterClassic { public $disableSingle = true; public $open = "{"; public $selectorSeparator = ","; public $assignSeparator = ":"; public $break = ""; public $compressColors = true; /** * Indent a string by $n positions * * @param integer $n How many positions to indent * * @return string The indented string */ public function indentStr($n = 0) { return ""; } } PKY[+[ V V fof/less/formatter/classic.phpnuW+A * Licensed under MIT or GPLv3, see LICENSE * * @package FrameworkOnFramework * @since 2.0 */ class FOFLessFormatterClassic { public $indentChar = " "; public $break = "\n"; public $open = " {"; public $close = "}"; public $selectorSeparator = ", "; public $assignSeparator = ":"; public $openSingle = " { "; public $closeSingle = " }"; public $disableSingle = false; public $breakSelectors = false; public $compressColors = false; /** * Public constructor */ public function __construct() { $this->indentLevel = 0; } /** * Indent a string by $n positions * * @param integer $n How many positions to indent * * @return string The indented string */ public function indentStr($n = 0) { return str_repeat($this->indentChar, max($this->indentLevel + $n, 0)); } /** * Return the code for a property * * @param string $name The name of the porperty * @param string $value The value of the porperty * * @return string The CSS code */ public function property($name, $value) { return $name . $this->assignSeparator . $value . ";"; } /** * Is a block empty? * * @param stdClass $block The block to check * * @return boolean True if the block has no lines or children */ protected function isEmpty($block) { if (empty($block->lines)) { foreach ($block->children as $child) { if (!$this->isEmpty($child)) { return false; } } return true; } return false; } /** * Output a CSS block * * @param stdClass $block The block definition to output * * @return void */ public function block($block) { if ($this->isEmpty($block)) { return; } $inner = $pre = $this->indentStr(); $isSingle = !$this->disableSingle && is_null($block->type) && count($block->lines) == 1; if (!empty($block->selectors)) { $this->indentLevel++; if ($this->breakSelectors) { $selectorSeparator = $this->selectorSeparator . $this->break . $pre; } else { $selectorSeparator = $this->selectorSeparator; } echo $pre . implode($selectorSeparator, $block->selectors); if ($isSingle) { echo $this->openSingle; $inner = ""; } else { echo $this->open . $this->break; $inner = $this->indentStr(); } } if (!empty($block->lines)) { $glue = $this->break . $inner; echo $inner . implode($glue, $block->lines); if (!$isSingle && !empty($block->children)) { echo $this->break; } } foreach ($block->children as $child) { $this->block($child); } if (!empty($block->selectors)) { if (!$isSingle && empty($block->children)) { echo $this->break; } if ($isSingle) { echo $this->closeSingle . $this->break; } else { echo $pre . $this->close . $this->break; } $this->indentLevel--; } } } PKY[k66fof/config/index.htmlnuW+APKY[M: fof/config/domain/dispatcher.phpnuW+Adispatcher; // Sanity check if (empty($dispatcherData)) { return; } $options = $xml->xpath('dispatcher/option'); if (!empty($options)) { foreach ($options as $option) { $key = (string) $option['name']; $ret['dispatcher'][$key] = (string) $option; } } } /** * Return a configuration variable * * @param string &$configuration Configuration variables (hashed array) * @param string $var The variable we want to fetch * @param mixed $default Default value * * @return mixed The variable's value */ public function get(&$configuration, $var, $default) { if (isset($configuration['dispatcher'][$var])) { return $configuration['dispatcher'][$var]; } else { return $default; } } } PKY[ccfof/config/domain/tables.phpnuW+Axpath('table'); // Sanity check if (empty($tableData)) { return; } foreach ($tableData as $aTable) { $key = (string) $aTable['name']; $ret['tables'][$key]['behaviors'] = (string) $aTable->behaviors; $ret['tables'][$key]['tablealias'] = $aTable->xpath('tablealias'); $ret['tables'][$key]['fields'] = array(); $ret['tables'][$key]['relations'] = array(); $fieldData = $aTable->xpath('field'); if (!empty($fieldData)) { foreach ($fieldData as $field) { $k = (string) $field['name']; $ret['tables'][$key]['fields'][$k] = (string) $field; } } $relationsData = $aTable->xpath('relation'); if (!empty($relationsData)) { foreach ($relationsData as $relationData) { $type = (string)$relationData['type']; $itemName = (string)$relationData['name']; if (empty($type) || empty($itemName)) { continue; } $tableClass = (string)$relationData['tableClass']; $localKey = (string)$relationData['localKey']; $remoteKey = (string)$relationData['remoteKey']; $ourPivotKey = (string)$relationData['ourPivotKey']; $theirPivotKey = (string)$relationData['theirPivotKey']; $pivotTable = (string)$relationData['pivotTable']; $default = (string)$relationData['default']; $default = !in_array($default, array('no', 'false', 0)); $relation = array( 'type' => $type, 'itemName' => $itemName, 'tableClass' => empty($tableClass) ? null : $tableClass, 'localKey' => empty($localKey) ? null : $localKey, 'remoteKey' => empty($remoteKey) ? null : $remoteKey, 'default' => $default, ); if (!empty($ourPivotKey) || !empty($theirPivotKey) || !empty($pivotTable)) { $relation['ourPivotKey'] = empty($ourPivotKey) ? null : $ourPivotKey; $relation['theirPivotKey'] = empty($theirPivotKey) ? null : $theirPivotKey; $relation['pivotTable'] = empty($pivotTable) ? null : $pivotTable; } $ret['tables'][$key]['relations'][] = $relation; } } } } /** * Return a configuration variable * * @param string &$configuration Configuration variables (hashed array) * @param string $var The variable we want to fetch * @param mixed $default Default value * * @return mixed The variable's value */ public function get(&$configuration, $var, $default) { $parts = explode('.', $var); $view = $parts[0]; $method = 'get' . ucfirst($parts[1]); if (!method_exists($this, $method)) { return $default; } array_shift($parts); array_shift($parts); $ret = $this->$method($view, $configuration, $parts, $default); return $ret; } /** * Internal method to return the magic field mapping * * @param string $table The table for which we will be fetching a field map * @param array &$configuration The configuration parameters hash array * @param array $params Extra options; key 0 defines the table we want to fetch * @param string $default Default magic field mapping; empty if not defined * * @return array Field map */ protected function getField($table, &$configuration, $params, $default = '') { $fieldmap = array(); if (isset($configuration['tables']['*']) && isset($configuration['tables']['*']['fields'])) { $fieldmap = $configuration['tables']['*']['fields']; } if (isset($configuration['tables'][$table]) && isset($configuration['tables'][$table]['fields'])) { $fieldmap = array_merge($fieldmap, $configuration['tables'][$table]['fields']); } $map = $default; if (empty($params[0])) { $map = $fieldmap; } elseif (isset($fieldmap[$params[0]])) { $map = $fieldmap[$params[0]]; } return $map; } /** * Internal method to get table alias * * @param string $table The table for which we will be fetching table alias * @param array &$configuration The configuration parameters hash array * @param array $params Extra options; key 0 defines the table we want to fetch * @param string $default Default table alias * * @return string Table alias */ protected function getTablealias($table, &$configuration, $params, $default = '') { $tablealias = $default; if (isset($configuration['tables']['*']) && isset($configuration['tables']['*']['tablealias']) && isset($configuration['tables']['*']['tablealias'][0])) { $tablealias = (string) $configuration['tables']['*']['tablealias'][0]; } if (isset($configuration['tables'][$table]) && isset($configuration['tables'][$table]['tablealias']) && isset($configuration['tables'][$table]['tablealias'][0])) { $tablealias = (string) $configuration['tables'][$table]['tablealias'][0]; } return $tablealias; } /** * Internal method to get table behaviours * * @param string $table The table for which we will be fetching table alias * @param array &$configuration The configuration parameters hash array * @param array $params Extra options; key 0 defines the table we want to fetch * @param string $default Default table alias * * @return string Table behaviours */ protected function getBehaviors($table, &$configuration, $params, $default = '') { $behaviors = $default; if (isset($configuration['tables']['*']) && isset($configuration['tables']['*']['behaviors'])) { $behaviors = (string) $configuration['tables']['*']['behaviors']; } if (isset($configuration['tables'][$table]) && isset($configuration['tables'][$table]['behaviors'])) { $behaviors = (string) $configuration['tables'][$table]['behaviors']; } return $behaviors; } /** * Internal method to get table relations * * @param string $table The table for which we will be fetching table alias * @param array &$configuration The configuration parameters hash array * @param array $params Extra options; key 0 defines the table we want to fetch * @param string $default Default table alias * * @return array Table relations */ protected function getRelations($table, &$configuration, $params, $default = '') { $relations = $default; if (isset($configuration['tables']['*']) && isset($configuration['tables']['*']['relations'])) { $relations = $configuration['tables']['*']['relations']; } if (isset($configuration['tables'][$table]) && isset($configuration['tables'][$table]['relations'])) { $relations = $configuration['tables'][$table]['relations']; } return $relations; } } PKY[VPfof/config/domain/interface.phpnuW+Axpath('view'); // Sanity check if (empty($viewData)) { return; } foreach ($viewData as $aView) { $key = (string) $aView['name']; // Parse ACL options $ret['views'][$key]['acl'] = array(); $aclData = $aView->xpath('acl/task'); if (!empty($aclData)) { foreach ($aclData as $acl) { $k = (string) $acl['name']; $ret['views'][$key]['acl'][$k] = (string) $acl; } } // Parse taskmap $ret['views'][$key]['taskmap'] = array(); $taskmapData = $aView->xpath('taskmap/task'); if (!empty($taskmapData)) { foreach ($taskmapData as $map) { $k = (string) $map['name']; $ret['views'][$key]['taskmap'][$k] = (string) $map; } } // Parse controller configuration $ret['views'][$key]['config'] = array(); $optionData = $aView->xpath('config/option'); if (!empty($optionData)) { foreach ($optionData as $option) { $k = (string) $option['name']; $ret['views'][$key]['config'][$k] = (string) $option; } } // Parse the toolbar $ret['views'][$key]['toolbar'] = array(); $toolBar = $aView->xpath('toolbar'); if (!empty($toolBar)) { $toolbarAttributes = $toolBar[0]->attributes(); // If a toolbar title is specified, create a title element. if (isset($toolbarAttributes['title'])) { $ret['views'][$key]['toolbar']['title'] = array( 'value' => (string) $toolbarAttributes['title'] ); } // Parse the toolbar buttons data $toolbarData = $aView->xpath('toolbar/button'); if (!empty($toolbarData)) { foreach ($toolbarData as $button) { $k = (string) $button['type']; $ret['views'][$key]['toolbar'][$k] = current($button->attributes()); $ret['views'][$key]['toolbar'][$k]['value'] = (string) $button; } } } } } /** * Return a configuration variable * * @param string &$configuration Configuration variables (hashed array) * @param string $var The variable we want to fetch * @param mixed $default Default value * * @return mixed The variable's value */ public function get(&$configuration, $var, $default) { $parts = explode('.', $var); $view = $parts[0]; $method = 'get' . ucfirst($parts[1]); if (!method_exists($this, $method)) { return $default; } array_shift($parts); array_shift($parts); $ret = $this->$method($view, $configuration, $parts, $default); return $ret; } /** * Internal function to return the task map for a view * * @param string $view The view for which we will be fetching a task map * @param array &$configuration The configuration parameters hash array * @param array $params Extra options (not used) * @param array $default ßDefault task map; empty array if not provided * * @return array The task map as a hash array in the format task => method */ protected function getTaskmap($view, &$configuration, $params, $default = array()) { $taskmap = array(); if (isset($configuration['views']['*']) && isset($configuration['views']['*']['taskmap'])) { $taskmap = $configuration['views']['*']['taskmap']; } if (isset($configuration['views'][$view]) && isset($configuration['views'][$view]['taskmap'])) { $taskmap = array_merge($taskmap, $configuration['views'][$view]['taskmap']); } if (empty($taskmap)) { return $default; } return $taskmap; } /** * Internal method to return the ACL mapping (privilege required to access * a specific task) for the given view's tasks * * @param string $view The view for which we will be fetching a task map * @param array &$configuration The configuration parameters hash array * @param array $params Extra options; key 0 defines the task we want to fetch * @param string $default Default ACL option; empty (no ACL check) if not defined * * @return string The privilege required to access this view */ protected function getAcl($view, &$configuration, $params, $default = '') { $aclmap = array(); if (isset($configuration['views']['*']) && isset($configuration['views']['*']['acl'])) { $aclmap = $configuration['views']['*']['acl']; } if (isset($configuration['views'][$view]) && isset($configuration['views'][$view]['acl'])) { $aclmap = array_merge($aclmap, $configuration['views'][$view]['acl']); } $acl = $default; if (isset($aclmap['*'])) { $acl = $aclmap['*']; } if (isset($aclmap[$params[0]])) { $acl = $aclmap[$params[0]]; } return $acl; } /** * Internal method to return the a configuration option for the view. These * are equivalent to $config array options passed to the Controller * * @param string $view The view for which we will be fetching a task map * @param array &$configuration The configuration parameters hash array * @param array $params Extra options; key 0 defines the option variable we want to fetch * @param mixed $default Default option; null if not defined * * @return string The setting for the requested option */ protected function getConfig($view, &$configuration, $params, $default = null) { $ret = $default; if (isset($configuration['views']['*']) && isset($configuration['views']['*']['config']) && isset($configuration['views']['*']['config'][$params[0]])) { $ret = $configuration['views']['*']['config'][$params[0]]; } if (isset($configuration['views'][$view]) && isset($configuration['views'][$view]['config']) && isset($configuration['views'][$view]['config'][$params[0]])) { $ret = $configuration['views'][$view]['config'][$params[0]]; } return $ret; } /** * Internal method to return the toolbar infos. * * @param string $view The view for which we will be fetching buttons * @param array &$configuration The configuration parameters hash array * @param array $params Extra options * @param string $default Default option * * @return string The toolbar data for this view */ protected function getToolbar($view, &$configuration, $params, $default = '') { $toolbar = array(); if (isset($configuration['views']['*']) && isset($configuration['views']['*']['toolbar'])) { $toolbar = $configuration['views']['*']['toolbar']; } if (isset($configuration['views'][$view]) && isset($configuration['views'][$view]['toolbar'])) { $toolbar = array_merge($toolbar, $configuration['views'][$view]['toolbar']); } if (empty($toolbar)) { return $default; } return $toolbar; } } PKY[<*wwfof/config/provider.phpnuW+AisCli()) { $order = array('cli', 'backend'); } elseif (FOFPlatform::getInstance()->isBackend()) { $order = array('backend'); } else { $order = array('frontend'); } $order[] = 'common'; $order = array_reverse($order); self::$configurations[$component] = array(); foreach ($order as $area) { $config = $this->parseComponentArea($component, $area); self::$configurations[$component] = array_merge_recursive(self::$configurations[$component], $config); } } /** * Returns the value of a variable. Variables use a dot notation, e.g. * view.config.whatever where the first part is the domain, the rest of the * parts specify the path to the variable. * * @param string $variable The variable name * @param mixed $default The default value, or null if not specified * * @return mixed The value of the variable */ public function get($variable, $default = null) { static $domains = null; if (is_null($domains)) { $domains = $this->getDomains(); } list($component, $domain, $var) = explode('.', $variable, 3); if (!isset(self::$configurations[$component])) { $this->parseComponent($component); } if (!in_array($domain, $domains)) { return $default; } $class = 'FOFConfigDomain' . ucfirst($domain); $o = new $class; return $o->get(self::$configurations[$component], $var, $default); } /** * Parses the configuration options of a specific component area * * @param string $component Which component's cionfiguration to parse * @param string $area Which area to parse (frontend, backend, cli) * * @return array A hash array with the configuration data */ protected function parseComponentArea($component, $area) { // Initialise the return array $ret = array(); // Get the folders of the component $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($component); $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); // Check that the path exists $path = $componentPaths['admin']; $path = $filesystem->pathCheck($path); if (!$filesystem->folderExists($path)) { return $ret; } // Read the filename if it exists $filename = $path . '/fof.xml'; if (!$filesystem->fileExists($filename)) { return $ret; } $data = file_get_contents($filename); // Load the XML data in a SimpleXMLElement object $xml = simplexml_load_string($data); if (!($xml instanceof SimpleXMLElement)) { return $ret; } // Get this area's data $areaData = $xml->xpath('//' . $area); if (empty($areaData)) { return $ret; } $xml = array_shift($areaData); // Parse individual configuration domains $domains = $this->getDomains(); foreach ($domains as $dom) { $class = 'FOFConfigDomain' . ucfirst($dom); if (class_exists($class, true)) { $o = new $class; $o->parseDomain($xml, $ret); } } // Finally, return the result return $ret; } /** * Gets a list of the available configuration domain adapters * * @return array A list of the available domains */ protected function getDomains() { static $domains = array(); if (empty($domains)) { $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); $files = $filesystem->folderFiles(__DIR__ . '/domain', '.php'); if (!empty($files)) { foreach ($files as $file) { $domain = basename($file, '.php'); if ($domain == 'interface') { continue; } $domain = preg_replace('/[^A-Za-z0-9]/', '', $domain); $domains[] = $domain; } $domains = array_unique($domains); } } return $domains; } } PKY[%%fof/model/behavior/language.phpnuW+AisFrontend()) { return; } // Get the name of the language field $table = $model->getTable(); $languageField = $table->getColumnAlias('language'); // Make sure the access field actually exists if (!in_array($languageField, $table->getKnownFields())) { return; } // Make sure it is a multilingual site and get a list of languages $app = JFactory::getApplication(); $hasLanguageFilter = method_exists($app, 'getLanguageFilter'); if ($hasLanguageFilter) { $hasLanguageFilter = $app->getLanguageFilter(); } if (!$hasLanguageFilter) { return; } $lang_filter_plugin = JPluginHelper::getPlugin('system', 'languagefilter'); $lang_filter_params = new JRegistry($lang_filter_plugin->params); $languages = array('*'); if ($lang_filter_params->get('remove_default_prefix')) { // Get default site language $lg = FOFPlatform::getInstance()->getLanguage(); $languages[] = $lg->getTag(); } else { $languages[] = JFactory::getApplication()->input->getCmd('language', '*'); } // Filter out double languages $languages = array_unique($languages); // And filter the query output by these languages $db = FOFPlatform::getInstance()->getDbo(); $languages = array_map(array($db, 'quote'), $languages); $query->where($db->qn($languageField) . ' IN (' . implode(',', $languages) . ')'); } /** * The event runs after FOFModel has called FOFTable and retrieved a single * item from the database. It is used to apply automatic filters. * * @param FOFModel &$model The model which was called * @param FOFTable &$record The record loaded from the databae * * @return void */ public function onAfterGetItem(&$model, &$record) { if ($record instanceof FOFTable) { $fieldName = $record->getColumnAlias('language'); // Make sure the field actually exists if (!in_array($fieldName, $record->getKnownFields())) { return; } // Make sure it is a multilingual site and get a list of languages $app = JFactory::getApplication(); $hasLanguageFilter = method_exists($app, 'getLanguageFilter'); if ($hasLanguageFilter) { $hasLanguageFilter = $app->getLanguageFilter(); } if (!$hasLanguageFilter) { return; } $lang_filter_plugin = JPluginHelper::getPlugin('system', 'languagefilter'); $lang_filter_params = new JRegistry($lang_filter_plugin->params); $languages = array('*'); if ($lang_filter_params->get('remove_default_prefix')) { // Get default site language $lg = FOFPlatform::getInstance()->getLanguage(); $languages[] = $lg->getTag(); } else { $languages[] = JFactory::getApplication()->input->getCmd('language', '*'); } // Filter out double languages $languages = array_unique($languages); if (!in_array($record->$fieldName, $languages)) { $record = null; } } } } PKY[_Gfof/model/behavior/enabled.phpnuW+AisFrontend()) { return; } // Get the name of the enabled field $table = $model->getTable(); $enabledField = $table->getColumnAlias('enabled'); // Make sure the field actually exists if (!in_array($enabledField, $table->getKnownFields())) { return; } // Filter by enabled fields only $db = FOFPlatform::getInstance()->getDbo(); $query->where($db->qn($enabledField) . ' = ' . $db->q(1)); } /** * The event runs after FOFModel has called FOFTable and retrieved a single * item from the database. It is used to apply automatic filters. * * @param FOFModel &$model The model which was called * @param FOFTable &$record The record loaded from the databae * * @return void */ public function onAfterGetItem(&$model, &$record) { if ($record instanceof FOFTable) { $fieldName = $record->getColumnAlias('enabled'); // Make sure the field actually exists if (!in_array($fieldName, $record->getKnownFields())) { return; } if ($record->$fieldName != 1) { $record = null; } } } } PKY[>^ۃ??fof/model/behavior/access.phpnuW+AisFrontend()) { return; } // Get the name of the access field $table = $model->getTable(); $accessField = $table->getColumnAlias('access'); // Make sure the field actually exists if (!in_array($accessField, $table->getKnownFields())) { return; } $model->applyAccessFiltering(null); } /** * The event runs after FOFModel has called FOFTable and retrieved a single * item from the database. It is used to apply automatic filters. * * @param FOFModel &$model The model which was called * @param FOFTable &$record The record loaded from the databae * * @return void */ public function onAfterGetItem(&$model, &$record) { if ($record instanceof FOFTable) { $fieldName = $record->getColumnAlias('access'); // Make sure the field actually exists if (!in_array($fieldName, $record->getKnownFields())) { return; } // Get the user $user = FOFPlatform::getInstance()->getUser(); // Filter by authorised access levels if (!in_array($record->$fieldName, $user->getAuthorisedViewLevels())) { $record = null; } } } } PKY[] ] fof/model/behavior/filters.phpnuW+AgetTable(); $tableName = $table->getTableName(); $tableKey = $table->getKeyName(); $db = $model->getDBO(); $fields = $model->getTableFields(); foreach ($fields as $fieldname => $fieldtype) { $field = new stdClass; $field->name = $fieldname; $field->type = $fieldtype; $filterName = ($field->name == $tableKey) ? 'id' : $field->name; $filterState = $model->getState($filterName, null); $field = FOFModelField::getField($field, array('dbo' => $db, 'table_alias' => $model->getTableAlias())); if ((is_array($filterState) && ( array_key_exists('value', $filterState) || array_key_exists('from', $filterState) || array_key_exists('to', $filterState) )) || is_object($filterState)) { $options = new JRegistry($filterState); } else { $options = new JRegistry; $options->set('value', $filterState); } $methods = $field->getSearchMethods(); $method = $options->get('method', $field->getDefaultSearchMethod()); if (!in_array($method, $methods)) { $method = 'exact'; } switch ($method) { case 'between': case 'outside': $sql = $field->$method($options->get('from', null), $options->get('to')); break; case 'interval': $sql = $field->$method($options->get('value', null), $options->get('interval')); break; case 'exact': case 'partial': case 'search': default: $sql = $field->$method($options->get('value', null)); break; } if ($sql) { $query->where($sql); } } } } PKY[n̔ fof/model/behavior/private.phpnuW+AisFrontend()) { return; } // Get the name of the access field $table = $model->getTable(); $createdField = $table->getColumnAlias('created_by'); // Make sure the access field actually exists if (!in_array($createdField, $table->getKnownFields())) { return; } // Get the current user's id $user_id = FOFPlatform::getInstance()->getUser()->id; // And filter the query output by the user id $db = FOFPlatform::getInstance()->getDbo(); $alias = $model->getTableAlias(); $alias = $alias ? $db->qn($alias) . '.' : ''; $query->where($alias . $db->qn($createdField) . ' = ' . $db->q($user_id)); } /** * The event runs after FOFModel has called FOFTable and retrieved a single * item from the database. It is used to apply automatic filters. * * @param FOFModel &$model The model which was called * @param FOFTable &$record The record loaded from the databae * * @return void */ public function onAfterGetItem(&$model, &$record) { if ($record instanceof FOFTable) { $keyName = $record->getKeyName(); if ($record->$keyName === null) { return; } $fieldName = $record->getColumnAlias('created_by'); // Make sure the field actually exists if (!in_array($fieldName, $record->getKnownFields())) { return; } $user_id = FOFPlatform::getInstance()->getUser()->id; if ($record->$fieldName != $user_id) { $record = null; } } } } PKY[˗5%%fof/model/behavior.phpnuW+APKY[1S !fof/model/dispatcher/behavior.phpnuW+Aget('option', 'com_foobar'); } $config['option'] = $component; $needsAView = true; if (array_key_exists('view', $config)) { if (!empty($config['view'])) { $needsAView = false; } } if ($needsAView) { $config['view'] = strtolower($type); } $config['input']->set('option', $config['option']); // Get the component directories $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($component); $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); // Try to load the requested model class if (!class_exists($modelClass)) { $include_paths = self::addIncludePath(); $extra_paths = array( $componentPaths['main'] . '/models', $componentPaths['alt'] . '/models' ); $include_paths = array_merge($extra_paths, $include_paths); // Try to load the model file $path = $filesystem->pathFind( $include_paths, self::_createFileName('model', array('name' => $type)) ); if ($path) { require_once $path; } } // Fallback to the Default model class, e.g. FoobarModelDefault if (!class_exists($modelClass)) { $modelClass = $prefix . 'Default'; if (!class_exists($modelClass)) { $include_paths = self::addIncludePath(); $extra_paths = array( $componentPaths['main'] . '/models', $componentPaths['alt'] . '/models' ); $include_paths = array_merge($extra_paths, $include_paths); // Try to load the model file $path = $filesystem->pathFind( $include_paths, self::_createFileName('model', array('name' => 'default')) ); if ($path) { require_once $path; } } } // Fallback to the generic FOFModel model class if (!class_exists($modelClass)) { $modelClass = 'FOFModel'; } $result = new $modelClass($config); return $result; } /** * Adds a behavior to the model * * @param string $name The name of the behavior * @param array $config Optional Behavior configuration * * @return boolean True if the behavior is found and added */ public function addBehavior($name, $config = array()) { // Sanity check: this objects needs a non-null behavior handler if (!is_object($this->modelDispatcher)) { return false; } // Sanity check: this objects needs a behavior handler of the correct class type if (!($this->modelDispatcher instanceof FOFModelDispatcherBehavior)) { return false; } // First look for ComponentnameModelViewnameBehaviorName (e.g. FoobarModelItemsBehaviorFilter) $option_name = str_replace('com_', '', $this->option); $behaviorClass = ucfirst($option_name) . 'Model' . FOFInflector::pluralize($this->name) . 'Behavior' . ucfirst(strtolower($name)); if (class_exists($behaviorClass)) { $behavior = new $behaviorClass($this->modelDispatcher, $config); return true; } // Then look for ComponentnameModelBehaviorName (e.g. FoobarModelBehaviorFilter) $option_name = str_replace('com_', '', $this->option); $behaviorClass = ucfirst($option_name) . 'ModelBehavior' . ucfirst(strtolower($name)); if (class_exists($behaviorClass)) { $behavior = new $behaviorClass($this->modelDispatcher, $config); return true; } // Then look for FOFModelBehaviorName (e.g. FOFModelBehaviorFilter) $behaviorClassAlt = 'FOFModelBehavior' . ucfirst(strtolower($name)); if (class_exists($behaviorClassAlt)) { $behavior = new $behaviorClassAlt($this->modelDispatcher, $config); return true; } // Nothing found? Return false. return false; } /** * Returns a new instance of a model, with the state reset to defaults * * @param string $type Model type, e.g. 'Items' * @param string $prefix Model prefix, e.g. 'FoobarModel' * @param array $config Model configuration variables * * @return FOFModel */ public static function &getTmpInstance($type, $prefix = '', $config = array()) { // Make sure $config is an array if (is_object($config)) { $config = (array) $config; } elseif (!is_array($config)) { $config = array(); } if (!array_key_exists('savesate', $config)) { $config['savestate'] = false; } $ret = self::getAnInstance($type, $prefix, $config) ->getClone() ->clearState() ->clearInput() ->reset() ->savestate(0) ->limitstart(0) ->limit(0); return $ret; } /** * Add a directory where FOFModel should search for models. You may * either pass a string or an array of directories. * * @param mixed $path A path or array[sting] of paths to search. * @param string $prefix A prefix for models. * * @return array An array with directory elements. If prefix is equal to '', all directories are returned. * * @since 12.2 */ public static function addIncludePath($path = '', $prefix = '') { static $paths; if (!isset($paths)) { $paths = array(); } if (!isset($paths[$prefix])) { $paths[$prefix] = array(); } if (!isset($paths[''])) { $paths[''] = array(); } if (!empty($path)) { $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); if (!in_array($path, $paths[$prefix])) { array_unshift($paths[$prefix], $filesystem->pathClean($path)); } if (!in_array($path, $paths[''])) { array_unshift($paths[''], $filesystem->pathClean($path)); } } return $paths[$prefix]; } /** * Adds to the stack of model table paths in LIFO order. * * @param mixed $path The directory as a string or directories as an array to add. * * @return void * * @since 12.2 */ public static function addTablePath($path) { FOFTable::addIncludePath($path); } /** * Create the filename for a resource * * @param string $type The resource type to create the filename for. * @param array $parts An associative array of filename information. * * @return string The filename * * @since 12.2 */ protected static function _createFileName($type, $parts = array()) { $filename = ''; switch ($type) { case 'model': $filename = strtolower($parts['name']) . '.php'; break; } return $filename; } /** * Public class constructor * * @param array $config The configuration array */ public function __construct($config = array()) { // Make sure $config is an array if (is_object($config)) { $config = (array) $config; } elseif (!is_array($config)) { $config = array(); } // Get the input if (array_key_exists('input', $config)) { if ($config['input'] instanceof FOFInput) { $this->input = $config['input']; } else { $this->input = new FOFInput($config['input']); } } else { $this->input = new FOFInput; } // Load the configuration provider $this->configProvider = new FOFConfigProvider; // Load the behavior dispatcher $this->modelDispatcher = new FOFModelDispatcherBehavior; // Set the $name/$_name variable $component = $this->input->getCmd('option', 'com_foobar'); if (array_key_exists('option', $config)) { $component = $config['option']; } // Set the $name variable $this->input->set('option', $component); $component = $this->input->getCmd('option', 'com_foobar'); if (array_key_exists('option', $config)) { $component = $config['option']; } $this->input->set('option', $component); $bareComponent = str_replace('com_', '', strtolower($component)); // Get the view name $className = get_class($this); if ($className == 'FOFModel') { if (array_key_exists('view', $config)) { $view = $config['view']; } if (empty($view)) { $view = $this->input->getCmd('view', 'cpanel'); } } else { $eliminatePart = ucfirst($bareComponent) . 'Model'; $view = strtolower(str_replace($eliminatePart, '', $className)); } if (array_key_exists('name', $config)) { $name = $config['name']; } else { $name = $view; } $this->name = $name; $this->option = $component; // Set the model state if (array_key_exists('state', $config)) { $this->state = $config['state']; } else { $this->state = new FOFUtilsObject; } // Set the model dbo if (array_key_exists('dbo', $config)) { $this->_db = $config['dbo']; } else { $this->_db = FOFPlatform::getInstance()->getDbo(); } // Set the default view search path if (array_key_exists('table_path', $config)) { $this->addTablePath($config['table_path']); } else { $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($this->option); $path = $componentPaths['admin'] . '/tables'; $altPath = $this->configProvider->get($this->option . '.views.' . FOFInflector::singularize($this->name) . '.config.table_path', null); if ($altPath) { $path = $componentPaths['main'] . '/' . $altPath; } $this->addTablePath($path); } // Assign the correct table if (array_key_exists('table', $config)) { $this->table = $config['table']; } else { $table = $this->configProvider->get( $this->option . '.views.' . FOFInflector::singularize($this->name) . '.config.table', FOFInflector::singularize($view) ); $this->table = $table; } // Set the internal state marker - used to ignore setting state from the request if (!empty($config['ignore_request']) || !is_null( $this->configProvider->get( $this->option . '.views.' . FOFInflector::singularize($this->name) . '.config.ignore_request', null ) )) { $this->__state_set = true; } // Get and store the pagination request variables $defaultSaveState = array_key_exists('savestate', $config) ? $config['savestate'] : -999; $this->populateSavestate($defaultSaveState); if (FOFPlatform::getInstance()->isCli()) { $limit = 20; $limitstart = 0; } else { $app = JFactory::getApplication(); if (method_exists($app, 'getCfg')) { $default_limit = $app->getCfg('list_limit'); } else { $default_limit = 20; } $limit = $this->getUserStateFromRequest($component . '.' . $view . '.limit', 'limit', $default_limit, 'int', $this->_savestate); $limitstart = $this->getUserStateFromRequest($component . '.' . $view . '.limitstart', 'limitstart', 0, 'int', $this->_savestate); } $this->setState('limit', $limit); $this->setState('limitstart', $limitstart); // Get the ID or list of IDs from the request or the configuration if (array_key_exists('cid', $config)) { $cid = $config['cid']; } elseif ($cid = $this->configProvider->get( $this->option . '.views.' . FOFInflector::singularize($this->name) . '.config.cid', null ) ) { $cid = explode(',', $cid); } else { $cid = $this->input->get('cid', array(), 'array'); } if (array_key_exists('id', $config)) { $id = $config['id']; } elseif ($id = $this->configProvider->get( $this->option . '.views.' . FOFInflector::singularize($this->name) . '.config.id', null ) ) { $id = explode(',', $id); $id = array_shift($id); } else { $id = $this->input->getInt('id', 0); } if (is_array($cid) && !empty($cid)) { $this->setIds($cid); } else { $this->setId($id); } // Populate the event names from the $config array $configKey = $this->option . '.views.' . FOFInflector::singularize($view) . '.config.'; // Assign after delete event handler if (isset($config['event_after_delete'])) { $this->event_after_delete = $config['event_after_delete']; } else { $this->event_after_delete = $this->configProvider->get( $configKey . 'event_after_delete', $this->event_after_delete ); } // Assign after save event handler if (isset($config['event_after_save'])) { $this->event_after_save = $config['event_after_save']; } else { $this->event_after_save = $this->configProvider->get( $configKey . 'event_after_save', $this->event_after_save ); } // Assign before delete event handler if (isset($config['event_before_delete'])) { $this->event_before_delete = $config['event_before_delete']; } else { $this->event_before_delete = $this->configProvider->get( $configKey . 'event_before_delete', $this->event_before_delete ); } // Assign before save event handler if (isset($config['event_before_save'])) { $this->event_before_save = $config['event_before_save']; } else { $this->event_before_save = $this->configProvider->get( $configKey . 'event_before_save', $this->event_before_save ); } // Assign state change event handler if (isset($config['event_change_state'])) { $this->event_change_state = $config['event_change_state']; } else { $this->event_change_state = $this->configProvider->get( $configKey . 'event_change_state', $this->event_change_state ); } // Assign cache clean event handler if (isset($config['event_clean_cache'])) { $this->event_clean_cache = $config['event_clean_cache']; } else { $this->event_clean_cache = $this->configProvider->get( $configKey . 'event_clean_cache', $this->event_clean_cache ); } // Apply model behaviors if (isset($config['behaviors'])) { $behaviors = (array) $config['behaviors']; } elseif ($behaviors = $this->configProvider->get($configKey . 'behaviors', null)) { $behaviors = explode(',', $behaviors); } else { $behaviors = $this->default_behaviors; } if (is_array($behaviors) && count($behaviors)) { foreach ($behaviors as $behavior) { $this->addBehavior($behavior); } } } /** * Sets the list of IDs from the request data * * @return FOFModel */ public function setIDsFromRequest() { // Get the ID or list of IDs from the request or the configuration $cid = $this->input->get('cid', array(), 'array'); $id = $this->input->getInt('id', 0); $kid = $this->input->getInt($this->getTable($this->table)->getKeyName(), 0); if (is_array($cid) && !empty($cid)) { $this->setIds($cid); } else { if (empty($id)) { $this->setId($kid); } else { $this->setId($id); } } return $this; } /** * Sets the ID and resets internal data * * @param integer $id The ID to use * * @throws InvalidArgumentException * * @return FOFModel */ public function setId($id = 0) { // If this is an array extract the first item if (is_array($id)) { FOFPlatform::getInstance()->logDeprecated('Passing arrays to FOFModel::setId is deprecated. Use setIds() instead.'); $id = array_shift($id); } // No string or no integer? What are you trying to do??? if (!is_string($id) && !is_numeric($id)) { throw new InvalidArgumentException(sprintf('%s::setId()', get_class($this))); } $this->reset(); $this->id = (int) $id; $this->id_list = array($this->id); return $this; } /** * Returns the currently set ID * * @return integer */ public function getId() { return $this->id; } /** * Sets a list of IDs for batch operations from an array and resets the model * * @param array $idlist An array of item IDs to be set to the model's state * * @return FOFModel */ public function setIds($idlist) { $this->reset(); $this->id_list = array(); $this->id = 0; if (is_array($idlist) && !empty($idlist)) { foreach ($idlist as $value) { // Protect vs fatal error (objects) and wrong behavior (nested array) if(!is_object($value) && !is_array($value)) { $this->id_list[] = (int) $value; } } if(count($this->id_list)) { $this->id = $this->id_list[0]; } } return $this; } /** * Returns the list of IDs for batch operations * * @return array An array of integers */ public function getIds() { return $this->id_list; } /** * Resets the model, like it was freshly loaded * * @return FOFModel */ public function reset() { $this->id = 0; $this->id_list = null; $this->record = null; $this->list = null; $this->pagination = null; $this->total = null; $this->otable = null; return $this; } /** * Clears the model state, but doesn't touch the internal lists of records, * record tables or record id variables. To clear these values, please use * reset(). * * @return FOFModel */ public function clearState() { $this->state = new FOFUtilsObject; return $this; } /** * Clears the input array. * * @return FOFModel */ public function clearInput() { $defSource = array(); $this->input = new FOFInput($defSource); return $this; } /** * Set the internal input field * * @param $input * * @return FOFModel */ public function setInput($input) { if (!($input instanceof FOFInput)) { if (!is_array($input)) { $input = (array) $input; } $input = array_merge($_REQUEST, $input); $input = new FOFInput($input); } $this->input = $input; return $this; } /** * Resets the saved state for this view * * @return FOFModel */ public function resetSavedState() { JFactory::getApplication()->setUserState(substr($this->getHash(), 0, -1), null); return $this; } /** * Returns a single item. It uses the id set with setId, or the first ID in * the list of IDs for batch operations * * @param integer $id Force a primary key ID to the model. Use null to use the id from the state. * * @return FOFTable A copy of the item's FOFTable array */ public function &getItem($id = null) { if (!is_null($id)) { $this->record = null; $this->setId($id); } if (empty($this->record)) { $table = $this->getTable($this->table); $table->load($this->id); $this->record = $table; // Do we have saved data? $session = JFactory::getSession(); if ($this->_savestate) { $serialized = $session->get($this->getHash() . 'savedata', null); if (!empty($serialized)) { $data = @unserialize($serialized); if ($data !== false) { $k = $table->getKeyName(); if (!array_key_exists($k, $data)) { $data[$k] = null; } if ($data[$k] != $this->id) { $session->set($this->getHash() . 'savedata', null); } else { $this->record->bind($data); } } } } $this->onAfterGetItem($this->record); } return $this->record; } /** * Alias for getItemList * * @param boolean $overrideLimits Should I override set limits? * @param string $group The group by clause * @codeCoverageIgnore * * @return array */ public function &getList($overrideLimits = false, $group = '') { return $this->getItemList($overrideLimits, $group); } /** * Returns a list of items * * @param boolean $overrideLimits Should I override set limits? * @param string $group The group by clause * * @return array */ public function &getItemList($overrideLimits = false, $group = '') { if (empty($this->list)) { $query = $this->buildQuery($overrideLimits); if (!$overrideLimits) { $limitstart = $this->getState('limitstart'); $limit = $this->getState('limit'); $this->list = $this->_getList((string) $query, $limitstart, $limit, $group); } else { $this->list = $this->_getList((string) $query, 0, 0, $group); } } return $this->list; } /** * Returns a FOFDatabaseIterator over a list of items. * * THERE BE DRAGONS. Unlike the getItemList() you have a few restrictions: * - The onProcessList event does not run when you get an iterator * - The Iterator returns FOFTable instances. By default, $this->table is used. If you have JOINs, GROUPs or a * complex query in general you will need to create a custom FOFTable subclass and pass its type in $tableType. * * The getIterator() method is a great way to sift through a large amount of records which would otherwise not fit * in memory since it only keeps one record in PHP memory at a time. It works best with simple models, returning * all the contents of a single database table. * * @param boolean $overrideLimits Should I ignore set limits? * @param string $tableClass The table class for the iterator, e.g. FoobarTableBar. Leave empty to use * the default Table class for this Model. * * @return FOFDatabaseIterator */ public function &getIterator($overrideLimits = false, $tableClass = null) { // Get the table name (required by the Iterator) if (empty($tableClass)) { $name = $this->table; if (empty($name)) { $name = FOFInflector::singularize($this->getName()); } $bareComponent = str_replace('com_', '', $this->option); $prefix = ucfirst($bareComponent) . 'Table'; $tableClass = $prefix . ucfirst($name); } // Get the query $query = $this->buildQuery($overrideLimits); // Apply limits if ($overrideLimits) { $limitStart = 0; $limit = 0; } else { $limitStart = $this->getState('limitstart'); $limit = $this->getState('limit'); } // This is required to prevent one relation from killing the db cursor used in a different relation... $oldDb = $this->getDbo(); $oldDb->disconnect(); // YES, WE DO NEED TO DISCONNECT BEFORE WE CLONE THE DB OBJECT. ARGH! $db = clone $oldDb; // Execute the query, get a db cursor and return the iterator $db->setQuery($query, $limitStart, $limit); $cursor = $db->execute(); $iterator = FOFDatabaseIterator::getIterator($db->name, $cursor, null, $tableClass); return $iterator; } /** * A cross-breed between getItem and getItemList. It runs the complete query, * like getItemList does. However, instead of returning an array of ad-hoc * objects, it binds the data from the first item fetched on the list to an * instance of the table object and returns that table object instead. * * @param boolean $overrideLimits Should I override set limits? * * @return FOFTable */ public function &getFirstItem($overrideLimits = false) { /** * We have to clone the instance, or when multiple getFirstItem calls occur, * we'll update EVERY instance created */ $table = clone $this->getTable($this->table); $list = $this->getItemList($overrideLimits); if (!empty($list)) { $firstItem = array_shift($list); $table->bind($firstItem); } unset($list); return $table; } /** * Binds the data to the model and tries to save it * * @param array|object $data The source data array or object * * @return boolean True on success */ public function save($data) { $this->otable = null; $table = $this->getTable($this->table); if (is_object($data)) { $data = clone($data); } $key = $table->getKeyName(); if (array_key_exists($key, (array) $data)) { $aData = (array) $data; $oid = $aData[$key]; $table->load($oid); } if ($data instanceof FOFTable) { $allData = $data->getData(); } elseif (is_object($data)) { $allData = (array) $data; } else { $allData = $data; } // Get the form if there is any $form = $this->getForm($allData, false); if ($form instanceof FOFForm) { // Make sure that $allData has for any field a key $fieldset = $form->getFieldset(); foreach ($fieldset as $nfield => $fldset) { if (!array_key_exists($nfield, $allData)) { $field = $form->getField($fldset->fieldname, $fldset->group); $type = strtolower($field->type); switch ($type) { case 'checkbox': $allData[$nfield] = 0; break; default: $allData[$nfield] = ''; break; } } } $serverside_validate = strtolower($form->getAttribute('serverside_validate')); $validateResult = true; if (in_array($serverside_validate, array('true', 'yes', '1', 'on'))) { $validateResult = $this->validateForm($form, $allData); } if ($validateResult === false) { if ($this->_savestate) { $session = JFactory::getSession(); $hash = $this->getHash() . 'savedata'; $session->set($hash, serialize($allData)); } return false; } } if (!$this->onBeforeSave($allData, $table)) { return false; } else { // If onBeforeSave successful, refetch the possibly modified data if ($data instanceof FOFTable) { $data->bind($allData); } elseif (is_object($data)) { $data = (object) $allData; } else { $data = $allData; } } if (!$table->save($data)) { foreach ($table->getErrors() as $error) { if (!empty($error)) { $this->setError($error); $session = JFactory::getSession(); $tableprops = $table->getProperties(true); unset($tableprops['input']); unset($tableprops['config']['input']); unset($tableprops['config']['db']); unset($tableprops['config']['dbo']); if ($this->_savestate) { $hash = $this->getHash() . 'savedata'; $session->set($hash, serialize($tableprops)); } } } return false; } else { $this->id = $table->$key; // Remove the session data if ($this->_savestate) { JFactory::getSession()->set($this->getHash() . 'savedata', null); } } $this->onAfterSave($table); $this->otable = $table; return true; } /** * Copy one or more records * * @return boolean True on success */ public function copy() { if (is_array($this->id_list) && !empty($this->id_list)) { $table = $this->getTable($this->table); if (!$this->onBeforeCopy($table)) { return false; } if (!$table->copy($this->id_list)) { $this->setError($table->getError()); return false; } else { // Call our internal event $this->onAfterCopy($table); // @todo Should we fire the content plugin? } } return true; } /** * Returns the table object after the last save() operation * * @return FOFTable */ public function getSavedTable() { return $this->otable; } /** * Deletes one or several items * * @return boolean True on success */ public function delete() { if (is_array($this->id_list) && !empty($this->id_list)) { $table = $this->getTable($this->table); foreach ($this->id_list as $id) { if (!$this->onBeforeDelete($id, $table)) { continue; } if (!$table->delete($id)) { $this->setError($table->getError()); return false; } else { $this->onAfterDelete($id); } } } return true; } /** * Toggles the published state of one or several items * * @param integer $publish The publishing state to set (e.g. 0 is unpublished) * @param integer $user The user ID performing this action * * @return boolean True on success */ public function publish($publish = 1, $user = null) { if (is_array($this->id_list) && !empty($this->id_list)) { if (empty($user)) { $oUser = FOFPlatform::getInstance()->getUser(); $user = $oUser->id; } $table = $this->getTable($this->table); if (!$this->onBeforePublish($table)) { return false; } if (!$table->publish($this->id_list, $publish, $user)) { $this->setError($table->getError()); return false; } else { // Call our internal event $this->onAfterPublish($table); // Call the plugin events FOFPlatform::getInstance()->importPlugin('content'); $name = $this->name; $context = $this->option . '.' . $name; // @TODO should we do anything with this return value? $result = FOFPlatform::getInstance()->runPlugins($this->event_change_state, array($context, $this->id_list, $publish)); } } return true; } /** * Checks out the current item * * @return boolean */ public function checkout() { $table = $this->getTable($this->table); $status = $table->checkout(FOFPlatform::getInstance()->getUser()->id, $this->id); if (!$status) { $this->setError($table->getError()); } return $status; } /** * Checks in the current item * * @return boolean */ public function checkin() { $table = $this->getTable($this->table); $status = $table->checkin($this->id); if (!$status) { $this->setError($table->getError()); } return $status; } /** * Tells you if the current item is checked out or not * * @return boolean */ public function isCheckedOut() { $table = $this->getTable($this->table); $status = $table->isCheckedOut($this->id); if (!$status) { $this->setError($table->getError()); } return $status; } /** * Increments the hit counter * * @return boolean */ public function hit() { $table = $this->getTable($this->table); if (!$this->onBeforeHit($table)) { return false; } $status = $table->hit($this->id); if (!$status) { $this->setError($table->getError()); } else { $this->onAfterHit($table); } return $status; } /** * Moves the current item up or down in the ordering list * * @param string $dirn The direction and magnitude to use (2 means move up by 2 positions, -3 means move down three positions) * * @return boolean True on success */ public function move($dirn) { $table = $this->getTable($this->table); $id = $this->getId(); $status = $table->load($id); if (!$status) { $this->setError($table->getError()); } if (!$status) { return false; } if (!$this->onBeforeMove($table)) { return false; } $status = $table->move($dirn); if (!$status) { $this->setError($table->getError()); } else { $this->onAfterMove($table); } return $status; } /** * Reorders all items in the table * * @return boolean */ public function reorder() { $table = $this->getTable($this->table); if (!$this->onBeforeReorder($table)) { return false; } $status = $table->reorder($this->getReorderWhere()); if (!$status) { $this->setError($table->getError()); } else { if (!$this->onAfterReorder($table)) { return false; } } return $status; } /** * Get a pagination object * * @return JPagination */ public function getPagination() { if (empty($this->pagination)) { // Import the pagination library JLoader::import('joomla.html.pagination'); // Prepare pagination values $total = $this->getTotal(); $limitstart = $this->getState('limitstart'); $limit = $this->getState('limit'); // Create the pagination object $this->pagination = new JPagination($total, $limitstart, $limit); } return $this->pagination; } /** * Get the number of all items * * @return integer */ public function getTotal() { if (is_null($this->total)) { $query = $this->buildCountQuery(); if ($query === false) { $subquery = $this->buildQuery(false); $subquery->clear('order'); $query = $this->_db->getQuery(true) ->select('COUNT(*)') ->from("(" . (string) $subquery . ") AS a"); } $this->_db->setQuery((string) $query); $this->total = $this->_db->loadResult(); } return $this->total; } /** * Returns a record count for the query * * @param string $query The query. * * @return integer Number of rows for query * * @since 12.2 */ protected function _getListCount($query) { return $this->getTotal(); } /** * Get a filtered state variable * * @param string $key The name of the state variable * @param mixed $default The default value to use * @param string $filter_type Filter type * * @return mixed The variable's value */ public function getState($key = null, $default = null, $filter_type = 'raw') { if (empty($key)) { return $this->_real_getState(); } // Get the savestate status $value = $this->_real_getState($key); if (is_null($value)) { $value = $this->getUserStateFromRequest($this->getHash() . $key, $key, $value, 'none', $this->_savestate); if (is_null($value)) { return $default; } } if (strtoupper($filter_type) == 'RAW') { return $value; } else { JLoader::import('joomla.filter.filterinput'); $filter = new JFilterInput; return $filter->clean($value, $filter_type); } } /** * Method to get model state variables * * @param string $property Optional parameter name * @param mixed $default Optional default value * * @return object The property where specified, the state object where omitted * * @since 12.2 */ protected function _real_getState($property = null, $default = null) { if (!$this->__state_set) { // Protected method to auto-populate the model state. $this->populateState(); // Set the model state set flag to true. $this->__state_set = true; } return $property === null ? $this->state : $this->state->get($property, $default); } /** * Returns a hash for this component and view, e.g. "foobar.items.", used * for determining the keys of the variables which will be placed in the * session storage. * * @return string The hash */ public function getHash() { $option = $this->input->getCmd('option', 'com_foobar'); $view = FOFInflector::pluralize($this->input->getCmd('view', 'cpanel')); return "$option.$view."; } /** * Gets the value of a user state variable. * * @param string $key The key of the user state variable. * @param string $request The name of the variable passed in a request. * @param string $default The default value for the variable if not found. Optional. * @param string $type Filter for the variable, for valid values see {@link JFilterInput::clean()}. Optional. * @param boolean $setUserState Should I save the variable in the user state? Default: true. Optional. * * @return string The request user state. */ protected function getUserStateFromRequest($key, $request, $default = null, $type = 'none', $setUserState = true) { return FOFPlatform::getInstance()->getUserStateFromRequest($key, $request, $this->input, $default, $type, $setUserState); } /** * Returns an object list * * @param string $query The query * @param integer $limitstart Offset from start * @param integer $limit The number of records * @param string $group The group by clause * * @return array Array of objects */ protected function &_getList($query, $limitstart = 0, $limit = 0, $group = '') { $this->_db->setQuery($query, $limitstart, $limit); $result = $this->_db->loadObjectList($group); $this->onProcessList($result); return $result; } /** * Method to get a table object, load it if necessary. * * @param string $name The table name. Optional. * @param string $prefix The class prefix. Optional. * @param array $options Configuration array for model. Optional. * * @throws Exception * * @return FOFTable A FOFTable object */ public function getTable($name = '', $prefix = null, $options = array()) { if (empty($name)) { $name = $this->table; if (empty($name)) { $name = FOFInflector::singularize($this->getName()); } } if (empty($prefix)) { $bareComponent = str_replace('com_', '', $this->option); $prefix = ucfirst($bareComponent) . 'Table'; } if (empty($options)) { $options = array('input' => $this->input); } if ($table = $this->_createTable($name, $prefix, $options)) { return $table; } FOFPlatform::getInstance()->raiseError(0, JText::sprintf('JLIB_APPLICATION_ERROR_TABLE_NAME_NOT_SUPPORTED', $name)); return null; } /** * Method to load and return a model object. * * @param string $name The name of the view * @param string $prefix The class prefix. Optional. * @param array $config The configuration array to pass to the table * * @return FOFTable Table object or boolean false if failed */ protected function &_createTable($name, $prefix = 'Table', $config = array()) { // Make sure $config is an array if (is_object($config)) { $config = (array) $config; } elseif (!is_array($config)) { $config = array(); } $result = null; // Clean the model name $name = preg_replace('/[^A-Z0-9_]/i', '', $name); $prefix = preg_replace('/[^A-Z0-9_]/i', '', $prefix); // Make sure we are returning a DBO object if (!array_key_exists('dbo', $config)) { $config['dbo'] = $this->getDBO(); } $instance = FOFTable::getAnInstance($name, $prefix, $config); return $instance; } /** * Creates the WHERE part of the reorder query * * @return string */ public function getReorderWhere() { return ''; } /** * Builds the SELECT query * * @param boolean $overrideLimits Are we requested to override the set limits? * * @return JDatabaseQuery */ public function buildQuery($overrideLimits = false) { $table = $this->getTable(); $tableName = $table->getTableName(); $tableKey = $table->getKeyName(); $db = $this->getDbo(); $query = $db->getQuery(true); // Call the behaviors $this->modelDispatcher->trigger('onBeforeBuildQuery', array(&$this, &$query)); $alias = $this->getTableAlias(); if ($alias) { $alias = ' AS ' . $db->qn($alias); } else { $alias = ''; } $select = $this->getTableAlias() ? $db->qn($this->getTableAlias()) . '.*' : $db->qn($tableName) . '.*'; $query->select($select)->from($db->qn($tableName) . $alias); if (!$overrideLimits) { $order = $this->getState('filter_order', null, 'cmd'); if (!in_array($order, array_keys($table->getData()))) { $order = $tableKey; } $order = $db->qn($order); if ($alias) { $order = $db->qn($this->getTableAlias()) . '.' . $order; } $dir = $this->getState('filter_order_Dir', 'ASC', 'cmd'); $query->order($order . ' ' . $dir); } // Call the behaviors $this->modelDispatcher->trigger('onAfterBuildQuery', array(&$this, &$query)); return $query; } /** * Returns a list of the fields of the table associated with this model * * @return array */ public function getTableFields() { $tableName = $this->getTable()->getTableName(); if (version_compare(JVERSION, '3.0', 'ge')) { $fields = $this->getDbo()->getTableColumns($tableName, true); } else { $fieldsArray = $this->getDbo()->getTableFields($tableName, true); $fields = array_shift($fieldsArray); } return $fields; } /** * Get the alias set for this model's table * * @return string The table alias */ public function getTableAlias() { return $this->getTable($this->table)->getTableAlias(); } /** * Builds the count query used in getTotal() * * @return boolean */ public function buildCountQuery() { return false; } /** * Clones the model object and returns the clone * * @return FOFModel */ public function &getClone() { $clone = clone($this); return $clone; } /** * Magic getter; allows to use the name of model state keys as properties * * @param string $name The name of the variable to get * * @return mixed The value of the variable */ public function __get($name) { return $this->getState($name); } /** * Magic setter; allows to use the name of model state keys as properties * * @param string $name The name of the variable * @param mixed $value The value to set the variable to * * @return void */ public function __set($name, $value) { return $this->setState($name, $value); } /** * Magic caller; allows to use the name of model state keys as methods to * set their values. * * @param string $name The name of the state variable to set * @param mixed $arguments The value to set the state variable to * * @return FOFModel Reference to self */ public function __call($name, $arguments) { $arg1 = array_shift($arguments); $this->setState($name, $arg1); return $this; } /** * Sets the model state auto-save status. By default the model is set up to * save its state to the session. * * @param boolean $newState True to save the state, false to not save it. * * @return FOFModel Reference to self */ public function &savestate($newState) { $this->_savestate = $newState ? true : false; return $this; } /** * Initialises the _savestate variable * * @param integer $defaultSaveState The default value for the savestate * * @return void */ public function populateSavestate($defaultSaveState = -999) { if (is_null($this->_savestate)) { $savestate = $this->input->getInt('savestate', $defaultSaveState); if ($savestate == -999) { $savestate = true; } $this->savestate($savestate); } } /** * Method to auto-populate the model state. * * This method should only be called once per instantiation and is designed * to be called on the first call to the getState() method unless the model * configuration flag to ignore the request is set. * * @return void * * @note Calling getState in this method will result in recursion. * @since 12.2 */ protected function populateState() { } /** * Applies view access level filtering for the specified user. Useful to * filter a front-end items listing. * * @param integer $userID The user ID to use. Skip it to use the currently logged in user. * * @return FOFModel Reference to self */ public function applyAccessFiltering($userID = null) { $user = FOFPlatform::getInstance()->getUser($userID); $table = $this->getTable(); $accessField = $table->getColumnAlias('access'); $this->setState($accessField, $user->getAuthorisedViewLevels()); return $this; } /** * A method for getting the form from the model. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @param boolean $source The name of the form. If not set we'll try the form_name state variable or fall back to default. * * @return mixed A FOFForm object on success, false on failure * * @since 2.0 */ public function getForm($data = array(), $loadData = true, $source = null) { $this->_formData = $data; $name = $this->input->getCmd('option', 'com_foobar') . '.' . $this->name; if (empty($source)) { $source = $this->getState('form_name', null); } if (empty($source)) { $source = 'form.' . $this->name; } $options = array( 'control' => false, 'load_data' => $loadData, ); $this->onBeforeLoadForm($name, $source, $options); $form = $this->loadForm($name, $source, $options); if ($form instanceof FOFForm) { $this->onAfterLoadForm($form, $name, $source, $options); } return $form; } /** * Method to get a form object. * * @param string $name The name of the form. * @param string $source The form filename (e.g. form.browse) * @param array $options Optional array of options for the form creation. * @param boolean $clear Optional argument to force load a new form. * @param bool|string $xpath An optional xpath to search for the fields. * * @return mixed FOFForm object on success, False on error. * * @see FOFForm * @since 2.0 */ protected function loadForm($name, $source, $options = array(), $clear = false, $xpath = false) { // Handle the optional arguments. $options['control'] = isset($options['control']) ? $options['control'] : false; // Create a signature hash. $hash = md5($source . serialize($options)); // Check if we can use a previously loaded form. if (isset($this->_forms[$hash]) && !$clear) { return $this->_forms[$hash]; } // Try to find the name and path of the form to load $formFilename = $this->findFormFilename($source); // No form found? Quit! if ($formFilename === false) { return false; } // Set up the form name and path $source = basename($formFilename, '.xml'); FOFForm::addFormPath(dirname($formFilename)); // Set up field paths $option = $this->input->getCmd('option', 'com_foobar'); $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($option); $view = $this->name; $file_root = $componentPaths['main']; $alt_file_root = $componentPaths['alt']; FOFForm::addFieldPath($file_root . '/fields'); FOFForm::addFieldPath($file_root . '/models/fields'); FOFForm::addFieldPath($alt_file_root . '/fields'); FOFForm::addFieldPath($alt_file_root . '/models/fields'); FOFForm::addHeaderPath($file_root . '/fields/header'); FOFForm::addHeaderPath($file_root . '/models/fields/header'); FOFForm::addHeaderPath($alt_file_root . '/fields/header'); FOFForm::addHeaderPath($alt_file_root . '/models/fields/header'); // Get the form. try { $form = FOFForm::getInstance($name, $source, $options, false, $xpath); if (isset($options['load_data']) && $options['load_data']) { // Get the data for the form. $data = $this->loadFormData(); } else { $data = array(); } // Allows data and form manipulation before preprocessing the form $this->onBeforePreprocessForm($form, $data); // Allow for additional modification of the form, and events to be triggered. // We pass the data because plugins may require it. $this->preprocessForm($form, $data); // Allows data and form manipulation After preprocessing the form $this->onAfterPreprocessForm($form, $data); // Load the data into the form after the plugins have operated. $form->bind($data); } catch (Exception $e) { // The above try-catch statement will catch EVERYTHING, even PhpUnit exceptions while testing if(stripos(get_class($e), 'phpunit') !== false) { throw $e; } else { $this->setError($e->getMessage()); return false; } } // Store the form for later. $this->_forms[$hash] = $form; return $form; } /** * Guesses the best candidate for the path to use for a particular form. * * @param string $source The name of the form file to load, without the .xml extension. * @param array $paths The paths to look into. You can declare this to override the default FOF paths. * * @return mixed A string if the path and filename of the form to load is found, false otherwise. * * @since 2.0 */ public function findFormFilename($source, $paths = array()) { // TODO Should we read from internal variables instead of the input? With a temp instance we have no input $option = $this->input->getCmd('option', 'com_foobar'); $view = $this->name; $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($option); $file_root = $componentPaths['main']; $alt_file_root = $componentPaths['alt']; $template_root = FOFPlatform::getInstance()->getTemplateOverridePath($option); if (empty($paths)) { // Set up the paths to look into // PLEASE NOTE: If you ever change this, please update Model Unit tests, too, since we have to // copy these default folders (we have to add the protocol for the virtual filesystem) $paths = array( // In the template override $template_root . '/' . $view, $template_root . '/' . FOFInflector::singularize($view), $template_root . '/' . FOFInflector::pluralize($view), // In this side of the component $file_root . '/views/' . $view . '/tmpl', $file_root . '/views/' . FOFInflector::singularize($view) . '/tmpl', $file_root . '/views/' . FOFInflector::pluralize($view) . '/tmpl', // In the other side of the component $alt_file_root . '/views/' . $view . '/tmpl', $alt_file_root . '/views/' . FOFInflector::singularize($view) . '/tmpl', $alt_file_root . '/views/' . FOFInflector::pluralize($view) . '/tmpl', // In the models/forms of this side $file_root . '/models/forms', // In the models/forms of the other side $alt_file_root . '/models/forms', ); } $paths = array_unique($paths); // Set up the suffixes to look into $suffixes = array(); $temp_suffixes = FOFPlatform::getInstance()->getTemplateSuffixes(); if (!empty($temp_suffixes)) { foreach ($temp_suffixes as $suffix) { $suffixes[] = $suffix . '.xml'; } } $suffixes[] = '.xml'; // Look for all suffixes in all paths $result = false; $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); foreach ($paths as $path) { foreach ($suffixes as $suffix) { $filename = $path . '/' . $source . $suffix; if ($filesystem->fileExists($filename)) { $result = $filename; break; } } if ($result) { break; } } return $result; } /** * Method to get the data that should be injected in the form. * * @return array The default data is an empty array. * * @since 2.0 */ protected function loadFormData() { if (empty($this->_formData)) { return array(); } else { return $this->_formData; } } /** * Method to allow derived classes to preprocess the form. * * @param FOFForm $form A FOFForm object. * @param mixed &$data The data expected for the form. * @param string $group The name of the plugin group to import (defaults to "content"). * * @return void * * @see FOFFormField * @since 2.0 * @throws Exception if there is an error in the form event. */ protected function preprocessForm(FOFForm &$form, &$data, $group = 'content') { // Import the appropriate plugin group. FOFPlatform::getInstance()->importPlugin($group); // Trigger the form preparation event. $results = FOFPlatform::getInstance()->runPlugins('onContentPrepareForm', array($form, $data)); // Check for errors encountered while preparing the form. if (count($results) && in_array(false, $results, true)) { // Get the last error. $dispatcher = FOFUtilsObservableDispatcher::getInstance(); $error = $dispatcher->getError(); if (!($error instanceof Exception)) { throw new Exception($error); } } } /** * Method to validate the form data. * * @param FOFForm $form The form to validate against. * @param array $data The data to validate. * @param string $group The name of the field group to validate. * * @return mixed Array of filtered data if valid, false otherwise. * * @see JFormRule * @see JFilterInput * @since 2.0 */ public function validateForm($form, $data, $group = null) { // Filter and validate the form data. $data = $form->filter($data); $return = $form->validate($data, $group); // Check for an error. if ($return instanceof Exception) { $this->setError($return->getMessage()); return false; } // Check the validation results. if ($return === false) { // Get the validation messages from the form. foreach ($form->getErrors() as $message) { if ($message instanceof Exception) { $this->setError($message->getMessage()); } else { $this->setError($message); } } return false; } return $data; } /** * Allows the manipulation before the form is loaded * * @param string &$name The name of the form. * @param string &$source The form source. Can be XML string if file flag is set to false. * @param array &$options Optional array of options for the form creation. * @codeCoverageIgnore * * @return void */ public function onBeforeLoadForm(&$name, &$source, &$options) { } /** * Allows the manipulation after the form is loaded * * @param FOFForm $form A FOFForm object. * @param string &$name The name of the form. * @param string &$source The form source. Can be XML string if file flag is set to false. * @param array &$options Optional array of options for the form creation. * @codeCoverageIgnore * * @return void */ public function onAfterLoadForm(FOFForm &$form, &$name, &$source, &$options) { } /** * Allows data and form manipulation before preprocessing the form * * @param FOFForm $form A FOFForm object. * @param array &$data The data expected for the form. * @codeCoverageIgnore * * @return void */ public function onBeforePreprocessForm(FOFForm &$form, &$data) { } /** * Allows data and form manipulation after preprocessing the form * * @param FOFForm $form A FOFForm object. * @param array &$data The data expected for the form. * @codeCoverageIgnore * * @return void */ public function onAfterPreprocessForm(FOFForm &$form, &$data) { } /** * This method can be overriden to automatically do something with the * list results array. You are supposed to modify the list which was passed * in the parameters; DO NOT return a new array! * * @param array &$resultArray An array of objects, each row representing a record * * @return void */ protected function onProcessList(&$resultArray) { } /** * This method runs after an item has been gotten from the database in a read * operation. You can modify it before it's returned to the MVC triad for * further processing. * * @param FOFTable &$record The table instance we fetched * * @return void */ protected function onAfterGetItem(&$record) { try { // Call the behaviors $result = $this->modelDispatcher->trigger('onAfterGetItem', array(&$this, &$record)); } catch (Exception $e) { // Oops, an exception occured! $this->setError($e->getMessage()); } } /** * This method runs before the $data is saved to the $table. Return false to * stop saving. * * @param array &$data The data to save * @param FOFTable &$table The table to save the data to * * @return boolean Return false to prevent saving, true to allow it */ protected function onBeforeSave(&$data, &$table) { // Let's import the plugin only if we're not in CLI (content plugin needs a user) FOFPlatform::getInstance()->importPlugin('content'); try { // Do I have a new record? $key = $table->getKeyName(); $pk = (!empty($data[$key])) ? $data[$key] : 0; $this->_isNewRecord = $pk <= 0; // Bind the data $table->bind($data); // Call the behaviors $result = $this->modelDispatcher->trigger('onBeforeSave', array(&$this, &$data)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } // Call the plugin $name = $this->name; $result = FOFPlatform::getInstance()->runPlugins($this->event_before_save, array($this->option . '.' . $name, &$table, $this->_isNewRecord)); if (in_array(false, $result, true)) { // Plugin failed, return false $this->setError($table->getError()); return false; } } catch (Exception $e) { // Oops, an exception occured! $this->setError($e->getMessage()); return false; } return true; } /** * This method runs after the data is saved to the $table. * * @param FOFTable &$table The table which was saved * * @return boolean */ protected function onAfterSave(&$table) { // Let's import the plugin only if we're not in CLI (content plugin needs a user) FOFPlatform::getInstance()->importPlugin('content'); try { // Call the behaviors $result = $this->modelDispatcher->trigger('onAfterSave', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } $name = $this->name; FOFPlatform::getInstance()->runPlugins($this->event_after_save, array($this->option . '.' . $name, &$table, $this->_isNewRecord)); return true; } catch (Exception $e) { // Oops, an exception occured! $this->setError($e->getMessage()); return false; } } /** * This method runs before the record with key value of $id is deleted from $table * * @param integer &$id The ID of the record being deleted * @param FOFTable &$table The table instance used to delete the record * * @return boolean */ protected function onBeforeDelete(&$id, &$table) { // Let's import the plugin only if we're not in CLI (content plugin needs a user) FOFPlatform::getInstance()->importPlugin('content'); try { $table->load($id); // Call the behaviors $result = $this->modelDispatcher->trigger('onBeforeDelete', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } $name = $this->name; $context = $this->option . '.' . $name; $result = FOFPlatform::getInstance()->runPlugins($this->event_before_delete, array($context, $table)); if (in_array(false, $result, true)) { // Plugin failed, return false $this->setError($table->getError()); return false; } $this->_recordForDeletion = clone $table; } catch (Exception $e) { // Oops, an exception occured! $this->setError($e->getMessage()); return false; } return true; } /** * This method runs after a record with key value $id is deleted * * @param integer $id The id of the record which was deleted * * @return boolean Return false to raise an error, true otherwise */ protected function onAfterDelete($id) { FOFPlatform::getInstance()->importPlugin('content'); // Call the behaviors $result = $this->modelDispatcher->trigger('onAfterDelete', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } try { $name = $this->name; $context = $this->option . '.' . $name; $result = FOFPlatform::getInstance()->runPlugins($this->event_after_delete, array($context, $this->_recordForDeletion)); unset($this->_recordForDeletion); } catch (Exception $e) { // Oops, an exception occured! $this->setError($e->getMessage()); return false; } } /** * This method runs before a record is copied * * @param FOFTable &$table The table instance of the record being copied * * @return boolean True to allow the copy */ protected function onBeforeCopy(&$table) { // Call the behaviors $result = $this->modelDispatcher->trigger('onBeforeCopy', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } return true; } /** * This method runs after a record has been copied * * @param FOFTable &$table The table instance of the record which was copied * * @return boolean True to allow the copy */ protected function onAfterCopy(&$table) { // Call the behaviors $result = $this->modelDispatcher->trigger('onAfterCopy', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } return true; } /** * This method runs before a record is published * * @param FOFTable &$table The table instance of the record being published * * @return boolean True to allow the operation */ protected function onBeforePublish(&$table) { // Call the behaviors $result = $this->modelDispatcher->trigger('onBeforePublish', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } return true; } /** * This method runs after a record has been published * * @param FOFTable &$table The table instance of the record which was published * * @return boolean True to allow the operation */ protected function onAfterPublish(&$table) { // Call the behaviors $result = $this->modelDispatcher->trigger('onAfterPublish', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } return true; } /** * This method runs before a record is hit * * @param FOFTable &$table The table instance of the record being hit * * @return boolean True to allow the operation */ protected function onBeforeHit(&$table) { // Call the behaviors $result = $this->modelDispatcher->trigger('onBeforeHit', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } return true; } /** * This method runs after a record has been hit * * @param FOFTable &$table The table instance of the record which was hit * * @return boolean True to allow the operation */ protected function onAfterHit(&$table) { // Call the behaviors $result = $this->modelDispatcher->trigger('onAfterHit', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } return true; } /** * This method runs before a record is moved * * @param FOFTable &$table The table instance of the record being moved * * @return boolean True to allow the operation */ protected function onBeforeMove(&$table) { // Call the behaviors $result = $this->modelDispatcher->trigger('onBeforeMove', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } return true; } /** * This method runs after a record has been moved * * @param FOFTable &$table The table instance of the record which was moved * * @return boolean True to allow the operation */ protected function onAfterMove(&$table) { // Call the behaviors $result = $this->modelDispatcher->trigger('onAfterMove', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } return true; } /** * This method runs before a table is reordered * * @param FOFTable &$table The table instance being reordered * * @return boolean True to allow the operation */ protected function onBeforeReorder(&$table) { // Call the behaviors $result = $this->modelDispatcher->trigger('onBeforeReorder', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } return true; } /** * This method runs after a table is reordered * * @param FOFTable &$table The table instance which was reordered * * @return boolean True to allow the operation */ protected function onAfterReorder(&$table) { // Call the behaviors $result = $this->modelDispatcher->trigger('onAfterReorder', array(&$this)); if (in_array(false, $result, true)) { // Behavior failed, return false return false; } return true; } /** * Method to get the database driver object * * @return JDatabaseDriver */ public function getDbo() { return $this->_db; } /** * Method to get the model name * * The model name. By default parsed using the classname or it can be set * by passing a $config['name'] in the class constructor * * @return string The name of the model * * @throws Exception */ public function getName() { if (empty($this->name)) { $r = null; if (!preg_match('/Model(.*)/i', get_class($this), $r)) { throw new Exception(JText::_('JLIB_APPLICATION_ERROR_MODEL_GET_NAME'), 500); } $this->name = strtolower($r[1]); } return $this->name; } /** * Method to set the database driver object * * @param JDatabaseDriver $db A JDatabaseDriver based object * * @return void */ public function setDbo($db) { $this->_db = $db; } /** * Method to set model state variables * * @param string $property The name of the property. * @param mixed $value The value of the property to set or null. * * @return mixed The previous value of the property or null if not set. */ public function setState($property, $value = null) { return $this->state->set($property, $value); } /** * Clean the cache * * @param string $group The cache group * @param integer $client_id The ID of the client * * @return void */ protected function cleanCache($group = null, $client_id = 0) { $conf = JFactory::getConfig(); $platformDirs = FOFPlatform::getInstance()->getPlatformBaseDirs(); $options = array( 'defaultgroup' => ($group) ? $group : (isset($this->option) ? $this->option : JFactory::getApplication()->input->get('option')), 'cachebase' => ($client_id) ? $platformDirs['admin'] . '/cache' : $conf->get('cache_path', $platformDirs['public'] . '/cache')); $cache = JCache::getInstance('callback', $options); $cache->clean(); // Trigger the onContentCleanCache event. FOFPlatform::getInstance()->runPlugins($this->event_clean_cache, $options); } } PKY[B fof/model/field/number.phpnuW+Aexact($value); } /** * Perform a between limits match. When $include is true * the condition tested is: * $from <= VALUE <= $to * When $include is false the condition tested is: * $from < VALUE < $to * * @param mixed $from The lowest value to compare to * @param mixed $to The higherst value to compare to * @param boolean $include Should we include the boundaries in the search? * * @return string The SQL where clause for this search */ public function between($from, $to, $include = true) { if ($this->isEmpty($from) || $this->isEmpty($to)) { return ''; } $extra = ''; if ($include) { $extra = '='; } $sql = '((' . $this->getFieldName() . ' >' . $extra . ' ' . $from . ') AND '; $sql .= '(' . $this->getFieldName() . ' <' . $extra . ' ' . $to . '))'; return $sql; } /** * Perform an outside limits match. When $include is true * the condition tested is: * (VALUE <= $from) || (VALUE >= $to) * When $include is false the condition tested is: * (VALUE < $from) || (VALUE > $to) * * @param mixed $from The lowest value of the excluded range * @param mixed $to The higherst value of the excluded range * @param boolean $include Should we include the boundaries in the search? * * @return string The SQL where clause for this search */ public function outside($from, $to, $include = false) { if ($this->isEmpty($from) || $this->isEmpty($to)) { return ''; } $extra = ''; if ($include) { $extra = '='; } $sql = '((' . $this->getFieldName() . ' <' . $extra . ' ' . $from . ') AND '; $sql .= '(' . $this->getFieldName() . ' >' . $extra . ' ' . $to . '))'; return $sql; } /** * Perform an interval match. It's similar to a 'between' match, but the * from and to values are calculated based on $value and $interval: * $value - $interval < VALUE < $value + $interval * * @param integer|float $value The center value of the search space * @param integer|float $interval The width of the search space * @param boolean $include Should I include the boundaries in the search? * * @return string The SQL where clause */ public function interval($value, $interval, $include = true) { if ($this->isEmpty($value)) { return ''; } $from = $value - $interval; $to = $value + $interval; $extra = ''; if ($include) { $extra = '='; } $sql = '((' . $this->getFieldName() . ' >' . $extra . ' ' . $from . ') AND '; $sql .= '(' . $this->getFieldName() . ' <' . $extra . ' ' . $to . '))'; return $sql; } } PKY[@Cfof/model/field/date.phpnuW+AisEmpty($from) || $this->isEmpty($to)) { return ''; } $extra = ''; if ($include) { $extra = '='; } $sql = '((' . $this->getFieldName() . ' >' . $extra . ' ' . $from . ') AND '; $sql .= '(' . $this->getFieldName() . ' <' . $extra . ' ' . $to . '))'; return $sql; } /** * Perform an outside limits match. When $include is true * the condition tested is: * (VALUE <= $from) || (VALUE >= $to) * When $include is false the condition tested is: * (VALUE < $from) || (VALUE > $to) * * @param mixed $from The lowest value of the excluded range * @param mixed $to The higherst value of the excluded range * @param boolean $include Should we include the boundaries in the search? * * @return string The SQL where clause for this search */ public function outside($from, $to, $include = false) { if ($this->isEmpty($from) || $this->isEmpty($to)) { return ''; } $extra = ''; if ($include) { $extra = '='; } $sql = '((' . $this->getFieldName() . ' <' . $extra . ' ' . $from . ') AND '; $sql .= '(' . $this->getFieldName() . ' >' . $extra . ' ' . $to . '))'; return $sql; } /** * Interval date search * * @param string $value The value to search * @param string|array|object $interval The interval. Can be (+1 MONTH or array('value' => 1, 'unit' => 'MONTH', 'sign' => '+')) * @param boolean $include If the borders should be included * * @return string the sql string */ public function interval($value, $interval, $include = true) { if ($this->isEmpty($value) || $this->isEmpty($interval)) { return ''; } $interval = $this->getInterval($interval); if ($interval['sign'] == '+') { $function = 'DATE_ADD'; } else { $function = 'DATE_SUB'; } $extra = ''; if ($include) { $extra = '='; } $sql = '(' . $this->getFieldName() . ' >' . $extra . ' ' . $function; $sql .= '(' . $this->getFieldName() . ', INTERVAL ' . $interval['value'] . ' ' . $interval['unit'] . '))'; return $sql; } /** * Parses an interval –which may be given as a string, array or object– into * a standardised hash array that can then be used bu the interval() method. * * @param string|array|object $interval The interval expression to parse * * @return array The parsed, hash array form of the interval */ protected function getInterval($interval) { if (is_string($interval)) { if (strlen($interval) > 2) { $interval = explode(" ", $interval); $sign = ($interval[0] == '-') ? '-' : '+'; $value = (int) substr($interval[0], 1); $interval = array( 'unit' => $interval[1], 'value' => $value, 'sign' => $sign ); } else { $interval = array( 'unit' => 'MONTH', 'value' => 1, 'sign' => '+' ); } } else { $interval = (array) $interval; } return $interval; } } PKY[ \  fof/model/field/text.phpnuW+Anull_value = ''; } /** * Returns the default search method for this field. * * @return string */ public function getDefaultSearchMethod() { return 'partial'; } /** * Perform a partial match (search in string) * * @param mixed $value The value to compare to * * @return string The SQL where clause for this search */ public function partial($value) { if ($this->isEmpty($value)) { return ''; } return '(' . $this->getFieldName() . ' LIKE ' . $this->_db->quote('%' . $value . '%') . ')'; } /** * Perform an exact match (match string) * * @param mixed $value The value to compare to * * @return string The SQL where clause for this search */ public function exact($value) { if ($this->isEmpty($value)) { return ''; } return '(' . $this->getFieldName() . ' LIKE ' . $this->_db->quote($value) . ')'; } /** * Dummy method; this search makes no sense for text fields * * @param mixed $from Ignored * @param mixed $to Ignored * @param boolean $include Ignored * * @return string Empty string */ public function between($from, $to, $include = true) { return ''; } /** * Dummy method; this search makes no sense for text fields * * @param mixed $from Ignored * @param mixed $to Ignored * @param boolean $include Ignored * * @return string Empty string */ public function outside($from, $to, $include = false) { return ''; } /** * Dummy method; this search makes no sense for text fields * * @param mixed $value Ignored * @param mixed $interval Ignored * @param boolean $include Ignored * * @return string Empty string */ public function interval($value, $interval, $include = true) { return ''; } } PKY[fof/model/field/boolean.phpnuW+A_db = $db; $this->name = $field->name; $this->type = $field->type; $this->table_alias = $table_alias; } /** * Is it a null or otherwise empty value? * * @param mixed $value The value to test for emptiness * * @return boolean */ public function isEmpty($value) { return ($value === $this->null_value) || empty($value); } /** * Returns the default search method for a field. This always returns 'exact' * and you are supposed to override it in specialised classes. The possible * values are exact, partial, between and outside, unless something * different is returned by getSearchMethods(). * * @see self::getSearchMethods() * * @return string */ public function getDefaultSearchMethod() { return 'exact'; } /** * Return the search methods available for this field class, * * @return array */ public function getSearchMethods() { $ignore = array('isEmpty', 'getField', 'getFieldType', '__construct', 'getDefaultSearchMethod', 'getSearchMethods'); $class = new ReflectionClass(__CLASS__); $methods = $class->getMethods(ReflectionMethod::IS_PUBLIC); $tmp = array(); foreach ($methods as $method) { $tmp[] = $method->name; } $methods = $tmp; if ($methods = array_diff($methods, $ignore)) { return $methods; } return array(); } /** * Perform an exact match (equality matching) * * @param mixed $value The value to compare to * * @return string The SQL where clause for this search */ public function exact($value) { if ($this->isEmpty($value)) { return ''; } if (is_array($value)) { $db = FOFPlatform::getInstance()->getDbo(); $value = array_map(array($db, 'quote'), $value); return '(' . $this->getFieldName() . ' IN (' . implode(',', $value) . '))'; } else { return $this->search($value, '='); } } /** * Perform a partial match (usually: search in string) * * @param mixed $value The value to compare to * * @return string The SQL where clause for this search */ abstract public function partial($value); /** * Perform a between limits match (usually: search for a value between * two numbers or a date between two preset dates). When $include is true * the condition tested is: * $from <= VALUE <= $to * When $include is false the condition tested is: * $from < VALUE < $to * * @param mixed $from The lowest value to compare to * @param mixed $to The higherst value to compare to * @param boolean $include Should we include the boundaries in the search? * * @return string The SQL where clause for this search */ abstract public function between($from, $to, $include = true); /** * Perform an outside limits match (usually: search for a value outside an * area or a date outside a preset period). When $include is true * the condition tested is: * (VALUE <= $from) || (VALUE >= $to) * When $include is false the condition tested is: * (VALUE < $from) || (VALUE > $to) * * @param mixed $from The lowest value of the excluded range * @param mixed $to The higherst value of the excluded range * @param boolean $include Should we include the boundaries in the search? * * @return string The SQL where clause for this search */ abstract public function outside($from, $to, $include = false); /** * Perform an interval search (usually: a date interval check) * * @param string $from The value to search * @param string|array|object $interval The interval * * @return string The SQL where clause for this search */ abstract public function interval($from, $interval); /** * Return the SQL where clause for a search * * @param mixed $value The value to search for * @param string $operator The operator to use * * @return string The SQL where clause for this search */ public function search($value, $operator = '=') { if ($this->isEmpty($value)) { return ''; } return '(' . $this->getFieldName() . ' ' . $operator . ' ' . $this->_db->quote($value) . ')'; } /** * Get the field name with the given table alias * * @return string The field name */ public function getFieldName() { $name = $this->_db->qn($this->name); if ($this->table_alias) { $name = $this->_db->qn($this->table_alias) . '.' . $name; } return $name; } /** * Creates a field Object based on the field column type * * @param object $field The field informations * @param array $config The field configuration (like the db object to use) * * @return FOFModelField The Field object */ public static function getField($field, $config = array()) { $type = $field->type; $classType = self::getFieldType($type); $className = 'FOFModelField' . $classType; if (class_exists($className)) { if (isset($config['dbo'])) { $db = $config['dbo']; } else { $db = FOFPlatform::getInstance()->getDbo(); } if (isset($config['table_alias'])) { $table_alias = $config['table_alias']; } else { $table_alias = false; } $field = new $className($db, $field, $table_alias); return $field; } return false; } /** * Get the classname based on the field Type * * @param string $type The type of the field * * @return string the class suffix */ public static function getFieldType($type) { switch ($type) { case 'varchar': case 'text': case 'smalltext': case 'longtext': case 'char': case 'mediumtext': case 'character varying': case 'nvarchar': case 'nchar': $type = 'Text'; break; case 'date': case 'datetime': case 'time': case 'year': case 'timestamp': case 'timestamp without time zone': case 'timestamp with time zone': $type = 'Date'; break; case 'tinyint': case 'smallint': $type = 'Boolean'; break; default: $type = 'Number'; break; } return $type; } } PKY[k66fof/controller/index.htmlnuW+APKY[Ԅ$ۡfof/controller/controller.phpnuW+AgetCmd('option', 'com_foobar'); $config['view'] = !is_null($view) ? $view : $input->getCmd('view', 'cpanel'); // Get the class base name, e.g. FoobarController $classBaseName = ucfirst(str_replace('com_', '', $config['option'])) . 'Controller'; // Get the class name suffixes, in the order to be searched for: plural, singular, 'default' $classSuffixes = array( FOFInflector::pluralize($config['view']), FOFInflector::singularize($config['view']), 'default' ); // Get the path names for the component $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($config['option']); $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); // Look for the best classname match foreach ($classSuffixes as $suffix) { $className = $classBaseName . ucfirst($suffix); if (class_exists($className)) { // The class is already loaded. We have a match! break; } // The class is not already loaded. Try to find and load it. $searchPaths = array( $componentPaths['main'] . '/controllers', $componentPaths['admin'] . '/controllers' ); // If we have a searchpath in the configuration please search it first if (array_key_exists('searchpath', $config)) { array_unshift($searchPaths, $config['searchpath']); } else { $configProvider = new FOFConfigProvider; $searchPath = $configProvider->get($config['option'] . '.views.' . FOFInflector::singularize($config['view']) . '.config.searchpath', null); if ($searchPath) { array_unshift($searchPaths, $componentPaths['admin'] . '/' . $searchPath); array_unshift($searchPaths, $componentPaths['main'] . '/' . $searchPath); } } /** * Try to find the path to this file. First try to find the * format-specific controller file, e.g. foobar.json.php for * format=json, then the regular one-size-fits-all controller */ $format = $input->getCmd('format', 'html'); $path = null; if (!empty($format)) { $path = $filesystem->pathFind( $searchPaths, strtolower($suffix) . '.' . strtolower($format) . '.php' ); } if (!$path) { $path = $filesystem->pathFind( $searchPaths, strtolower($suffix) . '.php' ); } // The path is found. Load the file and make sure the expected class name exists. if ($path) { require_once $path; if (class_exists($className)) { // The class was loaded successfully. We have a match! break; } } } if (!class_exists($className)) { // If no specialised class is found, instantiate the generic FOFController $className = 'FOFController'; } $instance = new $className($config); return $instance; } /** * Public constructor of the Controller class * * @param array $config Optional configuration parameters */ public function __construct($config = array()) { // Make sure $config is an array if (is_object($config)) { $config = (array) $config; } elseif (!is_array($config)) { $config = array(); } $this->methods = array(); $this->message = null; $this->messageType = 'message'; $this->paths = array(); $this->redirect = null; $this->taskMap = array(); // Cache the config $this->config = $config; // Get the input for this MVC triad if (array_key_exists('input', $config)) { $input = $config['input']; } else { $input = null; } if (array_key_exists('input_options', $config)) { $input_options = $config['input_options']; } else { $input_options = array(); } if ($input instanceof FOFInput) { $this->input = $input; } else { $this->input = new FOFInput($input, $input_options); } // Load the configuration provider $this->configProvider = new FOFConfigProvider; // Determine the methods to exclude from the base class. $xMethods = get_class_methods('FOFController'); // Some methods must always be considered valid tasks $iMethods = array('accesspublic', 'accessregistered', 'accessspecial', 'add', 'apply', 'browse', 'cancel', 'copy', 'edit', 'orderdown', 'orderup', 'publish', 'read', 'remove', 'save', 'savenew', 'saveorder', 'unpublish', 'display', 'archive', 'trash'); // Get the public methods in this class using reflection. $r = new ReflectionClass($this); $rMethods = $r->getMethods(ReflectionMethod::IS_PUBLIC); foreach ($rMethods as $rMethod) { $mName = $rMethod->getName(); // Add default display method if not explicitly declared. if (!in_array($mName, $xMethods) || in_array($mName, $iMethods)) { $this->methods[] = strtolower($mName); // Auto register the methods as tasks. $this->taskMap[strtolower($mName)] = $mName; } } // Get the default values for the component and view names $classNameParts = FOFInflector::explode(get_class($this)); if (count($classNameParts) == 3) { $defComponent = "com_" . $classNameParts[0]; $defView = $classNameParts[2]; } else { $defComponent = 'com_foobar'; $defView = 'cpanel'; } $this->component = $this->input->get('option', $defComponent, 'cmd'); $this->view = $this->input->get('view', $defView, 'cmd'); $this->layout = $this->input->get('layout', null, 'cmd'); // Overrides from the config if (array_key_exists('option', $config)) { $this->component = $config['option']; } if (array_key_exists('view', $config)) { $this->view = $config['view']; } if (array_key_exists('layout', $config)) { $this->layout = $config['layout']; } $this->layout = $this->configProvider->get($this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.layout', $this->layout); $this->input->set('option', $this->component); // Set the bareComponent variable $this->bareComponent = str_replace('com_', '', strtolower($this->component)); // Set the $name variable $this->name = $this->bareComponent; // Set the basePath variable $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($this->component); $basePath = $componentPaths['main']; if (array_key_exists('base_path', $config)) { $basePath = $config['base_path']; } $altBasePath = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.base_path', null ); if (!is_null($altBasePath)) { $platformDirs = FOFPlatform::getInstance()->getPlatformBaseDirs(); $basePath = $platformDirs['public'] . '/' . $altBasePath; } $this->basePath = $basePath; // If the default task is set, register it as such $defaultTask = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.default_task', 'display' ); if (array_key_exists('default_task', $config)) { $this->registerDefaultTask($config['default_task']); } else { $this->registerDefaultTask($defaultTask); } // Set the models prefix if (empty($this->model_prefix)) { if (array_key_exists('model_prefix', $config)) { // User-defined prefix $this->model_prefix = $config['model_prefix']; } else { $this->model_prefix = $this->name . 'Model'; $this->model_prefix = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.model_prefix', $this->model_prefix ); } } // Set the default model search path if (array_key_exists('model_path', $config)) { // User-defined dirs $this->addModelPath($config['model_path'], $this->model_prefix); } else { $modelPath = $this->basePath . '/models'; $altModelPath = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.model_path', null ); if (!is_null($altModelPath)) { $modelPath = $this->basePath . '/' . $altModelPath; } $this->addModelPath($modelPath, $this->model_prefix); } // Set the default view search path if (array_key_exists('view_path', $config)) { // User-defined dirs $this->setPath('view', $config['view_path']); } else { $viewPath = $this->basePath . '/views'; $altViewPath = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.view_path', null ); if (!is_null($altViewPath)) { $viewPath = $this->basePath . '/' . $altViewPath; } $this->setPath('view', $viewPath); } // Set the default view. if (array_key_exists('default_view', $config)) { $this->default_view = $config['default_view']; } else { if (empty($this->default_view)) { $this->default_view = $this->getName(); } $this->default_view = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.default_view', $this->default_view ); } // Set the CSRF protection if (array_key_exists('csrf_protection', $config)) { $this->csrfProtection = $config['csrf_protection']; } $this->csrfProtection = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.csrf_protection', $this->csrfProtection ); // Set any model/view name overrides if (array_key_exists('viewName', $config)) { $this->setThisViewName($config['viewName']); } else { $overrideViewName = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.viewName', null ); if ($overrideViewName) { $this->setThisViewName($overrideViewName); } } if (array_key_exists('modelName', $config)) { $this->setThisModelName($config['modelName']); } else { $overrideModelName = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.modelName', null ); if ($overrideModelName) { $this->setThisModelName($overrideModelName); } } // Caching if (array_key_exists('cacheableTasks', $config)) { if (is_array($config['cacheableTasks'])) { $this->cacheableTasks = $config['cacheableTasks']; } } else { $cacheableTasks = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.cacheableTasks', null ); if ($cacheableTasks) { $cacheableTasks = explode(',', $cacheableTasks); if (count($cacheableTasks)) { $temp = array(); foreach ($cacheableTasks as $t) { $temp[] = trim($t); } $temp = array_unique($temp); $this->cacheableTasks = $temp; } } } // Bit mask for auto routing on setRedirect $this->autoRouting = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.config.autoRouting', $this->autoRouting ); if (array_key_exists('autoRouting', $config)) { $this->autoRouting = $config['autoRouting']; } // Apply task map $taskmap = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.taskmap' ); if (is_array($taskmap) && !empty($taskmap)) { foreach ($taskmap as $aliasedtask => $realmethod) { $this->registerTask($aliasedtask, $realmethod); } } } /** * Adds to the stack of model paths in LIFO order. * * @param mixed $path The directory (string) , or list of directories (array) to add. * @param string $prefix A prefix for models * * @return void */ public static function addModelPath($path, $prefix = '') { FOFModel::addIncludePath($path, $prefix); } /** * Adds to the search path for templates and resources. * * @param string $type The path type (e.g. 'model', 'view'). * @param mixed $path The directory string or stream array to search. * * @return FOFController A FOFController object to support chaining. */ protected function addPath($type, $path) { // Just force path to array settype($path, 'array'); $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); if (!isset($this->paths[$type])) { $this->paths[$type] = array(); } // Loop through the path directories foreach ($path as $dir) { // No surrounding spaces allowed! $dir = rtrim($filesystem->pathCheck($dir, '/'), '/') . '/'; // Add to the top of the search dirs array_unshift($this->paths[$type], $dir); } return $this; } /** * Add one or more view paths to the controller's stack, in LIFO order. * * @param mixed $path The directory (string) or list of directories (array) to add. * * @return FOFController This object to support chaining. */ public function addViewPath($path) { $this->addPath('view', $path); return $this; } /** * Authorisation check * * @param string $task The ACO Section Value to check access on. * * @return boolean True if authorised * * @deprecated 2.0 Use JAccess instead. */ public function authorise($task) { FOFPlatform::getInstance()->logDeprecated(__CLASS__ . '::' .__METHOD__ . ' is deprecated. Use checkACL() instead.'); return true; } /** * Create the filename for a resource. * * @param string $type The resource type to create the filename for. * @param array $parts An associative array of filename information. Optional. * * @return string The filename. */ protected static function createFileName($type, $parts = array()) { $filename = ''; switch ($type) { case 'controller': if (!empty($parts['format'])) { if ($parts['format'] == 'html') { $parts['format'] = ''; } else { $parts['format'] = '.' . $parts['format']; } } else { $parts['format'] = ''; } $filename = strtolower($parts['name'] . $parts['format'] . '.php'); break; case 'view': if (!empty($parts['type'])) { $parts['type'] = '.' . $parts['type']; } else { $parts['type'] = ''; } $filename = strtolower($parts['name'] . '/view' . $parts['type'] . '.php'); break; } return $filename; } /** * Executes a given controller task. The onBefore and onAfter * methods are called automatically if they exist. * * @param string $task The task to execute, e.g. "browse" * * @throws Exception Exception thrown if the onBefore returns false * * @return null|bool False on execution failure */ public function execute($task) { $this->task = $task; $method_name = 'onBefore' . ucfirst($task); if (!method_exists($this, $method_name)) { $result = $this->onBeforeGenericTask($task); } elseif (method_exists($this, $method_name)) { $result = $this->$method_name(); } else { $result = true; } if ($result) { $plugin_event = FOFInflector::camelize('on before ' . $this->bareComponent . ' controller ' . $this->view . ' ' . $task); $plugin_result = FOFPlatform::getInstance()->runPlugins($plugin_event, array(&$this, &$this->input)); if (in_array(false, $plugin_result, true)) { $result = false; } } if (!$result) { throw new Exception(JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 403); } // Do not allow the display task to be directly called $task = strtolower($task); if (isset($this->taskMap[$task])) { $doTask = $this->taskMap[$task]; } elseif (isset($this->taskMap['__default'])) { $doTask = $this->taskMap['__default']; } else { $doTask = null; } if ($doTask == 'display') { FOFPlatform::getInstance()->setHeader('Status', '400 Bad Request', true); throw new Exception('Bad Request', 400); } $this->doTask = $doTask; $ret = $this->$doTask(); $method_name = 'onAfter' . ucfirst($task); if (method_exists($this, $method_name)) { $result = $this->$method_name(); } else { $result = true; } if ($result) { $plugin_event = FOFInflector::camelize('on after ' . $this->bareComponent . ' controller ' . $this->view . ' ' . $task); $plugin_result = FOFPlatform::getInstance()->runPlugins($plugin_event, array(&$this, &$this->input, &$ret)); if (in_array(false, $plugin_result, true)) { $result = false; } } if (!$result) { throw new Exception(JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN'), 403); } return $ret; } /** * Default task. Assigns a model to the view and asks the view to render * itself. * * YOU MUST NOT USETHIS TASK DIRECTLY IN A URL. It is supposed to be * used ONLY inside your code. In the URL, use task=browse instead. * * @param bool $cachable Is this view cacheable? * @param bool $urlparams Add your safe URL parameters (see further down in the code) * * @return bool */ public function display($cachable = false, $urlparams = false) { $document = FOFPlatform::getInstance()->getDocument(); if ($document instanceof JDocument) { $viewType = $document->getType(); } else { $viewType = $this->input->getCmd('format', 'html'); } $view = $this->getThisView(); // Get/Create the model if ($model = $this->getThisModel()) { // Push the model into the view (as default) $view->setModel($model, true); } // Set the layout $view->setLayout(is_null($this->layout) ? 'default' : $this->layout); // Display the view $conf = FOFPlatform::getInstance()->getConfig(); if (FOFPlatform::getInstance()->isFrontend() && $cachable && ($viewType != 'feed') && $conf->get('caching') >= 1) { // Get a JCache object $option = $this->input->get('option', 'com_foobar', 'cmd'); $cache = JFactory::getCache($option, 'view'); // Set up a cache ID based on component, view, task and user group assignment $user = FOFPlatform::getInstance()->getUser(); if ($user->guest) { $groups = array(); } else { $groups = $user->groups; } // Set up safe URL parameters if (!is_array($urlparams)) { $urlparams = array( 'option' => 'CMD', 'view' => 'CMD', 'task' => 'CMD', 'format' => 'CMD', 'layout' => 'CMD', 'id' => 'INT', ); } if (is_array($urlparams)) { $app = JFactory::getApplication(); $registeredurlparams = null; if (version_compare(JVERSION, '3.0', 'ge')) { if (property_exists($app, 'registeredurlparams')) { $registeredurlparams = $app->registeredurlparams; } } else { $registeredurlparams = $app->get('registeredurlparams'); } if (empty($registeredurlparams)) { $registeredurlparams = new stdClass; } foreach ($urlparams AS $key => $value) { // Add your safe url parameters with variable type as value {@see JFilterInput::clean()}. $registeredurlparams->$key = $value; } if (version_compare(JVERSION, '3.0', 'ge')) { $app->registeredurlparams = $registeredurlparams; } else { $app->set('registeredurlparams', $registeredurlparams); } } // Create the cache ID after setting the registered URL params, as they are used to generate the ID $cacheId = md5(serialize(array(JCache::makeId(), $view->getName(), $this->doTask, $groups))); // Get the cached view or cache the current view $cache->get($view, 'display', $cacheId); } else { // Display without caching $view->display(); } return true; } /** * Implements a default browse task, i.e. read a bunch of records and send * them to the browser. * * @return boolean */ public function browse() { if ($this->input->get('savestate', -999, 'int') == -999) { $this->input->set('savestate', true); } // Do I have a form? $model = $this->getThisModel(); if (empty($this->layout)) { $formname = 'form.default'; } else { $formname = 'form.' . $this->layout; } $model->setState('form_name', $formname); $form = $model->getForm(); if ($form !== false) { $this->hasForm = true; } $this->display(in_array('browse', $this->cacheableTasks)); return true; } /** * Single record read. The id set in the request is passed to the model and * then the item layout is used to render the result. * * @return bool */ public function read() { // Load the model $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } // Set the layout to item, if it's not set in the URL if (is_null($this->layout)) { $this->layout = 'item'; } // Do I have a form? $model->setState('form_name', 'form.' . $this->layout); $item = $model->getItem(); if (!($item instanceof FOFTable)) { return false; } $itemKey = $item->getKeyName(); if ($item->$itemKey != $model->getId()) { return false; } $formData = is_object($item) ? $item->getData() : array(); $form = $model->getForm($formData); if ($form !== false) { $this->hasForm = true; } // Display $this->display(in_array('read', $this->cacheableTasks)); return true; } /** * Single record add. The form layout is used to present a blank page. * * @return false|void */ public function add() { // Load and reset the model $model = $this->getThisModel(); $model->reset(); // Set the layout to form, if it's not set in the URL if (is_null($this->layout)) { $this->layout = 'form'; } // Do I have a form? $model->setState('form_name', 'form.' . $this->layout); $item = $model->getItem(); if (!($item instanceof FOFTable)) { return false; } $formData = is_object($item) ? $item->getData() : array(); $form = $model->getForm($formData); if ($form !== false) { $this->hasForm = true; } // Display $this->display(in_array('add', $this->cacheableTasks)); } /** * Single record edit. The ID set in the request is passed to the model, * then the form layout is used to edit the result. * * @return bool */ public function edit() { // Load the model $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $status = $model->checkout(); if (!$status) { // Redirect on error if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . FOFInflector::pluralize($this->view) . $this->getItemidURLSuffix(); $this->setRedirect($url, $model->getError(), 'error'); return false; } // Set the layout to form, if it's not set in the URL if (is_null($this->layout)) { $this->layout = 'form'; } // Do I have a form? $model->setState('form_name', 'form.' . $this->layout); $item = $model->getItem(); if (!($item instanceof FOFTable)) { return false; } $itemKey = $item->getKeyName(); if ($item->$itemKey != $model->getId()) { return false; } $formData = is_object($item) ? $item->getData() : array(); $form = $model->getForm($formData); if ($form !== false) { $this->hasForm = true; } // Display $this->display(in_array('edit', $this->cacheableTasks)); return true; } /** * Save the incoming data and then return to the Edit task * * @return bool */ public function apply() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } $model = $this->getThisModel(); $result = $this->applySave(); // Redirect to the edit task if ($result) { $id = $this->input->get('id', 0, 'int'); $textkey = strtoupper($this->component) . '_LBL_' . strtoupper($this->view) . '_SAVED'; if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . $this->view . '&task=edit&id=' . $id . $this->getItemidURLSuffix(); $this->setRedirect($url, JText::_($textkey)); } return $result; } /** * Duplicates selected items * * @return bool */ public function copy() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $status = $model->copy(); // Redirect if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . FOFInflector::pluralize($this->view) . $this->getItemidURLSuffix(); if (!$status) { $this->setRedirect($url, $model->getError(), 'error'); return false; } else { FOFPlatform::getInstance()->setHeader('Status', '201 Created', true); $this->setRedirect($url); return true; } } /** * Save the incoming data and then return to the Browse task * * @return bool */ public function save() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } $result = $this->applySave(); // Redirect to the display task if ($result) { $textkey = strtoupper($this->component) . '_LBL_' . strtoupper($this->view) . '_SAVED'; if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . FOFInflector::pluralize($this->view) . $this->getItemidURLSuffix(); $this->setRedirect($url, JText::_($textkey)); } return $result; } /** * Save the incoming data and then return to the Add task * * @return bool */ public function savenew() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } $result = $this->applySave(); // Redirect to the display task if ($result) { $textkey = strtoupper($this->component) . '_LBL_' . strtoupper($this->view) . '_SAVED'; if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . $this->view . '&task=add' . $this->getItemidURLSuffix(); $this->setRedirect($url, JText::_($textkey)); } return $result; } /** * Cancel the edit, check in the record and return to the Browse task * * @return bool */ public function cancel() { $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $model->checkin(); // Remove any saved data JFactory::getSession()->set($model->getHash() . 'savedata', null); // Redirect to the display task if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . FOFInflector::pluralize($this->view) . $this->getItemidURLSuffix(); $this->setRedirect($url); return true; } /** * Sets the access to public. Joomla! 1.5 compatibility. * * @return bool * * @deprecated since 2.0 */ public function accesspublic() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } return $this->setaccess(0); } /** * Sets the access to registered. Joomla! 1.5 compatibility. * * @return bool * * @deprecated since 2.0 */ public function accessregistered() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } return $this->setaccess(1); } /** * Sets the access to special. Joomla! 1.5 compatibility. * * @return bool * * @deprecated since 2.0 */ public function accessspecial() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } return $this->setaccess(2); } /** * Publish (set enabled = 1) an item. * * @return bool */ public function publish() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } return $this->setstate(1); } /** * Unpublish (set enabled = 0) an item. * * @return bool */ public function unpublish() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } return $this->setstate(0); } /** * Archive (set enabled = 2) an item. * * @return bool */ public function archive() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } return $this->setstate(2); } /** * Trash (set enabled = -2) an item. * * @return bool */ public function trash() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } return $this->setstate(-2); } /** * Saves the order of the items * * @return bool */ public function saveorder() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $ordering = $model->getTable()->getColumnAlias('ordering'); $ids = $model->getIds(); $orders = $this->input->get('order', array(), 'array'); if ($n = count($ids)) { for ($i = 0; $i < $n; $i++) { $model->setId($ids[$i]); $neworder = (int) $orders[$i]; $item = $model->getItem(); if (!($item instanceof FOFTable)) { return false; } $key = $item->getKeyName(); if ($item->$key == $ids[$i]) { $item->$ordering = $neworder; $model->save($item); } } } $status = $model->reorder(); // Redirect if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . FOFInflector::pluralize($this->view) . $this->getItemidURLSuffix(); $this->setRedirect($url); return $status; } /** * Moves selected items one position down the ordering list * * @return bool */ public function orderdown() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $status = $model->move(1); // Redirect if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . FOFInflector::pluralize($this->view) . $this->getItemidURLSuffix(); if (!$status) { $this->setRedirect($url, $model->getError(), 'error'); } else { $this->setRedirect($url); } return $status; } /** * Moves selected items one position up the ordering list * * @return bool */ public function orderup() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $status = $model->move(-1); // Redirect if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . FOFInflector::pluralize($this->view) . $this->getItemidURLSuffix(); if (!$status) { $this->setRedirect($url, $model->getError(), 'error'); } else { $this->setRedirect($url); } return $status; } /** * Delete selected item(s) * * @return bool */ public function remove() { // CSRF prevention if ($this->csrfProtection) { $this->_csrfProtection(); } $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $status = $model->delete(); // Redirect if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . FOFInflector::pluralize($this->view) . $this->getItemidURLSuffix(); if (!$status) { $this->setRedirect($url, $model->getError(), 'error'); } else { $this->setRedirect($url); } return $status; } /** * Redirects the browser or returns false if no redirect is set. * * @return boolean False if no redirect exists. */ public function redirect() { if ($this->redirect) { $app = JFactory::getApplication(); $app->enqueueMessage($this->message, $this->messageType); $app->redirect($this->redirect); return true; } return false; } /** * Returns true if there is a redirect set in the controller * * @return boolean */ public function hasRedirect() { return !empty($this->redirect); } /** * Register the default task to perform if a mapping is not found. * * @param string $method The name of the method in the derived class to perform if a named task is not found. * * @return FOFController A FOFController object to support chaining. */ public function registerDefaultTask($method) { $this->registerTask('__default', $method); return $this; } /** * Register (map) a task to a method in the class. * * @param string $task The task. * @param string $method The name of the method in the derived class to perform for this task. * * @return FOFController A FOFController object to support chaining. */ public function registerTask($task, $method) { if (in_array(strtolower($method), $this->methods)) { $this->taskMap[strtolower($task)] = $method; } return $this; } /** * Unregister (unmap) a task in the class. * * @param string $task The task. * * @return FOFController This object to support chaining. */ public function unregisterTask($task) { unset($this->taskMap[strtolower($task)]); return $this; } /** * Sets the internal message that is passed with a redirect * * @param string $text Message to display on redirect. * @param string $type Message type. Optional, defaults to 'message'. * * @return string Previous message */ public function setMessage($text, $type = 'message') { $previous = $this->message; $this->message = $text; $this->messageType = $type; return $previous; } /** * Sets an entire array of search paths for resources. * * @param string $type The type of path to set, typically 'view' or 'model'. * @param string $path The new set of search paths. If null or false, resets to the current directory only. * * @return void */ protected function setPath($type, $path) { // Clear out the prior search dirs $this->paths[$type] = array(); // Actually add the user-specified directories $this->addPath($type, $path); } /** * Registers a redirection with an optional message. The redirection is * carried out when you use the redirect method. * * @param string $url The URL to redirect to * @param string $msg The message to be pushed to the application * @param string $type The message type to be pushed to the application, e.g. 'error' * * @return FOFController This object to support chaining */ public function setRedirect($url, $msg = null, $type = null) { // Do the logic only if we're parsing a raw url (index.php?foo=bar&etc=etc) if (strpos($url, 'index.php') === 0) { $isAdmin = FOFPlatform::getInstance()->isBackend(); $auto = false; if (($this->autoRouting == 2 || $this->autoRouting == 3) && $isAdmin) { $auto = true; } elseif (($this->autoRouting == 1 || $this->autoRouting == 3) && !$isAdmin) { $auto = true; } if ($auto) { $url = JRoute::_($url, false); } } $this->redirect = $url; if ($msg !== null) { // Controller may have set this directly $this->message = $msg; } // Ensure the type is not overwritten by a previous call to setMessage. if (empty($type)) { if (empty($this->messageType)) { $this->messageType = 'message'; } } // If the type is explicitly set, set it. else { $this->messageType = $type; } return $this; } /** * Sets the published state (the enabled field) of the selected item(s) * * @param integer $state The desired state. 0 is unpublished, 1 is published. * * @return bool */ final protected function setstate($state = 0) { $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $status = $model->publish($state); // Redirect if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . FOFInflector::pluralize($this->view) . $this->getItemidURLSuffix(); if (!$status) { $this->setRedirect($url, $model->getError(), 'error'); } else { $this->setRedirect($url); } return $status; } /** * Sets the access level of the selected item(s). * * @param integer $level The desired viewing access level ID * * @return bool */ final protected function setaccess($level = 0) { $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $id = $model->getId(); $item = $model->getItem(); if (!($item instanceof FOFTable)) { return false; } $key = $item->getKeyName(); $loadedid = $item->$key; if ($id == $loadedid) { $item->access = $level; $status = $model->save($item); } else { $status = false; } // Redirect if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } $url = !empty($customURL) ? $customURL : 'index.php?option=' . $this->component . '&view=' . FOFInflector::pluralize($this->view) . $this->getItemidURLSuffix(); if (!$status) { $this->setRedirect($url, $model->getError(), 'error'); } else { $this->setRedirect($url); } return $status; } /** * Common method to handle apply and save tasks * * @return boolean Returns true on success */ final protected function applySave() { // Load the model $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $id = $model->getId(); $data = $this->input->getData(); if (!$this->onBeforeApplySave($data)) { return false; } // Set the layout to form, if it's not set in the URL if (is_null($this->layout)) { $this->layout = 'form'; } // Do I have a form? $model->setState('form_name', 'form.' . $this->layout); $status = $model->save($data); if ($status && ($id != 0)) { FOFPlatform::getInstance()->setHeader('Status', '201 Created', true); // Try to check-in the record if it's not a new one $status = $model->checkin(); if ($status) { $status = $this->onAfterApplySave(); } } $this->input->set('id', $model->getId()); if (!$status) { // Redirect on error $id = $model->getId(); if ($customURL = $this->input->get('returnurl', '', 'string')) { $customURL = base64_decode($customURL); } if (!empty($customURL)) { $url = $customURL; } elseif ($id != 0) { $url = 'index.php?option=' . $this->component . '&view=' . $this->view . '&task=edit&id=' . $id . $this->getItemidURLSuffix(); } else { $url = 'index.php?option=' . $this->component . '&view=' . $this->view . '&task=add' . $this->getItemidURLSuffix(); } $this->setRedirect($url, '
  • ' . implode('
  • ', $model->getErrors()) . '
  • ', 'error'); return false; } else { $session = JFactory::getSession(); $session->set($model->getHash() . 'savedata', null); return true; } } /** * Returns the default model associated with the current view * * @param array $config Configuration variables for the model * * @return FOFModel The global instance of the model (singleton) */ final public function getThisModel($config = array()) { if (!is_object($this->_modelObject)) { // Make sure $config is an array if (is_object($config)) { $config = (array) $config; } elseif (!is_array($config)) { $config = array(); } if (!empty($this->modelName)) { $parts = FOFInflector::explode($this->modelName); $modelName = ucfirst(array_pop($parts)); $prefix = FOFInflector::implode($parts); } else { $prefix = ucfirst($this->bareComponent) . 'Model'; $modelName = ucfirst(FOFInflector::pluralize($this->view)); } if (!array_key_exists('input', $config) || !($config['input'] instanceof FOFInput)) { $config['input'] = $this->input; } $this->_modelObject = $this->getModel($modelName, $prefix, $config); } return $this->_modelObject; } /** * Method to get a model object, loading it if required. * * @param string $name The model name. Optional. * @param string $prefix The class prefix. Optional. * @param array $config Configuration array for model. Optional. * * @return object The model. */ public function getModel($name = '', $prefix = '', $config = array()) { // Make sure $config is an array if (is_object($config)) { $config = (array) $config; } elseif (!is_array($config) || empty($config)) { // array_merge is required to create a copy instead of assigning by reference $config = array_merge($this->config); } if (empty($name)) { $name = $this->getName(); } if (empty($prefix)) { $prefix = $this->model_prefix; } if ($model = $this->createModel($name, $prefix, $config)) { // Task is a reserved state $model->setState('task', $this->task); // Let's get the application object and set menu information if it's available if (!FOFPlatform::getInstance()->isCli()) { $app = JFactory::getApplication(); $menu = $app->getMenu(); if (is_object($menu)) { if ($item = $menu->getActive()) { $params = $menu->getParams($item->id); // Set default state data $model->setState('parameters.menu', $params); } } } } return $model; } /** * Returns current view object * * @param array $config Configuration variables for the model * * @return FOFView The global instance of the view object (singleton) */ final public function getThisView($config = array()) { if (!is_object($this->_viewObject)) { // Make sure $config is an array if (is_object($config)) { $config = (array) $config; } elseif (!is_array($config) || empty($config)) { // array_merge is required to create a copy instead of assigning by reference $config = array_merge($this->config); } $prefix = null; $viewName = null; $viewType = null; if (!empty($this->viewName)) { $parts = FOFInflector::explode($this->viewName); $viewName = ucfirst(array_pop($parts)); $prefix = FOFInflector::implode($parts); } else { $prefix = ucfirst($this->bareComponent) . 'View'; $viewName = ucfirst($this->view); } $document = FOFPlatform::getInstance()->getDocument(); if ($document instanceof JDocument) { $viewType = $document->getType(); } else { $viewType = $this->input->getCmd('format', 'html'); } if (($viewType == 'html') && $this->hasForm) { $viewType = 'form'; } if (!array_key_exists('input', $config) || !($config['input'] instanceof FOFInput)) { $config['input'] = $this->input; } $config['input']->set('base_path', $this->basePath); $this->_viewObject = $this->getView($viewName, $viewType, $prefix, $config); } return $this->_viewObject; } /** * Method to get the controller name * * The dispatcher name is set by default parsed using the classname, or it can be set * by passing a $config['name'] in the class constructor * * @throws Exception * * @return string The name of the dispatcher */ public function getName() { if (empty($this->name)) { if (empty($this->bareComponent)) { $r = null; if (!preg_match('/(.*)Controller/i', get_class($this), $r)) { throw new Exception(JText::_('JLIB_APPLICATION_ERROR_CONTROLLER_GET_NAME'), 500); } $this->name = strtolower($r[1]); } else { $this->name = $this->bareComponent; } } return $this->name; } /** * Get the last task that is being performed or was most recently performed. * * @return string The task that is being performed or was most recently performed. */ public function getTask() { return $this->task; } /** * Gets the available tasks in the controller. * * @return array Array[i] of task names. */ public function getTasks() { return $this->methods; } /** * Method to get a reference to the current view and load it if necessary. * * @param string $name The view name. Optional, defaults to the controller name. * @param string $type The view type. Optional. * @param string $prefix The class prefix. Optional. * @param array $config Configuration array for view. Optional. * * @throws Exception * * @return FOFView Reference to the view or an error. */ public function getView($name = '', $type = '', $prefix = '', $config = array()) { // Make sure $config is an array if (is_object($config)) { $config = (array) $config; } elseif (!is_array($config)) { $config = array(); } if (empty($name)) { $name = $this->getName(); } if (empty($prefix)) { $prefix = $this->getName() . 'View'; } $signature = md5($name . $type . $prefix . serialize($config)); if (empty($this->viewsCache[$signature])) { if ($view = $this->createView($name, $prefix, $type, $config)) { $this->viewsCache[$signature] = & $view; } else { throw new Exception(JText::sprintf('JLIB_APPLICATION_ERROR_VIEW_NOT_FOUND', $name, $type, $prefix), 500); } } return $this->viewsCache[$signature]; } /** * Creates a new model object * * @param string $name The name of the model class, e.g. Items * @param string $prefix The prefix of the model class, e.g. FoobarModel * @param array $config The configuration parameters for the model class * * @return FOFModel The model object */ protected function createModel($name, $prefix = '', $config = array()) { // Make sure $config is an array if (is_object($config)) { $config = (array) $config; } elseif (!is_array($config)) { $config = array(); } $result = null; // Clean the model name $modelName = preg_replace('/[^A-Z0-9_]/i', '', $name); $classPrefix = preg_replace('/[^A-Z0-9_]/i', '', $prefix); $result = FOFModel::getAnInstance($modelName, $classPrefix, $config); return $result; } /** * Method to load and return a model object. * * @param string $name The name of the model. * @param string $prefix Optional model prefix. * @param array $config Configuration array for the model. Optional. * * @return mixed Model object on success; otherwise null */ protected function &_createModel($name, $prefix = '', $config = array()) { FOFPlatform::getInstance()->logDeprecated(__CLASS__ . '::' .__METHOD__ . ' is deprecated. Use createModel() instead.'); return $this->createModel($name, $prefix, $config); } /** * Creates a View object instance and returns it * * @param string $name The name of the view, e.g. Items * @param string $prefix The prefix of the view, e.g. FoobarView * @param string $type The type of the view, usually one of Html, Raw, Json or Csv * @param array $config The configuration variables to use for creating the view * * @return FOFView */ protected function createView($name, $prefix = '', $type = '', $config = array()) { // Make sure $config is an array if (is_object($config)) { $config = (array) $config; } elseif (!is_array($config)) { $config = array(); } $result = null; // Clean the view name $viewName = preg_replace('/[^A-Z0-9_]/i', '', $name); $classPrefix = preg_replace('/[^A-Z0-9_]/i', '', $prefix); $viewType = preg_replace('/[^A-Z0-9_]/i', '', $type); if (!isset($config['input'])) { $config['input'] = $this->input; } if (($config['input'] instanceof FOFInput)) { $tmpInput = $config['input']; } else { $tmpInput = new FOFInput($config['input']); } // Guess the component name and view if (!empty($prefix)) { preg_match('/(.*)View$/', $prefix, $m); $component = 'com_' . strtolower($m[1]); } else { $component = ''; } if (empty($component) && array_key_exists('input', $config)) { $component = $tmpInput->get('option', $component, 'cmd'); } if (array_key_exists('option', $config)) { if ($config['option']) { $component = $config['option']; } } $config['option'] = $component; $view = strtolower($viewName); if (empty($view) && array_key_exists('input', $config)) { $view = $tmpInput->get('view', $view, 'cmd'); } if (array_key_exists('view', $config)) { if ($config['view']) { $view = $config['view']; } } $config['view'] = $view; if (array_key_exists('input', $config)) { $tmpInput->set('option', $config['option']); $tmpInput->set('view', $config['view']); $config['input'] = $tmpInput; } // Get the component directories $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($config['option']); // Get the base paths where the view class files are expected to live $basePaths = array( $componentPaths['main'], $componentPaths['alt'] ); $basePaths = array_merge($this->paths['view']); // Get the alternate (singular/plural) view name $altViewName = FOFInflector::isPlural($viewName) ? FOFInflector::singularize($viewName) : FOFInflector::pluralize($viewName); $suffixes = array( $viewName, $altViewName, 'default' ); $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); foreach ($suffixes as $suffix) { // Build the view class name $viewClass = $classPrefix . ucfirst($suffix); if (class_exists($viewClass)) { // The class is already loaded break; } // The class is not loaded. Let's load it! $viewPath = $this->createFileName('view', array('name' => $suffix, 'type' => $viewType)); $path = $filesystem->pathFind($basePaths, $viewPath); if ($path) { require_once $path; } if (class_exists($viewClass)) { // The class was loaded successfully break; } } if (!class_exists($viewClass)) { $viewClass = 'FOFView' . ucfirst($type); } $templateOverridePath = FOFPlatform::getInstance()->getTemplateOverridePath($config['option']); // Setup View configuration options if (!array_key_exists('template_path', $config)) { $config['template_path'][] = $componentPaths['main'] . '/views/' . FOFInflector::pluralize($config['view']) . '/tmpl'; if ($templateOverridePath) { $config['template_path'][] = $templateOverridePath . '/' . FOFInflector::pluralize($config['view']); } $config['template_path'][] = $componentPaths['main'] . '/views/' . FOFInflector::singularize($config['view']) . '/tmpl'; if ($templateOverridePath) { $config['template_path'][] = $templateOverridePath . '/' . FOFInflector::singularize($config['view']); } $config['template_path'][] = $componentPaths['main'] . '/views/' . $config['view'] . '/tmpl'; if ($templateOverridePath) { $config['template_path'][] = $templateOverridePath . '/' . $config['view']; } } $extraTemplatePath = $this->configProvider->get($config['option'] . '.views.' . $config['view'] . '.config.template_path', null); if ($extraTemplatePath) { array_unshift($config['template_path'], $componentPaths['main'] . '/' . $extraTemplatePath); } if (!array_key_exists('helper_path', $config)) { $config['helper_path'] = array( $componentPaths['main'] . '/helpers', $componentPaths['admin'] . '/helpers' ); } $extraHelperPath = $this->configProvider->get($config['option'] . '.views.' . $config['view'] . '.config.helper_path', null); if ($extraHelperPath) { $config['helper_path'][] = $componentPaths['main'] . '/' . $extraHelperPath; } // Set the use_hypermedia flag in $config if it's not already set if (!isset($config['use_hypermedia'])) { $config['use_hypermedia'] = $this->configProvider->get($config['option'] . '.views.' . $config['view'] . '.config.use_hypermedia', false); } $result = new $viewClass($config); return $result; } /** * Deprecated function to create a View object instance * * @param string $name The name of the view, e.g. 'Items' * @param string $prefix The prefix of the view, e.g. 'FoobarView' * @param string $type The view type, e.g. 'html' * @param array $config The configuration array for the view * * @return FOFView * * @see FOFController::createView * * @deprecated since version 2.0 */ protected function &_createView($name, $prefix = '', $type = '', $config = array()) { FOFPlatform::getInstance()->logDeprecated(__CLASS__ . '::' . __METHOD__ . ' is deprecated. Use createView() instead.'); return $this->createView($name, $prefix, $type, $config); } /** * Set the name of the view to be used by this Controller * * @param string $viewName The name of the view * * @return void */ public function setThisViewName($viewName) { $this->viewName = $viewName; } /** * Set the name of the model to be used by this Controller * * @param string $modelName The name of the model * * @return void */ public function setThisModelName($modelName) { $this->modelName = $modelName; } /** * Checks if the current user has enough privileges for the requested ACL * area. * * @param string $area The ACL area, e.g. core.manage. * * @return boolean True if the user has the ACL privilege specified */ protected function checkACL($area) { if (in_array(strtolower($area), array('false','0','no','403'))) { return false; } if (in_array(strtolower($area), array('true','1','yes'))) { return true; } elseif (empty($area)) { return true; } else { // Check if we're dealing with ids $ids = null; // First, check if there is an asset for this record $table = $this->getThisModel()->getTable(); if ($table && $table->isAssetsTracked()) { $ids = $this->getThisModel()->getId() ? $this->getThisModel()->getId() : null; } // Generic or Asset tracking if (empty($ids)) { return FOFPlatform::getInstance()->authorise($area, $this->component); } else { if (!is_array($ids)) { $ids = array($ids); } $resource = FOFInflector::singularize($this->view); $isEditState = ($area == 'core.edit.state'); foreach ($ids as $id) { $asset = $this->component . '.' . $resource . '.' . $id; // Dedicated permission found, check it! if (FOFPlatform::getInstance()->authorise($area, $asset) ) { return true; } // Fallback on edit.own, if not edit.state. First test if the permission is available. if ((!$isEditState) && (FOFPlatform::getInstance()->authorise('core.edit.own', $asset))) { $table = $this->getThisModel()->getTable(); $table->load($id); $created_by = $table->getColumnAlias('created_by'); if ($table && isset($table->$created_by)) { // Now test the owner is the user. $owner_id = (int) $table->$created_by; // If the owner matches 'me' then do the test. if ($owner_id == FOFPlatform::getInstance()->getUser()->id) { return true; } else { return false; } } else { return false; } } } } } return false; } /** * A catch-all method for all tasks without a corresponding onBefore * method. Applies the ACL preferences defined in fof.xml. * * @param string $task The task being executed * * @return boolean True to allow execution of the task */ protected function onBeforeGenericTask($task) { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.' . $task, '' ); return $this->checkACL($privilege); } /** * Execute something before applySave is called. Return false to prevent * applySave from executing. * * @param array &$data The data upon which applySave will act * * @return boolean True to allow applySave to run */ protected function onBeforeApplySave(&$data) { return true; } /** * Execute something after applySave has run. * * @return boolean True to allow normal return, false to cause a 403 error */ protected function onAfterApplySave() { return true; } /** * ACL check before changing the access level; override to customise * * @return boolean True to allow accesspublic() to run */ protected function onBeforeAccesspublic() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.accesspublic', 'core.edit.state'); return $this->checkACL($privilege); } /** * ACL check before changing the access level; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeAccessregistered() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.accessregistered', 'core.edit.state' ); return $this->checkACL($privilege); } /** * ACL check before changing the access level; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeAccessspecial() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.accessspecial', 'core.edit.state' ); return $this->checkACL($privilege); } /** * ACL check before adding a new record; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeAdd() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.add', 'core.create' ); return $this->checkACL($privilege); } /** * ACL check before saving a new/modified record; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeApply() { $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $id = $model->getId(); if(!$id) { $defaultPrivilege = 'core.create'; } else { $defaultPrivilege = 'core.edit'; } $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.apply', $defaultPrivilege ); return $this->checkACL($privilege); } /** * ACL check before allowing someone to browse * * @return boolean True to allow the method to run */ protected function onBeforeBrowse() { $defaultPrivilege = ''; $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.browse', $defaultPrivilege ); return $this->checkACL($privilege); } /** * ACL check before cancelling an edit * * @return boolean True to allow the method to run */ protected function onBeforeCancel() { $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $id = $model->getId(); if(!$id) { $defaultPrivilege = 'core.create'; } else { $defaultPrivilege = 'core.edit'; } $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.cancel', $defaultPrivilege ); return $this->checkACL($privilege); } /** * ACL check before editing a record; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeEdit() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.edit', 'core.edit' ); return $this->checkACL($privilege); } /** * ACL check before changing the ordering of a record; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeOrderdown() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.orderdown', 'core.edit.state' ); return $this->checkACL($privilege); } /** * ACL check before changing the ordering of a record; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeOrderup() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.orderup', 'core.edit.state' ); return $this->checkACL($privilege); } /** * ACL check before changing the publish status of a record; override to customise * * @return boolean True to allow the method to run */ protected function onBeforePublish() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.publish', 'core.edit.state' ); return $this->checkACL($privilege); } /** * ACL check before removing a record; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeRemove() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.remove', 'core.delete' ); return $this->checkACL($privilege); } /** * ACL check before saving a new/modified record; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeSave() { $model = $this->getThisModel(); if (!$model->getId()) { $model->setIDsFromRequest(); } $id = $model->getId(); if(!$id) { $defaultPrivilege = 'core.create'; } else { $defaultPrivilege = 'core.edit'; } $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.save', $defaultPrivilege ); return $this->checkACL($privilege); } /** * ACL check before saving a new/modified record; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeSavenew() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.savenew', 'core.create' ); return $this->checkACL($privilege); } /** * ACL check before changing the ordering of a record; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeSaveorder() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.saveorder', 'core.edit.state' ); return $this->checkACL($privilege); } /** * ACL check before changing the publish status of a record; override to customise * * @return boolean True to allow the method to run */ protected function onBeforeUnpublish() { $privilege = $this->configProvider->get( $this->component . '.views.' . FOFInflector::singularize($this->view) . '.acl.unpublish', 'core.edit.state' ); return $this->checkACL($privilege); } /** * Gets a URL suffix with the Itemid parameter. If it's not the front-end of the site, or if * there is no Itemid set it returns an empty string. * * @return string The &Itemid=123 URL suffix, or an empty string if Itemid is not applicable */ public function getItemidURLSuffix() { if (FOFPlatform::getInstance()->isFrontend() && ($this->input->getCmd('Itemid', 0) != 0)) { return '&Itemid=' . $this->input->getInt('Itemid', 0); } else { return ''; } } /** * Applies CSRF protection by means of a standard Joomla! token (nonce) check. * Raises a 403 Access Forbidden error through the platform if the check fails. * * TODO Move this check inside the platform * * @return boolean True if the CSRF check is successful * * @throws Exception */ protected function _csrfProtection() { static $isCli = null, $isAdmin = null; if (is_null($isCli)) { $isCli = FOFPlatform::getInstance()->isCli(); $isAdmin = FOFPlatform::getInstance()->isBackend(); } switch ($this->csrfProtection) { // Never case 0: return true; break; // Always case 1: break; // Only back-end and HTML format case 2: if ($isCli) { return true; } elseif (!$isAdmin && ($this->input->get('format', 'html', 'cmd') != 'html')) { return true; } break; // Only back-end case 3: if (!$isAdmin) { return true; } break; } $hasToken = false; $session = JFactory::getSession(); // Joomla! 1.5/1.6/1.7/2.5 (classic Joomla! API) method if (method_exists('JUtility', 'getToken')) { $token = JUtility::getToken(); $hasToken = $this->input->get($token, false, 'none') == 1; if (!$hasToken) { $hasToken = $this->input->get('_token', null, 'none') == $token; } } // Joomla! 2.5+ (Platform 12.1+) method if (!$hasToken) { if (method_exists($session, 'getToken')) { $token = $session->getToken(); $hasToken = $this->input->get($token, false, 'none') == 1; if (!$hasToken) { $hasToken = $this->input->get('_token', null, 'none') == $token; } } } // Joomla! 2.5+ formToken method if (!$hasToken) { if (method_exists($session, 'getFormToken')) { $token = $session->getFormToken(); $hasToken = $this->input->get($token, false, 'none') == 1; if (!$hasToken) { $hasToken = $this->input->get('_token', null, 'none') == $token; } } } if (!$hasToken) { FOFPlatform::getInstance()->raiseError(403, JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN')); return false; } } } PKY[>\/^H^Hfof/LICENSE.txtnuW+A================================================================================ Historical note ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ On February 21st, 2013 FOF changed its license to GPLv2 or later (instead of v3 or later) so that it can be distributed with the Joomla! CMS without causing licensing issues. ================================================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License.PKY[yfof/encrypt/totp.phpnuW+A_timeStep = $timeStep; $this->_passCodeLength = $passCodeLength; $this->_secretLength = $secretLength; $this->_pinModulo = pow(10, $this->_passCodeLength); if (is_null($base32)) { $this->_base32 = new FOFEncryptBase32; } else { $this->_base32 = $base32; } } /** * Get the time period based on the $time timestamp and the Time Step * defined. If $time is skipped or set to null the current timestamp will * be used. * * @param int|null $time Timestamp * * @return int The time period since the UNIX Epoch */ public function getPeriod($time = null) { if (is_null($time)) { $time = time(); } $period = floor($time / $this->_timeStep); return $period; } /** * Check is the given passcode $code is a valid TOTP generated using secret * key $secret * * @param string $secret The Base32-encoded secret key * @param string $code The passcode to check * * @return boolean True if the code is valid */ public function checkCode($secret, $code) { $time = $this->getPeriod(); for ($i = -1; $i <= 1; $i++) { if ($this->getCode($secret, $time + $i) == $code) { return true; } } return false; } /** * Gets the TOTP passcode for a given secret key $secret and a given UNIX * timestamp $time * * @param string $secret The Base32-encoded secret key * @param int $time UNIX timestamp * * @return string */ public function getCode($secret, $time = null) { $period = $this->getPeriod($time); $secret = $this->_base32->decode($secret); $time = pack("N", $period); $time = str_pad($time, 8, chr(0), STR_PAD_LEFT); $hash = hash_hmac('sha1', $time, $secret, true); $offset = ord(substr($hash, -1)); $offset = $offset & 0xF; $truncatedHash = $this->hashToInt($hash, $offset) & 0x7FFFFFFF; $pinValue = str_pad($truncatedHash % $this->_pinModulo, $this->_passCodeLength, "0", STR_PAD_LEFT); return $pinValue; } /** * Extracts a part of a hash as an integer * * @param string $bytes The hash * @param string $start The char to start from (0 = first char) * * @return string */ protected function hashToInt($bytes, $start) { $input = substr($bytes, $start, strlen($bytes) - $start); $val2 = unpack("N", substr($input, 0, 4)); return $val2[1]; } /** * Returns a QR code URL for easy setup of TOTP apps like Google Authenticator * * @param string $user User * @param string $hostname Hostname * @param string $secret Secret string * * @return string */ public function getUrl($user, $hostname, $secret) { $url = sprintf("otpauth://totp/%s@%s?secret=%s", $user, $hostname, $secret); $encoder = "https://chart.googleapis.com/chart?chs=200x200&chld=Q|2&cht=qr&chl="; $encoderURL = $encoder . urlencode($url); return $encoderURL; } /** * Generates a (semi-)random Secret Key for TOTP generation * * @return string */ public function generateSecret() { $secret = ""; for ($i = 1; $i <= $this->_secretLength; $i++) { $c = rand(0, 255); $secret .= pack("c", $c); } $base32 = new FOFEncryptBase32; return $this->_base32->encode($secret); } } PKY[k66fof/encrypt/index.htmlnuW+APKY[֗J**fof/encrypt/base32.phpnuW+A 0) { throw new Exception('Length must be divisible by 8'); } if (!preg_match('/^[01]+$/', $str)) { throw new Exception('Only 0\'s and 1\'s are permitted'); } preg_match_all('/.{8}/', $str, $chrs); $chrs = array_map('bindec', $chrs[0]); // I'm just being slack here array_unshift($chrs, 'C*'); return call_user_func_array('pack', $chrs); } /** * fromBin * * Converts a correct binary string to base32 * * @param string $str The string of 0's and 1's you want to convert * * @return string String encoded as base32 * * @throws exception */ private function fromBin($str) { if (strlen($str) % 8 > 0) { throw new Exception('Length must be divisible by 8'); } if (!preg_match('/^[01]+$/', $str)) { throw new Exception('Only 0\'s and 1\'s are permitted'); } // Base32 works on the first 5 bits of a byte, so we insert blanks to pad it out $str = preg_replace('/(.{5})/', '000$1', $str); // We need a string divisible by 5 $length = strlen($str); $rbits = $length & 7; if ($rbits > 0) { // Excessive bits need to be padded $ebits = substr($str, $length - $rbits); $str = substr($str, 0, $length - $rbits); $str .= "000$ebits" . str_repeat('0', 5 - strlen($ebits)); } preg_match_all('/.{8}/', $str, $chrs); $chrs = array_map(array($this, '_mapcharset'), $chrs[0]); return join('', $chrs); } /** * toBin * * Accepts a base32 string and returns an ascii binary string * * @param string $str The base32 string to convert * * @return string Ascii binary string * * @throws Exception */ private function toBin($str) { if (!preg_match('/^[' . self::CSRFC3548 . ']+$/', $str)) { throw new Exception('Must match character set'); } // Convert the base32 string back to a binary string $str = join('', array_map(array($this, '_mapbin'), str_split($str))); // Remove the extra 0's we added $str = preg_replace('/000(.{5})/', '$1', $str); // Unpad if nessicary $length = strlen($str); $rbits = $length & 7; if ($rbits > 0) { $str = substr($str, 0, $length - $rbits); } return $str; } /** * fromString * * Convert any string to a base32 string * This should be binary safe... * * @param string $str The string to convert * * @return string The converted base32 string */ public function encode($str) { return $this->fromBin($this->str2bin($str)); } /** * toString * * Convert any base32 string to a normal sctring * This should be binary safe... * * @param string $str The base32 string to convert * * @return string The normal string */ public function decode($str) { $str = strtoupper($str); return $this->bin2str($this->tobin($str)); } /** * _mapcharset * * Used with array_map to map the bits from a binary string * directly into a base32 character set * * @param string $str The string of 0's and 1's you want to convert * * @return string Resulting base32 character * * @access private */ private function _mapcharset($str) { // Huh! $x = self::CSRFC3548; return $x[bindec($str)]; } /** * _mapbin * * Used with array_map to map the characters from a base32 * character set directly into a binary string * * @param string $chr The caracter to map * * @return string String of 0's and 1's * * @access private */ private function _mapbin($chr) { return sprintf('%08b', strpos(self::CSRFC3548, $chr)); } } PKY[inuZZfof/encrypt/aes.phpnuW+A_keyString = $key; switch ($strength) { case 256: default: $this->_cipherType = MCRYPT_RIJNDAEL_256; break; case 192: $this->_cipherType = MCRYPT_RIJNDAEL_192; break; case 128: $this->_cipherType = MCRYPT_RIJNDAEL_128; break; } switch (strtoupper($mode)) { case 'ECB': $this->_cipherMode = MCRYPT_MODE_ECB; break; case 'CBC': $this->_cipherMode = MCRYPT_MODE_CBC; break; } } /** * Encrypts a string using AES * * @param string $stringToEncrypt The plaintext to encrypt * @param bool $base64encoded Should I Base64-encode the result? * * @return string The cryptotext. Please note that the first 16 bytes of * the raw string is the IV (initialisation vector) which * is necessary for decoding the string. */ public function encryptString($stringToEncrypt, $base64encoded = true) { if (strlen($this->_keyString) != 32) { $key = hash('sha256', $this->_keyString, true); } else { $key = $this->_keyString; } // Set up the IV (Initialization Vector) $iv_size = mcrypt_get_iv_size($this->_cipherType, $this->_cipherMode); $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_URANDOM); if (empty($iv)) { $iv = mcrypt_create_iv($iv_size, MCRYPT_DEV_RANDOM); } if (empty($iv)) { $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND); } // Encrypt the data $cipherText = mcrypt_encrypt($this->_cipherType, $key, $stringToEncrypt, $this->_cipherMode, $iv); // Prepend the IV to the ciphertext $cipherText = $iv . $cipherText; // Optionally pass the result through Base64 encoding if ($base64encoded) { $cipherText = base64_encode($cipherText); } // Return the result return $cipherText; } /** * Decrypts a ciphertext into a plaintext string using AES * * @param string $stringToDecrypt The ciphertext to decrypt. The first 16 bytes of the raw string must contain the IV (initialisation vector). * @param bool $base64encoded Should I Base64-decode the data before decryption? * * @return string The plain text string */ public function decryptString($stringToDecrypt, $base64encoded = true) { if (strlen($this->_keyString) != 32) { $key = hash('sha256', $this->_keyString, true); } else { $key = $this->_keyString; } if ($base64encoded) { $stringToDecrypt = base64_decode($stringToDecrypt); } // Calculate the IV size $iv_size = mcrypt_get_iv_size($this->_cipherType, $this->_cipherMode); // Extract IV $iv = substr($stringToDecrypt, 0, $iv_size); $stringToDecrypt = substr($stringToDecrypt, $iv_size); // Decrypt the data $plainText = mcrypt_decrypt($this->_cipherType, $key, $stringToDecrypt, $this->_cipherMode, $iv); return $plainText; } /** * Is AES encryption supported by this PHP installation? * * @return boolean */ public static function isSupported() { if (!function_exists('mcrypt_get_key_size')) { return false; } if (!function_exists('mcrypt_get_iv_size')) { return false; } if (!function_exists('mcrypt_create_iv')) { return false; } if (!function_exists('mcrypt_encrypt')) { return false; } if (!function_exists('mcrypt_decrypt')) { return false; } if (!function_exists('mcrypt_list_algorithms')) { return false; } if (!function_exists('hash')) { return false; } if (!function_exists('hash_algos')) { return false; } if (!function_exists('base64_encode')) { return false; } if (!function_exists('base64_decode')) { return false; } $algorightms = mcrypt_list_algorithms(); if (!in_array('rijndael-128', $algorightms)) { return false; } if (!in_array('rijndael-192', $algorightms)) { return false; } if (!in_array('rijndael-256', $algorightms)) { return false; } $algorightms = hash_algos(); if (!in_array('sha256', $algorightms)) { return false; } return true; } } PKY[k66fof/template/index.htmlnuW+APKY[ ?88fof/template/utils.phpnuW+AgetDocument(); if ($document instanceof JDocument) { if (method_exists($document, 'addStyleSheet')) { $url = self::parsePath($path); $document->addStyleSheet($url); } } } /** * Add a JS script file to the page generated by the CMS. * * There are three combinations of defer and async (see http://www.w3schools.com/tags/att_script_defer.asp): * * $defer false, $async true: The script is executed asynchronously with the rest of the page * (the script will be executed while the page continues the parsing) * * $defer true, $async false: The script is executed when the page has finished parsing. * * $defer false, $async false. (default) The script is loaded and executed immediately. When it finishes * loading the browser continues parsing the rest of the page. * * When you are using $defer = true there is no guarantee about the load order of the scripts. Whichever * script loads first will be executed first. The order they appear on the page is completely irrelevant. * * @param string $path A fancy path definition understood by parsePath * @param boolean $defer Adds the defer attribute, meaning that your script * will only load after the page has finished parsing. * @param boolean $async Adds the async attribute, meaning that your script * will be executed while the resto of the page * continues parsing. * * @see FOFTemplateUtils::parsePath * * @return void */ public static function addJS($path, $defer = false, $async = false) { $document = FOFPlatform::getInstance()->getDocument(); if ($document instanceof JDocument) { if (method_exists($document, 'addScript')) { $url = self::parsePath($path); $document->addScript($url, "text/javascript", $defer, $async); } } } /** * Compile a LESS file into CSS and add it to the page generated by the CMS. * This method has integrated cache support. The compiled LESS files will be * written to the media/lib_fof/compiled directory of your site. If the file * cannot be written we will use the $altPath, if specified * * @param string $path A fancy path definition understood by parsePath pointing to the source LESS file * @param string $altPath A fancy path definition understood by parsePath pointing to a precompiled CSS file, * used when we can't write the generated file to the output directory * @param boolean $returnPath Return the URL of the generated CSS file but do not include it. If it can't be * generated, false is returned and the alt files are not included * * @see FOFTemplateUtils::parsePath * * @since 2.0 * * @return mixed True = successfully included generated CSS, False = the alternate CSS file was used, null = the source file does not exist */ public static function addLESS($path, $altPath = null, $returnPath = false) { // Does the cache directory exists and is writeable static $sanityCheck = null; // Get the local LESS file $localFile = self::parsePath($path, true); $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); $platformDirs = FOFPlatform::getInstance()->getPlatformBaseDirs(); if (is_null($sanityCheck)) { // Make sure the cache directory exists if (!is_dir($platformDirs['public'] . '/media/lib_fof/compiled/')) { $sanityCheck = $filesystem->folderCreate($platformDirs['public'] . '/media/lib_fof/compiled/'); } else { $sanityCheck = true; } } // No point continuing if the source file is not there or we can't write to the cache if (!$sanityCheck || !is_file($localFile)) { if (!$returnPath) { if (is_string($altPath)) { self::addCSS($altPath); } elseif (is_array($altPath)) { foreach ($altPath as $anAltPath) { self::addCSS($anAltPath); } } } return false; } // Get the source file's unique ID $id = md5(filemtime($localFile) . filectime($localFile) . $localFile); // Get the cached file path $cachedPath = $platformDirs['public'] . '/media/lib_fof/compiled/' . $id . '.css'; // Get the LESS compiler $lessCompiler = new FOFLess; $lessCompiler->formatterName = 'compressed'; // Should I add an alternative import path? $altFiles = self::getAltPaths($path); if (isset($altFiles['alternate'])) { $currentLocation = realpath(dirname($localFile)); $normalLocation = realpath(dirname($altFiles['normal'])); $alternateLocation = realpath(dirname($altFiles['alternate'])); if ($currentLocation == $normalLocation) { $lessCompiler->importDir = array($alternateLocation, $currentLocation); } else { $lessCompiler->importDir = array($currentLocation, $normalLocation); } } // Compile the LESS file $lessCompiler->checkedCompile($localFile, $cachedPath); // Add the compiled CSS to the page $base_url = rtrim(FOFPlatform::getInstance()->URIbase(), '/'); if (substr($base_url, -14) == '/administrator') { $base_url = substr($base_url, 0, -14); } $url = $base_url . '/media/lib_fof/compiled/' . $id . '.css'; if ($returnPath) { return $url; } else { $document = FOFPlatform::getInstance()->getDocument(); if ($document instanceof JDocument) { if (method_exists($document, 'addStyleSheet')) { $document->addStyleSheet($url); } } return true; } } /** * Creates a SEF compatible sort header. Standard Joomla function will add a href="#" tag, so with SEF * enabled, the browser will follow the fake link instead of processing the onSubmit event; so we * need a fix. * * @param string $text Header text * @param string $field Field used for sorting * @param FOFUtilsObject $list Object holding the direction and the ordering field * * @return string HTML code for sorting */ public static function sefSort($text, $field, $list) { $sort = JHTML::_('grid.sort', JText::_(strtoupper($text)) . ' ', $field, $list->order_Dir, $list->order); return str_replace('href="#"', 'href="javascript:void(0);"', $sort); } /** * Parse a fancy path definition into a path relative to the site's root, * respecting template overrides, suitable for inclusion of media files. * For example, media://com_foobar/css/test.css is parsed into * media/com_foobar/css/test.css if no override is found, or * templates/mytemplate/media/com_foobar/css/test.css if the current * template is called mytemplate and there's a media override for it. * * The valid protocols are: * media:// The media directory or a media override * admin:// Path relative to administrator directory (no overrides) * site:// Path relative to site's root (no overrides) * * @param string $path Fancy path * @param boolean $localFile When true, it returns the local path, not the URL * * @return string Parsed path */ public static function parsePath($path, $localFile = false) { $platformDirs = FOFPlatform::getInstance()->getPlatformBaseDirs(); if ($localFile) { $url = rtrim($platformDirs['root'], DIRECTORY_SEPARATOR) . '/'; } else { $url = FOFPlatform::getInstance()->URIroot(); } $altPaths = self::getAltPaths($path); $filePath = $altPaths['normal']; // If JDEBUG is enabled, prefer that path, else prefer an alternate path if present if (defined('JDEBUG') && JDEBUG && isset($altPaths['debug'])) { if (file_exists($platformDirs['public'] . '/' . $altPaths['debug'])) { $filePath = $altPaths['debug']; } } elseif (isset($altPaths['alternate'])) { if (file_exists($platformDirs['public'] . '/' . $altPaths['alternate'])) { $filePath = $altPaths['alternate']; } } $url .= $filePath; return $url; } /** * Parse a fancy path definition into a path relative to the site's root. * It returns both the normal and alternative (template media override) path. * For example, media://com_foobar/css/test.css is parsed into * array( * 'normal' => 'media/com_foobar/css/test.css', * 'alternate' => 'templates/mytemplate/media/com_foobar/css//test.css' * ); * * The valid protocols are: * media:// The media directory or a media override * admin:// Path relative to administrator directory (no alternate) * site:// Path relative to site's root (no alternate) * * @param string $path Fancy path * * @return array Array of normal and alternate parsed path */ public static function getAltPaths($path) { $protoAndPath = explode('://', $path, 2); if (count($protoAndPath) < 2) { $protocol = 'media'; } else { $protocol = $protoAndPath[0]; $path = $protoAndPath[1]; } $path = ltrim($path, '/' . DIRECTORY_SEPARATOR); switch ($protocol) { case 'media': // Do we have a media override in the template? $pathAndParams = explode('?', $path, 2); $ret = array( 'normal' => 'media/' . $pathAndParams[0], 'alternate' => FOFPlatform::getInstance()->getTemplateOverridePath('media:/' . $pathAndParams[0], false), ); break; case 'admin': $ret = array( 'normal' => 'administrator/' . $path ); break; default: case 'site': $ret = array( 'normal' => $path ); break; } // For CSS and JS files, add a debug path if the supplied file is compressed $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); $ext = $filesystem->getExt($ret['normal']); if (in_array($ext, array('css', 'js'))) { $file = basename($filesystem->stripExt($ret['normal'])); /* * Detect if we received a file in the format name.min.ext * If so, strip the .min part out, otherwise append -uncompressed */ if (strlen($file) > 4 && strrpos($file, '.min', '-4')) { $position = strrpos($file, '.min', '-4'); $filename = str_replace('.min', '.', $file, $position); } else { $filename = $file . '-uncompressed.' . $ext; } // Clone the $ret array so we can manipulate the 'normal' path a bit $t1 = (object) $ret; $temp = clone $t1; unset($t1); $temp = (array)$temp; $normalPath = explode('/', $temp['normal']); array_pop($normalPath); $normalPath[] = $filename; $ret['debug'] = implode('/', $normalPath); } return $ret; } /** * Returns the contents of a module position * * @param string $position The position name, e.g. "position-1" * @param int $style Rendering style; please refer to Joomla!'s code for more information * * @return string The contents of the module position */ public static function loadPosition($position, $style = -2) { $document = FOFPlatform::getInstance()->getDocument(); if (!($document instanceof JDocument)) { return ''; } if (!method_exists($document, 'loadRenderer')) { return ''; } try { $renderer = $document->loadRenderer('module'); } catch (Exception $exc) { return ''; } $params = array('style' => $style); $contents = ''; foreach (JModuleHelper::getModules($position) as $mod) { $contents .= $renderer->render($mod, $params); } return $contents; } /** * Merges the current url with new or changed parameters. * * This method merges the route string with the url parameters defined * in current url. The parameters defined in current url, but not given * in route string, will automatically reused in the resulting url. * But only these following parameters will be reused: * * option, view, layout, format * * Example: * * Assuming that current url is: * http://fobar.com/index.php?option=com_foo&view=cpanel * * * * * * Result: * http://fobar.com/index.php?option=com_foo&view=categories&layout=tree * * @param string $route The parameters string * * @return string The human readable, complete url */ public static function route($route = '') { $route = trim($route); // Special cases if ($route == 'index.php' || $route == 'index.php?') { $result = $route; } elseif (substr($route, 0, 1) == '&') { $url = JURI::getInstance(); $vars = array(); parse_str($route, $vars); $url->setQuery(array_merge($url->getQuery(true), $vars)); $result = 'index.php?' . $url->getQuery(); } else { $url = JURI::getInstance(); $props = $url->getQuery(true); // Strip 'index.php?' if (substr($route, 0, 10) == 'index.php?') { $route = substr($route, 10); } // Parse route $parts = array(); parse_str($route, $parts); $result = array(); // Check to see if there is component information in the route if not add it if (!isset($parts['option']) && isset($props['option'])) { $result[] = 'option=' . $props['option']; } // Add the layout information to the route only if it's not 'default' if (!isset($parts['view']) && isset($props['view'])) { $result[] = 'view=' . $props['view']; if (!isset($parts['layout']) && isset($props['layout'])) { $result[] = 'layout=' . $props['layout']; } } // Add the format information to the URL only if it's not 'html' if (!isset($parts['format']) && isset($props['format']) && $props['format'] != 'html') { $result[] = 'format=' . $props['format']; } // Reconstruct the route if (!empty($route)) { $result[] = $route; } $result = 'index.php?' . implode('&', $result); } return JRoute::_($result); } } PKY[™,TATAfof/platform/interface.phpnuW+AisDir()) { continue; } $fileName = $fileSpec->getFilename(); if (substr($fileName, 0, 1) == '.') { continue; } $platformFilename = $path . '/' . $fileName . '/platform.php'; if (!file_exists($platformFilename)) { continue; } $temp[] = array( 'classname' => 'FOFIntegration' . ucfirst($fileName) . 'Platform', 'fullpath' => $path . '/' . $fileName . '/platform.php', ); } $integrations = array_merge($integrations, $temp); } // Loop all paths foreach ($integrations as $integration) { // Get the class name for this platform class $class_name = $integration['classname']; // Load the file if the class doesn't exist if (!class_exists($class_name, false)) { @include_once $integration['fullpath']; } // If the class still doesn't exist this file didn't // actually contain a platform class; skip it if (!class_exists($class_name, false)) { continue; } // If it doesn't implement FOFPlatformInterface, skip it if (!class_implements($class_name, 'FOFPlatformInterface')) { continue; } // Get an object of this platform $o = new $class_name; // If it's not enabled, skip it if (!$o->isEnabled()) { continue; } if (is_object(self::$instance)) { // Replace self::$instance if this object has a // lower order number $current_order = self::$instance->getOrdering(); $new_order = $o->getOrdering(); if ($new_order < $current_order) { self::$instance = null; self::$instance = $o; } } else { // There is no self::$instance already, so use the // object we just created. self::$instance = $o; } } } return self::$instance; } /** * Returns the ordering of the platform class. * * @see FOFPlatformInterface::getOrdering() * * @return integer */ public function getOrdering() { return $this->ordering; } /** * Is this platform enabled? * * @see FOFPlatformInterface::isEnabled() * * @return boolean */ public function isEnabled() { if (is_null($this->isEnabled)) { $this->isEnabled = false; } return $this->isEnabled; } /** * Returns a platform integration object * * @param string $key The key name of the platform integration object, e.g. 'filesystem' * * @return object * * @since 2.1.2 */ public function getIntegrationObject($key) { $hasObject = false; if (array_key_exists($key, $this->objectCache)) { if (is_object($this->objectCache[$key])) { $hasObject = true; } } if (!$hasObject) { // Instantiate a new platform integration object $className = 'FOFIntegration' . ucfirst($this->getPlatformName()) . ucfirst($key); $this->objectCache[$key] = new $className; } return $this->objectCache[$key]; } /** * Forces a platform integration object instance * * @param string $key The key name of the platform integration object, e.g. 'filesystem' * @param object $object The object to force for this key * * @return object * * @since 2.1.2 */ public function setIntegrationObject($key, $object) { $this->objectCache[$key] = $object; } // ======================================================================== // Default implementation // ======================================================================== /** * Set the error Handling, if possible * * @param integer $level PHP error level (E_ALL) * @param string $log_level What to do with the error (ignore, callback) * @param array $options Options for the error handler * * @return void */ public function setErrorHandling($level, $log_level, $options = array()) { if (version_compare(JVERSION, '3.0', 'lt') ) { return JError::setErrorHandling($level, $log_level, $options); } } /** * Returns the base (root) directories for a given component. * * @param string $component The name of the component. For Joomla! this * is something like "com_example" * * @see FOFPlatformInterface::getComponentBaseDirs() * * @return array A hash array with keys main, alt, site and admin. */ public function getComponentBaseDirs($component) { return array( 'main' => '', 'alt' => '', 'site' => '', 'admin' => '', ); } /** * Return a list of the view template directories for this component. * * @param string $component The name of the component. For Joomla! this * is something like "com_example" * @param string $view The name of the view you're looking a * template for * @param string $layout The layout name to load, e.g. 'default' * @param string $tpl The sub-template name to load (null by default) * @param boolean $strict If true, only the specified layout will be * searched for. Otherwise we'll fall back to * the 'default' layout if the specified layout * is not found. * * @see FOFPlatformInterface::getViewTemplateDirs() * * @return array */ public function getViewTemplatePaths($component, $view, $layout = 'default', $tpl = null, $strict = false) { return array(); } /** * Get application-specific suffixes to use with template paths. This allows * you to look for view template overrides based on the application version. * * @return array A plain array of suffixes to try in template names */ public function getTemplateSuffixes() { return array(); } /** * Return the absolute path to the application's template overrides * directory for a specific component. We will use it to look for template * files instead of the regular component directorues. If the application * does not have such a thing as template overrides return an empty string. * * @param string $component The name of the component for which to fetch the overrides * @param boolean $absolute Should I return an absolute or relative path? * * @return string The path to the template overrides directory */ public function getTemplateOverridePath($component, $absolute = true) { return ''; } /** * Load the translation files for a given component. * * @param string $component The name of the component. For Joomla! this * is something like "com_example" * * @see FOFPlatformInterface::loadTranslations() * * @return void */ public function loadTranslations($component) { return null; } /** * Authorise access to the component in the back-end. * * @param string $component The name of the component. * * @see FOFPlatformInterface::authorizeAdmin() * * @return boolean True to allow loading the component, false to halt loading */ public function authorizeAdmin($component) { return true; } /** * Returns the JUser object for the current user * * @param integer $id The ID of the user to fetch * * @see FOFPlatformInterface::getUser() * * @return JDocument */ public function getUser($id = null) { return null; } /** * Returns the JDocument object which handles this component's response. * * @see FOFPlatformInterface::getDocument() * * @return JDocument */ public function getDocument() { return null; } /** * This method will try retrieving a variable from the request (input) data. * * @param string $key The user state key for the variable * @param string $request The request variable name for the variable * @param FOFInput $input The FOFInput object with the request (input) data * @param mixed $default The default value. Default: null * @param string $type The filter type for the variable data. Default: none (no filtering) * @param boolean $setUserState Should I set the user state with the fetched value? * * @see FOFPlatformInterface::getUserStateFromRequest() * * @return mixed The value of the variable */ public function getUserStateFromRequest($key, $request, $input, $default = null, $type = 'none', $setUserState = true) { return $input->get($request, $default, $type); } /** * Load plugins of a specific type. Obviously this seems to only be required * in the Joomla! CMS. * * @param string $type The type of the plugins to be loaded * * @see FOFPlatformInterface::importPlugin() * * @return void */ public function importPlugin($type) { } /** * Execute plugins (system-level triggers) and fetch back an array with * their return values. * * @param string $event The event (trigger) name, e.g. onBeforeScratchMyEar * @param array $data A hash array of data sent to the plugins as part of the trigger * * @see FOFPlatformInterface::runPlugins() * * @return array A simple array containing the results of the plugins triggered */ public function runPlugins($event, $data) { return array(); } /** * Perform an ACL check. * * @param string $action The ACL privilege to check, e.g. core.edit * @param string $assetname The asset name to check, typically the component's name * * @see FOFPlatformInterface::authorise() * * @return boolean True if the user is allowed this action */ public function authorise($action, $assetname) { return true; } /** * Is this the administrative section of the component? * * @see FOFPlatformInterface::isBackend() * * @return boolean */ public function isBackend() { return true; } /** * Is this the public section of the component? * * @see FOFPlatformInterface::isFrontend() * * @return boolean */ public function isFrontend() { return true; } /** * Is this a component running in a CLI application? * * @see FOFPlatformInterface::isCli() * * @return boolean */ public function isCli() { return true; } /** * Is AJAX re-ordering supported? This is 100% Joomla!-CMS specific. All * other platforms should return false and never ask why. * * @see FOFPlatformInterface::supportsAjaxOrdering() * * @return boolean */ public function supportsAjaxOrdering() { return true; } /** * Performs a check between two versions. Use this function instead of PHP version_compare * so we can mock it while testing * * @param string $version1 First version number * @param string $version2 Second version number * @param string $operator Operator (see version_compare for valid operators) * * @return boolean */ public function checkVersion($version1, $version2, $operator) { return version_compare($version1, $version2, $operator); } /** * Saves something to the cache. This is supposed to be used for system-wide * FOF data, not application data. * * @param string $key The key of the data to save * @param string $content The actual data to save * * @return boolean True on success */ public function setCache($key, $content) { return false; } /** * Retrieves data from the cache. This is supposed to be used for system-side * FOF data, not application data. * * @param string $key The key of the data to retrieve * @param string $default The default value to return if the key is not found or the cache is not populated * * @return string The cached value */ public function getCache($key, $default = null) { return false; } /** * Is the global FOF cache enabled? * * @return boolean */ public function isGlobalFOFCacheEnabled() { return true; } /** * Clears the cache of system-wide FOF data. You are supposed to call this in * your components' installation script post-installation and post-upgrade * methods or whenever you are modifying the structure of database tables * accessed by FOF. Please note that FOF's cache never expires and is not * purged by Joomla!. You MUST use this method to manually purge the cache. * * @return boolean True on success */ public function clearCache() { return false; } /** * logs in a user * * @param array $authInfo authentification information * * @return boolean True on success */ public function loginUser($authInfo) { return true; } /** * logs out a user * * @return boolean True on success */ public function logoutUser() { return true; } /** * Logs a deprecated practice. In Joomla! this results in the $message being output in the * deprecated log file, found in your site's log directory. * * @param $message The deprecated practice log message * * @return void */ public function logDeprecated($message) { // The default implementation does nothing. Override this in your platform classes. } /** * Returns the (internal) name of the platform implementation, e.g. * "joomla", "foobar123" etc. This MUST be the last part of the platform * class name. For example, if you have a plaform implementation class * FOFPlatformFoobar you MUST return "foobar" (all lowercase). * * @return string * * @since 2.1.2 */ public function getPlatformName() { return $this->name; } /** * Returns the version number string of the platform, e.g. "4.5.6". If * implementation integrates with a CMS or a versioned foundation (e.g. * a framework) it is advisable to return that version. * * @return string * * @since 2.1.2 */ public function getPlatformVersion() { return $this->version; } /** * Returns the human readable platform name, e.g. "Joomla!", "Joomla! * Framework", "Something Something Something Framework" etc. * * @return string * * @since 2.1.2 */ public function getPlatformHumanName() { return $this->humanReadableName; } } PKY[ ^%fof/platform/filesystem/interface.phpnuW+A $file, 'classname' => 'FOFPlatform'.ucfirst($parts[0]).ucfirst(basename($parts[1], '.php')) ); } return $return; } /** * Recursive function that will scan every directory unless it's in the ignore list. Files that aren't in the * ignore list are returned. * * @param string $path Folder where we should start looking * @param array $ignoreFolders Folder ignore list * @param array $ignoreFiles File ignore list * * @return array List of all the files */ protected static function scanDirectory($path, array $ignoreFolders = array(), array $ignoreFiles = array()) { $return = array(); $handle = @opendir($path); if(!$handle) { return $return; } while (($file = readdir($handle)) !== false) { if($file == '.' || $file == '..') { continue; } $fullpath = $path . '/' . $file; if((is_dir($fullpath) && in_array($file, $ignoreFolders)) || (is_file($fullpath) && in_array($file, $ignoreFiles))) { continue; } if(is_dir($fullpath)) { $return = array_merge(self::scanDirectory($fullpath, $ignoreFolders, $ignoreFiles), $return); } else { $return[] = $path . '/' . $file; } } return $return; } /** * Gets the extension of a file name * * @param string $file The file name * * @return string The file extension */ public function getExt($file) { $dot = strrpos($file, '.') + 1; return substr($file, $dot); } /** * Strips the last extension off of a file name * * @param string $file The file name * * @return string The file name without the extension */ public function stripExt($file) { return preg_replace('#\.[^.]*$#', '', $file); } }PKY[k66fof/index.htmlnuW+APKY[CCfof/dispatcher/dispatcher.phpnuW+AgetCmd('option', 'com_foobar'); $config['view'] = !is_null($view) ? $view : $input->getCmd('view', ''); $input->set('option', $config['option']); $input->set('view', $config['view']); $config['input'] = $input; $className = ucfirst(str_replace('com_', '', $config['option'])) . 'Dispatcher'; if (!class_exists($className)) { $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($config['option']); $searchPaths = array( $componentPaths['main'], $componentPaths['main'] . '/dispatchers', $componentPaths['admin'], $componentPaths['admin'] . '/dispatchers' ); if (array_key_exists('searchpath', $config)) { array_unshift($searchPaths, $config['searchpath']); } $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); $path = $filesystem->pathFind( $searchPaths, 'dispatcher.php' ); if ($path) { require_once $path; } } if (!class_exists($className)) { $className = 'FOFDispatcher'; } $instance = new $className($config); return $instance; } /** * Public constructor * * @param array $config The configuration variables */ public function __construct($config = array()) { // Cache the config $this->config = $config; // Get the input for this MVC triad if (array_key_exists('input', $config)) { $this->input = $config['input']; } else { $this->input = new FOFInput; } // Get the default values for the component name $this->component = $this->input->getCmd('option', 'com_foobar'); // Load the component's fof.xml configuration file $configProvider = new FOFConfigProvider; $this->defaultView = $configProvider->get($this->component . '.dispatcher.default_view', $this->defaultView); // Get the default values for the view name $this->view = $this->input->getCmd('view', null); if (empty($this->view)) { // Do we have a task formatted as controller.task? $task = $this->input->getCmd('task', ''); if (!empty($task) && (strstr($task, '.') !== false)) { list($this->view, $task) = explode('.', $task, 2); $this->input->set('task', $task); } } if (empty($this->view)) { $this->view = $this->defaultView; } $this->layout = $this->input->getCmd('layout', null); // Overrides from the config if (array_key_exists('option', $config)) { $this->component = $config['option']; } if (array_key_exists('view', $config)) { $this->view = empty($config['view']) ? $this->view : $config['view']; } if (array_key_exists('layout', $config)) { $this->layout = $config['layout']; } $this->input->set('option', $this->component); $this->input->set('view', $this->view); $this->input->set('layout', $this->layout); } /** * The main code of the Dispatcher. It spawns the necessary controller and * runs it. * * @throws Exception * * @return null */ public function dispatch() { $platform = FOFPlatform::getInstance(); if (!$platform->authorizeAdmin($this->input->getCmd('option', 'com_foobar'))) { return $platform->raiseError(403, JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN')); } $this->transparentAuthentication(); // Merge English and local translations $platform->loadTranslations($this->component); $canDispatch = true; if ($platform->isCli()) { $canDispatch = $canDispatch && $this->onBeforeDispatchCLI(); } $canDispatch = $canDispatch && $this->onBeforeDispatch(); if (!$canDispatch) { $platform->setHeader('Status', '403 Forbidden', true); return $platform->raiseError(403, JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN')); } // Get and execute the controller $option = $this->input->getCmd('option', 'com_foobar'); $view = $this->input->getCmd('view', $this->defaultView); $task = $this->input->getCmd('task', null); if (empty($task)) { $task = $this->getTask($view); } // Pluralise/sungularise the view name for typical tasks if (in_array($task, array('edit', 'add', 'read'))) { $view = FOFInflector::singularize($view); } elseif (in_array($task, array('browse'))) { $view = FOFInflector::pluralize($view); } $this->input->set('view', $view); $this->input->set('task', $task); $config = $this->config; $config['input'] = $this->input; $controller = FOFController::getTmpInstance($option, $view, $config); $status = $controller->execute($task); if (!$this->onAfterDispatch()) { $platform->setHeader('Status', '403 Forbidden', true); return $platform->raiseError(403, JText::_('JLIB_APPLICATION_ERROR_ACCESS_FORBIDDEN')); } $format = $this->input->get('format', 'html', 'cmd'); $format = empty($format) ? 'html' : $format; if ($format == 'html') { // In HTML views perform a redirection if ($controller->redirect()) { return; } } else { // In non-HTML views just exit the application with the proper HTTP headers if ($controller->hasRedirect()) { $headers = $platform->sendHeaders(); jexit(); } } } /** * Tries to guess the controller task to execute based on the view name and * the HTTP request method. * * @param string $view The name of the view * * @return string The best guess of the task to execute */ protected function getTask($view) { // Get a default task based on plural/singular view $request_task = $this->input->getCmd('task', null); $task = FOFInflector::isPlural($view) ? 'browse' : 'edit'; // Get a potential ID, we might need it later $id = $this->input->get('id', null, 'int'); if ($id == 0) { $ids = $this->input->get('ids', array(), 'array'); if (!empty($ids)) { $id = array_shift($ids); } } // Check the request method if (!isset($_SERVER['REQUEST_METHOD'])) { $_SERVER['REQUEST_METHOD'] = 'GET'; } $requestMethod = strtoupper($_SERVER['REQUEST_METHOD']); switch ($requestMethod) { case 'POST': case 'PUT': if (!is_null($id)) { $task = 'save'; } break; case 'DELETE': if ($id != 0) { $task = 'delete'; } break; case 'GET': default: // If it's an edit without an ID or ID=0, it's really an add if (($task == 'edit') && ($id == 0)) { $task = 'add'; } // If it's an edit in the frontend, it's really a read elseif (($task == 'edit') && FOFPlatform::getInstance()->isFrontend()) { $task = 'read'; } break; } return $task; } /** * Executes right before the dispatcher tries to instantiate and run the * controller. * * @return boolean Return false to abort */ public function onBeforeDispatch() { return true; } /** * Sets up some environment variables, so we can work as usually on CLI, too. * * @return boolean Return false to abort */ public function onBeforeDispatchCLI() { JLoader::import('joomla.environment.uri'); JLoader::import('joomla.application.component.helper'); // Trick to create a valid url used by JURI $this->_originalPhpScript = ''; // We have no Application Helper (there is no Application!), so I have to define these constants manually $option = $this->input->get('option', '', 'cmd'); if ($option) { $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($option); if (!defined('JPATH_COMPONENT')) { define('JPATH_COMPONENT', $componentPaths['main']); } if (!defined('JPATH_COMPONENT_SITE')) { define('JPATH_COMPONENT_SITE', $componentPaths['site']); } if (!defined('JPATH_COMPONENT_ADMINISTRATOR')) { define('JPATH_COMPONENT_ADMINISTRATOR', $componentPaths['admin']); } } return true; } /** * Executes right after the dispatcher runs the controller. * * @return boolean Return false to abort */ public function onAfterDispatch() { // If we have to log out the user, please do so now if ($this->fofAuth_LogoutOnReturn && $this->_fofAuth_isLoggedIn) { FOFPlatform::getInstance()->logoutUser(); } return true; } /** * Transparently authenticates a user * * @return void */ public function transparentAuthentication() { // Only run when there is no logged in user if (!FOFPlatform::getInstance()->getUser()->guest) { return; } // @todo Check the format $format = $this->input->getCmd('format', 'html'); if (!in_array($format, $this->fofAuth_Formats)) { return; } foreach ($this->fofAuth_AuthMethods as $method) { // If we're already logged in, don't bother if ($this->_fofAuth_isLoggedIn) { continue; } // This will hold our authentication data array (username, password) $authInfo = null; switch ($method) { case 'HTTPBasicAuth_TOTP': if (empty($this->fofAuth_Key)) { continue; } if (!isset($_SERVER['PHP_AUTH_USER'])) { continue; } if (!isset($_SERVER['PHP_AUTH_PW'])) { continue; } if ($_SERVER['PHP_AUTH_USER'] != '_fof_auth') { continue; } $encryptedData = $_SERVER['PHP_AUTH_PW']; $authInfo = $this->_decryptWithTOTP($encryptedData); break; case 'QueryString_TOTP': $encryptedData = $this->input->get('_fofauthentication', '', 'raw'); if (empty($encryptedData)) { continue; } $authInfo = $this->_decryptWithTOTP($encryptedData); break; case 'HTTPBasicAuth_Plaintext': if (!isset($_SERVER['PHP_AUTH_USER'])) { continue; } if (!isset($_SERVER['PHP_AUTH_PW'])) { continue; } $authInfo = array( 'username' => $_SERVER['PHP_AUTH_USER'], 'password' => $_SERVER['PHP_AUTH_PW'] ); break; case 'QueryString_Plaintext': $jsonencoded = $this->input->get('_fofauthentication', '', 'raw'); if (empty($jsonencoded)) { continue; } $authInfo = json_decode($jsonencoded, true); if (!is_array($authInfo)) { $authInfo = null; } elseif (!array_key_exists('username', $authInfo) || !array_key_exists('password', $authInfo)) { $authInfo = null; } break; case 'SplitQueryString_Plaintext': $authInfo = array( 'username' => $this->input->get('_fofauthentication_username', '', 'raw'), 'password' => $this->input->get('_fofauthentication_password', '', 'raw'), ); if (empty($authInfo['username'])) { $authInfo = null; } break; default: continue; break; } // No point trying unless we have a username and password if (!is_array($authInfo)) { continue; } $this->_fofAuth_isLoggedIn = FOFPlatform::getInstance()->loginUser($authInfo); } } /** * Decrypts a transparent authentication message using a TOTP * * @param string $encryptedData The encrypted data * * @return array The decrypted data */ private function _decryptWithTOTP($encryptedData) { if (empty($this->fofAuth_Key)) { $this->_fofAuth_CryptoKey = null; return null; } $totp = new FOFEncryptTotp($this->fofAuth_timeStep); $period = $totp->getPeriod(); $period--; for ($i = 0; $i <= 2; $i++) { $time = ($period + $i) * $this->fofAuth_timeStep; $otp = $totp->getCode($this->fofAuth_Key, $time); $this->_fofAuth_CryptoKey = hash('sha256', $this->fofAuth_Key . $otp); $aes = new FOFEncryptAes($this->_fofAuth_CryptoKey); $ret = $aes->decryptString($encryptedData); $ret = rtrim($ret, "\000"); $ret = json_decode($ret, true); if (!is_array($ret)) { continue; } if (!array_key_exists('username', $ret)) { continue; } if (!array_key_exists('password', $ret)) { continue; } // Successful decryption! return $ret; } // Obviously if we're here we could not decrypt anything. Bail out. $this->_fofAuth_CryptoKey = null; return null; } /** * Creates a decryption key for use with the TOTP decryption method * * @param integer $time The timestamp used for TOTP calculation, leave empty to use current timestamp * * @return string THe encryption key */ private function _createDecryptionKey($time = null) { $totp = new FOFEncryptTotp($this->fofAuth_timeStep); $otp = $totp->getCode($this->fofAuth_Key, $time); $key = hash('sha256', $this->fofAuth_Key . $otp); return $key; } /** * Main function to detect if we're running in a CLI environment and we're admin * * @return array isCLI and isAdmin. It's not an associtive array, so we can use list. */ public static function isCliAdmin() { static $isCLI = null; static $isAdmin = null; if (is_null($isCLI) && is_null($isAdmin)) { $isCLI = FOFPlatform::getInstance()->isCli(); $isAdmin = FOFPlatform::getInstance()->isBackend(); } return array($isCLI, $isAdmin); } } PKY[k66fof/dispatcher/index.htmlnuW+APKY[k66fof/toolbar/index.htmlnuW+APKY[q~.j.jfof/toolbar/toolbar.phpnuW+AgetCmd('option', 'com_foobar'); $input->set('option', $config['option']); $config['input'] = $input; $className = ucfirst(str_replace('com_', '', $config['option'])) . 'Toolbar'; if (!class_exists($className)) { $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($config['option']); $searchPaths = array( $componentPaths['main'], $componentPaths['main'] . '/toolbars', $componentPaths['alt'], $componentPaths['alt'] . '/toolbars' ); if (array_key_exists('searchpath', $config)) { array_unshift($searchPaths, $config['searchpath']); } $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); $path = $filesystem->pathFind( $searchPaths, 'toolbar.php' ); if ($path) { require_once $path; } } if (!class_exists($className)) { $className = 'FOFToolbar'; } $instance = new $className($config); $instances[$hash] = $instance; } return $instances[$hash]; } /** * Public constructor * * @param array $config The configuration array of the component */ public function __construct($config = array()) { // Make sure $config is an array if (is_object($config)) { $config = (array) $config; } elseif (!is_array($config)) { $config = array(); } // Cache the config $this->config = $config; // Get the input for this MVC triad if (array_key_exists('input', $config)) { $this->input = $config['input']; } else { $this->input = new FOFInput; } // Get the default values for the component and view names $this->component = $this->input->getCmd('option', 'com_foobar'); // Overrides from the config if (array_key_exists('option', $config)) { $this->component = $config['option']; } $this->input->set('option', $this->component); // Get default permissions (can be overriden by the view) $platform = FOFPlatform::getInstance(); $perms = (object) array( 'manage' => $platform->authorise('core.manage', $this->input->getCmd('option', 'com_foobar')), 'create' => $platform->authorise('core.create', $this->input->getCmd('option', 'com_foobar')), 'edit' => $platform->authorise('core.edit', $this->input->getCmd('option', 'com_foobar')), 'editstate' => $platform->authorise('core.edit.state', $this->input->getCmd('option', 'com_foobar')), 'delete' => $platform->authorise('core.delete', $this->input->getCmd('option', 'com_foobar')), ); // Save front-end toolbar and submenu rendering flags if present in the config if (array_key_exists('renderFrontendButtons', $config)) { $this->renderFrontendButtons = $config['renderFrontendButtons']; } if (array_key_exists('renderFrontendSubmenu', $config)) { $this->renderFrontendSubmenu = $config['renderFrontendSubmenu']; } // If not in the administrative area, load the JToolbarHelper if (!FOFPlatform::getInstance()->isBackend()) { $platformDirs = FOFPlatform::getInstance()->getPlatformBaseDirs(); // Pretty ugly require... require_once $platformDirs['root'] . '/administrator/includes/toolbar.php'; // Things to do if we have to render a front-end toolbar if ($this->renderFrontendButtons) { // Load back-end toolbar language files in front-end FOFPlatform::getInstance()->loadTranslations(''); // Load the core Javascript JHtml::_('behavior.framework', true); } } // Store permissions in the local toolbar object $this->perms = $perms; } /** * Renders the toolbar for the current view and task * * @param string $view The view of the component * @param string $task The exact task of the view * @param FOFInput $input An optional input object used to determine the defaults * * @return void */ public function renderToolbar($view = null, $task = null, $input = null) { if (!empty($input)) { $saveInput = $this->input; $this->input = $input; } // If tmpl=component the default behaviour is to not render the toolbar if ($this->input->getCmd('tmpl', '') == 'component') { $render_toolbar = false; } else { $render_toolbar = true; } // If there is a render_toolbar=0 in the URL, do not render a toolbar $render_toolbar = $this->input->getBool('render_toolbar', $render_toolbar); if (!$render_toolbar) { return; } // Get the view and task if (empty($view)) { $view = $this->input->getCmd('view', 'cpanel'); } if (empty($task)) { $task = $this->input->getCmd('task', 'default'); } $this->view = $view; $this->task = $task; $view = FOFInflector::pluralize($view); $component = $input->get('option', 'com_foobar', 'cmd'); $configProvider = new FOFConfigProvider; $toolbar = $configProvider->get( $component . '.views.' . '.toolbar' ); // If we have a toolbar config specified if (!empty($toolbar)) { return $this->renderFromConfig($toolbar); } // Check for an onViewTask method $methodName = 'on' . ucfirst($view) . ucfirst($task); if (method_exists($this, $methodName)) { return $this->$methodName(); } // Check for an onView method $methodName = 'on' . ucfirst($view); if (method_exists($this, $methodName)) { return $this->$methodName(); } // Check for an onTask method $methodName = 'on' . ucfirst($task); if (method_exists($this, $methodName)) { return $this->$methodName(); } if (!empty($input)) { $this->input = $saveInput; } } /** * Renders the toolbar for the component's Control Panel page * * @return void */ public function onCpanelsBrowse() { if (FOFPlatform::getInstance()->isBackend() || $this->renderFrontendSubmenu) { $this->renderSubmenu(); } if (!FOFPlatform::getInstance()->isBackend() && !$this->renderFrontendButtons) { return; } $option = $this->input->getCmd('option', 'com_foobar'); JToolBarHelper::title(JText::_(strtoupper($option)), str_replace('com_', '', $option)); JToolBarHelper::preferences($option, 550, 875); } /** * Renders the toolbar for the component's Browse pages (the plural views) * * @return void */ public function onBrowse() { // On frontend, buttons must be added specifically if (FOFPlatform::getInstance()->isBackend() || $this->renderFrontendSubmenu) { $this->renderSubmenu(); } if (!FOFPlatform::getInstance()->isBackend() && !$this->renderFrontendButtons) { return; } // Set toolbar title $option = $this->input->getCmd('option', 'com_foobar'); $subtitle_key = strtoupper($option . '_TITLE_' . $this->input->getCmd('view', 'cpanel')); JToolBarHelper::title(JText::_(strtoupper($option)) . ': ' . JText::_($subtitle_key), str_replace('com_', '', $option)); // Add toolbar buttons if ($this->perms->create) { if (version_compare(JVERSION, '3.0', 'ge')) { JToolBarHelper::addNew(); } else { JToolBarHelper::addNewX(); } } if ($this->perms->edit) { if (version_compare(JVERSION, '3.0', 'ge')) { JToolBarHelper::editList(); } else { JToolBarHelper::editListX(); } } if ($this->perms->create || $this->perms->edit) { JToolBarHelper::divider(); } if ($this->perms->editstate) { JToolBarHelper::publishList(); JToolBarHelper::unpublishList(); JToolBarHelper::divider(); } if ($this->perms->delete) { $msg = JText::_($this->input->getCmd('option', 'com_foobar') . '_CONFIRM_DELETE'); JToolBarHelper::deleteList($msg); } } /** * Renders the toolbar for the component's Read pages * * @return void */ public function onRead() { // On frontend, buttons must be added specifically if (FOFPlatform::getInstance()->isBackend() || $this->renderFrontendSubmenu) { $this->renderSubmenu(); } if (!FOFPlatform::getInstance()->isBackend() && !$this->renderFrontendButtons) { return; } $option = $this->input->getCmd('option', 'com_foobar'); $componentName = str_replace('com_', '', $option); // Set toolbar title $subtitle_key = strtoupper($option . '_TITLE_' . $this->input->getCmd('view', 'cpanel') . '_READ'); JToolBarHelper::title(JText::_(strtoupper($option)) . ': ' . JText::_($subtitle_key), $componentName); // Set toolbar icons JToolBarHelper::back(); } /** * Renders the toolbar for the component's Add pages * * @return void */ public function onAdd() { // On frontend, buttons must be added specifically if (!FOFPlatform::getInstance()->isBackend() && !$this->renderFrontendButtons) { return; } $option = $this->input->getCmd('option', 'com_foobar'); $componentName = str_replace('com_', '', $option); // Set toolbar title $subtitle_key = strtoupper($option . '_TITLE_' . FOFInflector::pluralize($this->input->getCmd('view', 'cpanel'))) . '_EDIT'; JToolBarHelper::title(JText::_(strtoupper($option)) . ': ' . JText::_($subtitle_key), $componentName); // Set toolbar icons if ($this->perms->edit || $this->perms->editown) { // Show the apply button only if I can edit the record, otherwise I'll return to the edit form and get a // 403 error since I can't do that JToolBarHelper::apply(); } JToolBarHelper::save(); if ($this->perms->create) { JToolBarHelper::custom('savenew', 'save-new.png', 'save-new_f2.png', 'JTOOLBAR_SAVE_AND_NEW', false); } JToolBarHelper::cancel(); } /** * Renders the toolbar for the component's Edit pages * * @return void */ public function onEdit() { // On frontend, buttons must be added specifically if (!FOFPlatform::getInstance()->isBackend() && !$this->renderFrontendButtons) { return; } $this->onAdd(); } /** * Removes all links from the link bar * * @return void */ public function clearLinks() { $this->linkbar = array(); } /** * Get the link bar's link definitions * * @return array */ public function &getLinks() { return $this->linkbar; } /** * Append a link to the link bar * * @param string $name The text of the link * @param string|null $link The link to render; set to null to render a separator * @param boolean $active True if it's an active link * @param string|null $icon Icon class (used by some renderers, like the Bootstrap renderer) * @param string|null $parent The parent element (referenced by name)) Thsi will create a dropdown list * * @return void */ public function appendLink($name, $link = null, $active = false, $icon = null, $parent = '') { $linkDefinition = array( 'name' => $name, 'link' => $link, 'active' => $active, 'icon' => $icon ); if (empty($parent)) { $this->linkbar[$name] = $linkDefinition; } else { if (!array_key_exists($parent, $this->linkbar)) { $parentElement = $linkDefinition; $parentElement['link'] = null; $this->linkbar[$parent] = $parentElement; $parentElement['items'] = array(); } else { $parentElement = $this->linkbar[$parent]; if (!array_key_exists('dropdown', $parentElement) && !empty($parentElement['link'])) { $newSubElement = $parentElement; $parentElement['items'] = array($newSubElement); } } $parentElement['items'][] = $linkDefinition; $parentElement['dropdown'] = true; if($active) { $parentElement['active'] = true; } $this->linkbar[$parent] = $parentElement; } } /** * Prefixes (some people erroneously call this "prepend" – there is no such word) a link to the link bar * * @param string $name The text of the link * @param string|null $link The link to render; set to null to render a separator * @param boolean $active True if it's an active link * @param string|null $icon Icon class (used by some renderers, like the Bootstrap renderer) * * @return void */ public function prefixLink($name, $link = null, $active = false, $icon = null) { $linkDefinition = array( 'name' => $name, 'link' => $link, 'active' => $active, 'icon' => $icon ); array_unshift($this->linkbar, $linkDefinition); } /** * Renders the submenu (toolbar links) for all detected views of this component * * @return void */ public function renderSubmenu() { $views = $this->getMyViews(); if (empty($views)) { return; } $activeView = $this->input->getCmd('view', 'cpanel'); foreach ($views as $view) { // Get the view name $key = strtoupper($this->component) . '_TITLE_' . strtoupper($view); if (strtoupper(JText::_($key)) == $key) { $altview = FOFInflector::isPlural($view) ? FOFInflector::singularize($view) : FOFInflector::pluralize($view); $key2 = strtoupper($this->component) . '_TITLE_' . strtoupper($altview); if (strtoupper(JText::_($key2)) == $key2) { $name = ucfirst($view); } else { $name = JText::_($key2); } } else { $name = JText::_($key); } $link = 'index.php?option=' . $this->component . '&view=' . $view; $active = $view == $activeView; $this->appendLink($name, $link, $active); } } /** * Automatically detects all views of the component * * @return array A list of all views, in the order to be displayed in the toolbar submenu */ protected function getMyViews() { $views = array(); $t_views = array(); $using_meta = false; $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($this->component); $searchPath = $componentPaths['main'] . '/views'; $filesystem = FOFPlatform::getInstance()->getIntegrationObject('filesystem'); $allFolders = $filesystem->folderFolders($searchPath); if (!empty($allFolders)) { foreach ($allFolders as $folder) { $view = $folder; // View already added if (in_array(FOFInflector::pluralize($view), $t_views)) { continue; } // Do we have a 'skip.xml' file in there? $files = $filesystem->folderFiles($searchPath . '/' . $view, '^skip\.xml$'); if (!empty($files)) { continue; } // Do we have extra information about this view? (ie. ordering) $meta = $filesystem->folderFiles($searchPath . '/' . $view, '^metadata\.xml$'); // Not found, do we have it inside the plural one? if (!$meta) { $plural = FOFInflector::pluralize($view); if (in_array($plural, $allFolders)) { $view = $plural; $meta = $filesystem->folderFiles($searchPath . '/' . $view, '^metadata\.xml$'); } } if (!empty($meta)) { $using_meta = true; $xml = simplexml_load_file($searchPath . '/' . $view . '/' . $meta[0]); $order = (int) $xml->foflib->ordering; } else { // Next place. It's ok since the index are 0-based and count is 1-based if (!isset($to_order)) { $to_order = array(); } $order = count($to_order); } $view = FOFInflector::pluralize($view); $t_view = new stdClass; $t_view->ordering = $order; $t_view->view = $view; $to_order[] = $t_view; $t_views[] = $view; } } FOFUtilsArray::sortObjects($to_order, 'ordering'); $views = FOFUtilsArray::getColumn($to_order, 'view'); // If not using the metadata file, let's put the cpanel view on top if (!$using_meta) { $cpanel = array_search('cpanels', $views); if ($cpanel !== false) { unset($views[$cpanel]); array_unshift($views, 'cpanels'); } } return $views; } /** * Return the front-end toolbar rendering flag * * @return boolean */ public function getRenderFrontendButtons() { return $this->renderFrontendButtons; } /** * Return the front-end submenu rendering flag * * @return boolean */ public function getRenderFrontendSubmenu() { return $this->renderFrontendSubmenu; } /** * Render the toolbar from the configuration. * * @param array $toolbar The toolbar definition * * @return void */ private function renderFromConfig(array $toolbar) { if (FOFPlatform::getInstance()->isBackend() || $this->renderFrontendSubmenu) { $this->renderSubmenu(); } if (!FOFPlatform::getInstance()->isBackend() && !$this->renderFrontendButtons) { return; } // Render each element foreach ($toolbar as $elementType => $elementAttributes) { $value = isset($elementAttributes['value']) ? $elementAttributes['value'] : null; $this->renderToolbarElement($elementType, $value, $elementAttributes); } return; } /** * Render a toolbar element. * * @param string $type The element type. * @param mixed $value The element value. * @param array $attributes The element attributes. * * @return void * * @throws InvalidArgumentException */ private function renderToolbarElement($type, $value = null, array $attributes = array()) { switch ($type) { case 'title': $icon = isset($attributes['icon']) ? $attributes['icon'] : 'generic.png'; JToolbarHelper::title($value, $icon); break; case 'divider': JToolbarHelper::divider(); break; case 'custom': $task = isset($attributes['task']) ? $attributes['task'] : ''; $icon = isset($attributes['icon']) ? $attributes['icon'] : ''; $iconOver = isset($attributes['icon_over']) ? $attributes['icon_over'] : ''; $alt = isset($attributes['alt']) ? $attributes['alt'] : ''; $listSelect = isset($attributes['list_select']) ? FOFStringUtils::toBool($attributes['list_select']) : true; JToolbarHelper::custom($task, $icon, $iconOver, $alt, $listSelect); break; case 'preview': $url = isset($attributes['url']) ? $attributes['url'] : ''; $update_editors = isset($attributes['update_editors']) ? FOFStringUtils::toBool($attributes['update_editors']) : false; JToolbarHelper::preview($url, $update_editors); break; case 'help': if (!isset($attributes['help'])) { throw new InvalidArgumentException( 'The help attribute is missing in the help button type.' ); } $ref = $attributes['help']; $com = isset($attributes['com']) ? FOFStringUtils::toBool($attributes['com']) : false; $override = isset($attributes['override']) ? $attributes['override'] : null; $component = isset($attributes['component']) ? $attributes['component'] : null; JToolbarHelper::help($ref, $com, $override, $component); break; case 'back': $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_BACK'; $href = isset($attributes['href']) ? $attributes['href'] : 'javascript:history.back();'; JToolbarHelper::back($alt, $href); break; case 'media_manager': $directory = isset($attributes['directory']) ? $attributes['directory'] : ''; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_UPLOAD'; JToolbarHelper::media_manager($directory, $alt); break; case 'assign': $task = isset($attributes['task']) ? $attributes['task'] : 'assign'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_ASSIGN'; JToolbarHelper::assign($task, $alt); break; case 'new': if ($this->perms->create) { $task = isset($attributes['task']) ? $attributes['task'] : 'add'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_NEW'; $check = isset($attributes['check']) ? FOFStringUtils::toBool($attributes['check']) : false; JToolbarHelper::addNew($task, $alt, $check); } break; case 'publish': if ($this->perms->editstate) { $task = isset($attributes['task']) ? $attributes['task'] : 'publish'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_PUBLISH'; $check = isset($attributes['check']) ? FOFStringUtils::toBool($attributes['check']) : false; JToolbarHelper::publish($task, $alt, $check); } break; case 'publishList': if ($this->perms->editstate) { $task = isset($attributes['task']) ? $attributes['task'] : 'publish'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_PUBLISH'; JToolbarHelper::publishList($task, $alt); } break; case 'unpublish': if ($this->perms->editstate) { $task = isset($attributes['task']) ? $attributes['task'] : 'unpublish'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_UNPUBLISH'; $check = isset($attributes['check']) ? FOFStringUtils::toBool($attributes['check']) : false; JToolbarHelper::unpublish($task, $alt, $check); } break; case 'unpublishList': if ($this->perms->editstate) { $task = isset($attributes['task']) ? $attributes['task'] : 'unpublish'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_UNPUBLISH'; JToolbarHelper::unpublishList($task, $alt); } break; case 'archiveList': if ($this->perms->editstate) { $task = isset($attributes['task']) ? $attributes['task'] : 'archive'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_ARCHIVE'; JToolbarHelper::archiveList($task, $alt); } break; case 'unarchiveList': if ($this->perms->editstate) { $task = isset($attributes['task']) ? $attributes['task'] : 'unarchive'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_UNARCHIVE'; JToolbarHelper::unarchiveList($task, $alt); } break; case 'editList': if ($this->perms->edit) { $task = isset($attributes['task']) ? $attributes['task'] : 'edit'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_EDIT'; JToolbarHelper::editList($task, $alt); } break; case 'editHtml': $task = isset($attributes['task']) ? $attributes['task'] : 'edit_source'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_EDIT_HTML'; JToolbarHelper::editHtml($task, $alt); break; case 'editCss': $task = isset($attributes['task']) ? $attributes['task'] : 'edit_css'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_EDIT_CSS'; JToolbarHelper::editCss($task, $alt); break; case 'deleteList': if ($this->perms->delete) { $msg = isset($attributes['msg']) ? $attributes['msg'] : ''; $task = isset($attributes['task']) ? $attributes['task'] : 'remove'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_DELETE'; JToolbarHelper::deleteList($msg, $task, $alt); } break; case 'trash': if ($this->perms->editstate) { $task = isset($attributes['task']) ? $attributes['task'] : 'remove'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_TRASH'; $check = isset($attributes['check']) ? FOFStringUtils::toBool($attributes['check']) : true; JToolbarHelper::trash($task, $alt, $check); } break; case 'apply': $task = isset($attributes['task']) ? $attributes['task'] : 'apply'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_APPLY'; JToolbarHelper::apply($task, $alt); break; case 'save': $task = isset($attributes['task']) ? $attributes['task'] : 'save'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_SAVE'; JToolbarHelper::save($task, $alt); break; case 'save2new': $task = isset($attributes['task']) ? $attributes['task'] : 'save2new'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_SAVE_AND_NEW'; JToolbarHelper::save2new($task, $alt); break; case 'save2copy': $task = isset($attributes['task']) ? $attributes['task'] : 'save2copy'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_SAVE_AS_COPY'; JToolbarHelper::save2copy($task, $alt); break; case 'checkin': $task = isset($attributes['task']) ? $attributes['task'] : 'checkin'; $alt = isset($attributes['alt']) ? $attributes['alt'] :'JTOOLBAR_CHECKIN'; $check = isset($attributes['check']) ? FOFStringUtils::toBool($attributes['check']) : true; JToolbarHelper::checkin($task, $alt, $check); break; case 'cancel': $task = isset($attributes['task']) ? $attributes['task'] : 'cancel'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JTOOLBAR_CANCEL'; JToolbarHelper::cancel($task, $alt); break; case 'preferences': if (!isset($attributes['component'])) { throw new InvalidArgumentException( 'The component attribute is missing in the preferences button type.' ); } $component = $attributes['component']; $height = isset($attributes['height']) ? $attributes['height'] : '550'; $width = isset($attributes['width']) ? $attributes['width'] : '875'; $alt = isset($attributes['alt']) ? $attributes['alt'] : 'JToolbar_Options'; $path = isset($attributes['path']) ? $attributes['path'] : ''; JToolbarHelper::preferences($component, $height, $width, $alt, $path); break; default: throw new InvalidArgumentException(sprintf('Unknown button type %s', $type)); } } } PKY[ dvvfof/hal/document.phpnuW+A_data = $data; $this->_links = new FOFHalLinks; } /** * Add a link to the document * * @param string $rel The relation of the link to the document. * See RFC 5988 http://tools.ietf.org/html/rfc5988#section-6.2.2 A document MUST always have * a "self" link. * @param FOFHalLink $link The actual link object * @param boolean $overwrite When false and a link of $rel relation exists, an array of links is created. Otherwise the * existing link is overwriten with the new one * * @see FOFHalLinks::addLink * * @return boolean True if the link was added to the collection */ public function addLink($rel, FOFHalLink $link, $overwrite = true) { return $this->_links->addLink($rel, $link, $overwrite); } /** * Add links to the document * * @param string $rel The relation of the link to the document. See RFC 5988 * @param array $links An array of FOFHalLink objects * @param boolean $overwrite When false and a link of $rel relation exists, an array of * links is created. Otherwise the existing link is overwriten * with the new one * * @see FOFHalLinks::addLinks * * @return boolean */ public function addLinks($rel, array $links, $overwrite = true) { return $this->_links->addLinks($rel, $links, $overwrite); } /** * Add data to the document * * @param stdClass $data The data to add * @param boolean $overwrite Should I overwrite existing data? * * @return void */ public function addData($data, $overwrite = true) { if (is_array($data)) { $data = (object) $data; } if ($overwrite) { $this->_data = $data; } else { if (!is_array($this->_data)) { $this->_data = array($this->_data); } $this->_data[] = $data; } } /** * Add an embedded document * * @param string $rel The relation of the embedded document to its container document * @param FOFHalDocument $document The document to add * @param boolean $overwrite Should I overwrite existing data with the same relation? * * @return boolean */ public function addEmbedded($rel, FOFHalDocument $document, $overwrite = true) { if (!array_key_exists($rel, $this->_embedded) || !$overwrite) { $this->_embedded[$rel] = $document; } elseif (array_key_exists($rel, $this->_embedded) && !$overwrite) { if (!is_array($this->_embedded[$rel])) { $this->_embedded[$rel] = array($this->_embedded[$rel]); } $this->_embedded[$rel][] = $document; } else { return false; } } /** * Returns the collection of links of this document * * @param string $rel The relation of the links to fetch. Skip to get all links. * * @return array */ public function getLinks($rel = null) { return $this->_links->getLinks($rel); } /** * Returns the collection of embedded documents * * @param string $rel Optional; the relation to return the embedded documents for * * @return array|FOFHalDocument */ public function getEmbedded($rel = null) { if (empty($rel)) { return $this->_embedded; } elseif (isset($this->_embedded[$rel])) { return $this->_embedded[$rel]; } else { return array(); } } /** * Return the data attached to this document * * @return array|stdClass */ public function getData() { return $this->_data; } /** * Instantiate and call a suitable renderer class to render this document * into the specified format. * * @param string $format The format to render the document into, e.g. 'json' * * @return string The rendered document * * @throws RuntimeException If the format is unknown, i.e. there is no suitable renderer */ public function render($format = 'json') { $class_name = 'FOFHalRender' . ucfirst($format); if (!class_exists($class_name, true)) { throw new RuntimeException("Unsupported HAL Document format '$format'. Render aborted."); } $renderer = new $class_name($this); return $renderer->render( array( 'data_key' => $this->_dataKey ) ); } } PKY[zY Y fof/hal/links.phpnuW+Acheck()) { return false; } if (!array_key_exists($rel, $this->_links) || $overwrite) { $this->_links[$rel] = $link; } elseif (array_key_exists($rel, $this->_links) && !$overwrite) { if (!is_array($this->_links[$rel])) { $this->_links[$rel] = array($this->_links[$rel]); } $this->_links[$rel][] = $link; } else { return false; } } /** * Add multiple links to the links collection * * @param string $rel The relation of the links to the document. See RFC 5988. * @param array $links An array of FOFHalLink objects * @param boolean $overwrite When false and a link of $rel relation exists, an array * of links is created. Otherwise the existing link is * overwriten with the new one * * @return boolean True if the link was added to the collection */ public function addLinks($rel, array $links, $overwrite = true) { if (empty($links)) { return false; } $localOverwrite = $overwrite; foreach ($links as $link) { if ($link instanceof FOFHalLink) { $this->addLink($rel, $link, $localOverwrite); } // After the first time we call this with overwrite on we have to // turn it off so that the other links are added to the set instead // of overwriting the first item that's already added. if ($localOverwrite) { $localOverwrite = false; } } } /** * Returns the collection of links * * @param string $rel Optional; the relation to return the links for * * @return array|FOFHalLink */ public function getLinks($rel = null) { if (empty($rel)) { return $this->_links; } elseif (isset($this->_links[$rel])) { return $this->_links[$rel]; } else { return array(); } } } PKY[ __fof/hal/render/interface.phpnuW+A_document = $document; } /** * Render a HAL document in JSON format * * @param array $options Rendering options. You can currently only set json_options (json_encode options) * * @return string The JSON representation of the HAL document */ public function render($options = array()) { if (isset($options['data_key'])) { $this->_dataKey = $options['data_key']; } if (isset($options['json_options'])) { $jsonOptions = $options['json_options']; } else { $jsonOptions = 0; } $serialiseThis = new stdClass; // Add links $collection = $this->_document->getLinks(); $serialiseThis->_links = new stdClass; foreach ($collection as $rel => $links) { if (!is_array($links)) { $serialiseThis->_links->$rel = $this->_getLink($links); } else { $serialiseThis->_links->$rel = array(); foreach ($links as $link) { array_push($serialiseThis->_links->$rel, $this->_getLink($link)); } } } // Add embedded documents $collection = $this->_document->getEmbedded(); if (!empty($collection)) { $serialiseThis->_embedded->$rel = new stdClass; foreach ($collection as $rel => $embeddeddocs) { if (!is_array($embeddeddocs)) { $embeddeddocs = array($embeddeddocs); } foreach ($embeddeddocs as $embedded) { $renderer = new FOFHalRenderJson($embedded); array_push($serialiseThis->_embedded->$rel, $renderer->render($options)); } } } // Add data $data = $this->_document->getData(); if (is_object($data)) { if ($data instanceof FOFTable) { $data = $data->getData(); } else { $data = (array) $data; } if (!empty($data)) { foreach ($data as $k => $v) { $serialiseThis->$k = $v; } } } elseif (is_array($data)) { $serialiseThis->{$this->_dataKey} = $data; } return json_encode($serialiseThis, $jsonOptions); } /** * Converts a FOFHalLink object into a stdClass object which will be used * for JSON serialisation * * @param FOFHalLink $link The link you want converted * * @return stdClass The converted link object */ protected function _getLink(FOFHalLink $link) { $ret = array( 'href' => $link->href ); if ($link->templated) { $ret['templated'] = 'true'; } if (!empty($link->name)) { $ret['name'] = $link->name; } if (!empty($link->hreflang)) { $ret['hreflang'] = $link->hreflang; } if (!empty($link->title)) { $ret['title'] = $link->title; } return (object) $ret; } } PKY[2?Q Q fof/hal/link.phpnuW+A_href * @param boolean $templated See $this->_templated * @param string $name See $this->_name * @param string $hreflang See $this->_hreflang * @param string $title See $this->_title * * @throws RuntimeException If $href is empty */ public function __construct($href, $templated = false, $name = null, $hreflang = null, $title = null) { if (empty($href)) { throw new RuntimeException('A HAL link must always have a non-empty href'); } $this->_href = $href; $this->_templated = $templated; $this->_name = $name; $this->_hreflang = $hreflang; $this->_title = $title; } /** * Is this a valid link? Checks the existence of required fields, not their * values. * * @return boolean */ public function check() { return !empty($this->_href); } /** * Magic getter for the protected properties * * @param string $name The name of the property to retrieve, sans the underscore * * @return mixed Null will always be returned if the property doesn't exist */ public function __get($name) { $property = '_' . $name; if (property_exists($this, $property)) { return $this->$property; } else { return null; } } /** * Magic setter for the protected properties * * @param string $name The name of the property to set, sans the underscore * @param mixed $value The value of the property to set * * @return void */ public function __set($name, $value) { if (($name == 'href') && empty($value)) { return; } $property = '_' . $name; if (property_exists($this, $property)) { $this->$property = $value; } } } PKY[k66fof/utils/object/index.htmlnuW+APKY[22fof/utils/object/object.phpnuW+AsetProperties($properties); } } /** * Magic method to convert the object to a string gracefully. * * @return string The classname. */ public function __toString() { return get_class($this); } /** * Sets a default value if not alreay assigned * * @param string $property The name of the property. * @param mixed $default The default value. * * @return mixed */ public function def($property, $default = null) { $value = $this->get($property, $default); return $this->set($property, $value); } /** * Returns a property of the object or the default value if the property is not set. * * @param string $property The name of the property. * @param mixed $default The default value. * * @return mixed The value of the property. */ public function get($property, $default = null) { if (isset($this->$property)) { return $this->$property; } return $default; } /** * Returns an associative array of object properties. * * @param boolean $public If true, returns only the public properties. * * @return array */ public function getProperties($public = true) { $vars = get_object_vars($this); if ($public) { foreach ($vars as $key => $value) { if ('_' == substr($key, 0, 1)) { unset($vars[$key]); } } } return $vars; } /** * Get the most recent error message. * * @param integer $i Option error index. * @param boolean $toString Indicates if JError objects should return their error message. * * @return string Error message */ public function getError($i = null, $toString = true) { // Find the error if ($i === null) { // Default, return the last message $error = end($this->_errors); } elseif (!array_key_exists($i, $this->_errors)) { // If $i has been specified but does not exist, return false return false; } else { $error = $this->_errors[$i]; } // Check if only the string is requested if ($error instanceof Exception && $toString) { return (string) $error; } return $error; } /** * Return all errors, if any. * * @return array Array of error messages or JErrors. */ public function getErrors() { return $this->_errors; } /** * Modifies a property of the object, creating it if it does not already exist. * * @param string $property The name of the property. * @param mixed $value The value of the property to set. * * @return mixed Previous value of the property. */ public function set($property, $value = null) { $previous = isset($this->$property) ? $this->$property : null; $this->$property = $value; return $previous; } /** * Set the object properties based on a named array/hash. * * @param mixed $properties Either an associative array or another object. * * @return boolean */ public function setProperties($properties) { if (is_array($properties) || is_object($properties)) { foreach ((array) $properties as $k => $v) { // Use the set function which might be overridden. $this->set($k, $v); } return true; } return false; } /** * Add an error message. * * @param string $error Error message. * * @return void */ public function setError($error) { array_push($this->_errors, $error); } } PKY[k66fof/utils/index.htmlnuW+APKY[>sg11fof/utils/array/array.phpnuW+A $v) { $array[$i] = (int) $v; } } else { if ($default === null) { $array = array(); } elseif (is_array($default)) { self::toInteger($default, null); $array = $default; } else { $array = array((int) $default); } } } /** * Utility function to map an array to a stdClass object. * * @param array &$array The array to map. * @param string $class Name of the class to create * * @return object The object mapped from the given array */ public static function toObject(&$array, $class = 'stdClass') { $obj = null; if (is_array($array)) { $obj = new $class; foreach ($array as $k => $v) { if (is_array($v)) { $obj->$k = self::toObject($v, $class); } else { $obj->$k = $v; } } } return $obj; } /** * Utility function to map an array to a string. * * @param array $array The array to map. * @param string $inner_glue The glue (optional, defaults to '=') between the key and the value. * @param string $outer_glue The glue (optional, defaults to ' ') between array elements. * @param boolean $keepOuterKey True if final key should be kept. * * @return string The string mapped from the given array */ public static function toString($array = null, $inner_glue = '=', $outer_glue = ' ', $keepOuterKey = false) { $output = array(); if (is_array($array)) { foreach ($array as $key => $item) { if (is_array($item)) { if ($keepOuterKey) { $output[] = $key; } // This is value is an array, go and do it again! $output[] = self::toString($item, $inner_glue, $outer_glue, $keepOuterKey); } else { $output[] = $key . $inner_glue . '"' . $item . '"'; } } } return implode($outer_glue, $output); } /** * Utility function to map an object to an array * * @param object $p_obj The source object * @param boolean $recurse True to recurse through multi-level objects * @param string $regex An optional regular expression to match on field names * * @return array The array mapped from the given object */ public static function fromObject($p_obj, $recurse = true, $regex = null) { if (is_object($p_obj)) { return self::_fromObject($p_obj, $recurse, $regex); } else { return null; } } /** * Utility function to map an object or array to an array * * @param mixed $item The source object or array * @param boolean $recurse True to recurse through multi-level objects * @param string $regex An optional regular expression to match on field names * * @return array The array mapped from the given object */ protected static function _fromObject($item, $recurse, $regex) { if (is_object($item)) { $result = array(); foreach (get_object_vars($item) as $k => $v) { if (!$regex || preg_match($regex, $k)) { if ($recurse) { $result[$k] = self::_fromObject($v, $recurse, $regex); } else { $result[$k] = $v; } } } } elseif (is_array($item)) { $result = array(); foreach ($item as $k => $v) { $result[$k] = self::_fromObject($v, $recurse, $regex); } } else { $result = $item; } return $result; } /** * Extracts a column from an array of arrays or objects * * @param array &$array The source array * @param string $index The index of the column or name of object property * * @return array Column of values from the source array */ public static function getColumn(&$array, $index) { $result = array(); if (is_array($array)) { foreach ($array as &$item) { if (is_array($item) && isset($item[$index])) { $result[] = $item[$index]; } elseif (is_object($item) && isset($item->$index)) { $result[] = $item->$index; } // Else ignore the entry } } return $result; } /** * Utility function to return a value from a named array or a specified default * * @param array &$array A named array * @param string $name The key to search for * @param mixed $default The default value to give if no key found * @param string $type Return type for the variable (INT, FLOAT, STRING, WORD, BOOLEAN, ARRAY) * * @return mixed The value from the source array */ public static function getValue(&$array, $name, $default = null, $type = '') { $result = null; if (isset($array[$name])) { $result = $array[$name]; } // Handle the default case if (is_null($result)) { $result = $default; } // Handle the type constraint switch (strtoupper($type)) { case 'INT': case 'INTEGER': // Only use the first integer value @preg_match('/-?[0-9]+/', $result, $matches); $result = @(int) $matches[0]; break; case 'FLOAT': case 'DOUBLE': // Only use the first floating point value @preg_match('/-?[0-9]+(\.[0-9]+)?/', $result, $matches); $result = @(float) $matches[0]; break; case 'BOOL': case 'BOOLEAN': $result = (bool) $result; break; case 'ARRAY': if (!is_array($result)) { $result = array($result); } break; case 'STRING': $result = (string) $result; break; case 'WORD': $result = (string) preg_replace('#\W#', '', $result); break; case 'NONE': default: // No casting necessary break; } return $result; } /** * Takes an associative array of arrays and inverts the array keys to values using the array values as keys. * * Example: * $input = array( * 'New' => array('1000', '1500', '1750'), * 'Used' => array('3000', '4000', '5000', '6000') * ); * $output = FOFUtilsArray::invert($input); * * Output would be equal to: * $output = array( * '1000' => 'New', * '1500' => 'New', * '1750' => 'New', * '3000' => 'Used', * '4000' => 'Used', * '5000' => 'Used', * '6000' => 'Used' * ); * * @param array $array The source array. * * @return array The inverted array. */ public static function invert($array) { $return = array(); foreach ($array as $base => $values) { if (!is_array($values)) { continue; } foreach ($values as $key) { // If the key isn't scalar then ignore it. if (is_scalar($key)) { $return[$key] = $base; } } } return $return; } /** * Method to determine if an array is an associative array. * * @param array $array An array to test. * * @return boolean True if the array is an associative array. */ public static function isAssociative($array) { if (is_array($array)) { foreach (array_keys($array) as $k => $v) { if ($k !== $v) { return true; } } } return false; } /** * Pivots an array to create a reverse lookup of an array of scalars, arrays or objects. * * @param array $source The source array. * @param string $key Where the elements of the source array are objects or arrays, the key to pivot on. * * @return array An array of arrays pivoted either on the value of the keys, or an individual key of an object or array. */ public static function pivot($source, $key = null) { $result = array(); $counter = array(); foreach ($source as $index => $value) { // Determine the name of the pivot key, and its value. if (is_array($value)) { // If the key does not exist, ignore it. if (!isset($value[$key])) { continue; } $resultKey = $value[$key]; $resultValue = &$source[$index]; } elseif (is_object($value)) { // If the key does not exist, ignore it. if (!isset($value->$key)) { continue; } $resultKey = $value->$key; $resultValue = &$source[$index]; } else { // Just a scalar value. $resultKey = $value; $resultValue = $index; } // The counter tracks how many times a key has been used. if (empty($counter[$resultKey])) { // The first time around we just assign the value to the key. $result[$resultKey] = $resultValue; $counter[$resultKey] = 1; } elseif ($counter[$resultKey] == 1) { // If there is a second time, we convert the value into an array. $result[$resultKey] = array( $result[$resultKey], $resultValue, ); $counter[$resultKey]++; } else { // After the second time, no need to track any more. Just append to the existing array. $result[$resultKey][] = $resultValue; } } unset($counter); return $result; } /** * Utility function to sort an array of objects on a given field * * @param array &$a An array of objects * @param mixed $k The key (string) or a array of key to sort on * @param mixed $direction Direction (integer) or an array of direction to sort in [1 = Ascending] [-1 = Descending] * @param mixed $caseSensitive Boolean or array of booleans to let sort occur case sensitive or insensitive * @param mixed $locale Boolean or array of booleans to let sort occur using the locale language or not * * @return array The sorted array of objects */ public static function sortObjects(&$a, $k, $direction = 1, $caseSensitive = true, $locale = false) { if (!is_array($locale) || !is_array($locale[0])) { $locale = array($locale); } self::$sortCase = (array) $caseSensitive; self::$sortDirection = (array) $direction; self::$sortKey = (array) $k; self::$sortLocale = $locale; usort($a, array(__CLASS__, '_sortObjects')); self::$sortCase = null; self::$sortDirection = null; self::$sortKey = null; self::$sortLocale = null; return $a; } /** * Callback function for sorting an array of objects on a key * * @param array &$a An array of objects * @param array &$b An array of objects * * @return integer Comparison status * * @see FOFUtilsArray::sortObjects() */ protected static function _sortObjects(&$a, &$b) { $key = self::$sortKey; for ($i = 0, $count = count($key); $i < $count; $i++) { if (isset(self::$sortDirection[$i])) { $direction = self::$sortDirection[$i]; } if (isset(self::$sortCase[$i])) { $caseSensitive = self::$sortCase[$i]; } if (isset(self::$sortLocale[$i])) { $locale = self::$sortLocale[$i]; } $va = $a->$key[$i]; $vb = $b->$key[$i]; if ((is_bool($va) || is_numeric($va)) && (is_bool($vb) || is_numeric($vb))) { $cmp = $va - $vb; } elseif ($caseSensitive) { $cmp = JString::strcmp($va, $vb, $locale); } else { $cmp = JString::strcasecmp($va, $vb, $locale); } if ($cmp > 0) { return $direction; } if ($cmp < 0) { return -$direction; } } return 0; } /** * Multidimensional array safe unique test * * @param array $myArray The array to make unique. * * @return array * * @see http://php.net/manual/en/function.array-unique.php */ public static function arrayUnique($myArray) { if (!is_array($myArray)) { return $myArray; } foreach ($myArray as &$myvalue) { $myvalue = serialize($myvalue); } $myArray = array_unique($myArray); foreach ($myArray as &$myvalue) { $myvalue = unserialize($myvalue); } return $myArray; } } PKY[k66fof/utils/array/index.htmlnuW+APKY[бfof/utils/observable/event.phpnuW+Aattach($this); // Set the subject to observe $this->_subject = &$subject; } /** * Method to trigger events. * The method first generates the even from the argument array. Then it unsets the argument * since the argument has no bearing on the event handler. * If the method exists it is called and returns its return value. If it does not exist it * returns null. * * @param array &$args Arguments * * @return mixed Routine return value */ public function update(&$args) { // First let's get the event from the argument array. Next we will unset the // event argument as it has no bearing on the method to handle the event. $event = $args['event']; unset($args['event']); /* * If the method to handle an event exists, call it and return its return * value. If it does not exist, return null. */ if (method_exists($this, $event)) { return call_user_func_array(array($this, $event), $args); } else { return null; } } } PKY[X3yaa#fof/utils/observable/dispatcher.phpnuW+A_state; } /** * Registers an event handler to the event dispatcher * * @param string $event Name of the event to register handler for * @param string $handler Name of the event handler * * @return void * * @throws InvalidArgumentException */ public function register($event, $handler) { // Are we dealing with a class or callback type handler? if (is_callable($handler)) { // Ok, function type event handler... let's attach it. $method = array('event' => $event, 'handler' => $handler); $this->attach($method); } elseif (class_exists($handler)) { // Ok, class type event handler... let's instantiate and attach it. $this->attach(new $handler($this)); } else { throw new InvalidArgumentException('Invalid event handler.'); } } /** * Triggers an event by dispatching arguments to all observers that handle * the event and returning their return values. * * @param string $event The event to trigger. * @param array $args An array of arguments. * * @return array An array of results from each function call. */ public function trigger($event, $args = array()) { $result = array(); /* * If no arguments were passed, we still need to pass an empty array to * the call_user_func_array function. */ $args = (array) $args; $event = strtolower($event); // Check if any plugins are attached to the event. if (!isset($this->_methods[$event]) || empty($this->_methods[$event])) { // No Plugins Associated To Event! return $result; } // Loop through all plugins having a method matching our event foreach ($this->_methods[$event] as $key) { // Check if the plugin is present. if (!isset($this->_observers[$key])) { continue; } // Fire the event for an object based observer. if (is_object($this->_observers[$key])) { $args['event'] = $event; $value = $this->_observers[$key]->update($args); } // Fire the event for a function based observer. elseif (is_array($this->_observers[$key])) { $value = call_user_func_array($this->_observers[$key]['handler'], $args); } if (isset($value)) { $result[] = $value; } } return $result; } /** * Attach an observer object * * @param object $observer An observer object to attach * * @return void */ public function attach($observer) { if (is_array($observer)) { if (!isset($observer['handler']) || !isset($observer['event']) || !is_callable($observer['handler'])) { return; } // Make sure we haven't already attached this array as an observer foreach ($this->_observers as $check) { if (is_array($check) && $check['event'] == $observer['event'] && $check['handler'] == $observer['handler']) { return; } } $this->_observers[] = $observer; end($this->_observers); $methods = array($observer['event']); } else { if (!($observer instanceof FOFUtilsObservableEvent)) { return; } // Make sure we haven't already attached this object as an observer $class = get_class($observer); foreach ($this->_observers as $check) { if ($check instanceof $class) { return; } } $this->_observers[] = $observer; //$methods = array_diff(get_class_methods($observer), get_class_methods('JPlugin')); $methods = get_class_methods($observer); } $key = key($this->_observers); foreach ($methods as $method) { $method = strtolower($method); if (!isset($this->_methods[$method])) { $this->_methods[$method] = array(); } $this->_methods[$method][] = $key; } } /** * Detach an observer object * * @param object $observer An observer object to detach. * * @return boolean True if the observer object was detached. */ public function detach($observer) { $retval = false; $key = array_search($observer, $this->_observers); if ($key !== false) { unset($this->_observers[$key]); $retval = true; foreach ($this->_methods as &$method) { $k = array_search($key, $method); if ($k !== false) { unset($method[$k]); } } } return $retval; } } PKY[k66fof/utils/observable/index.htmlnuW+APKY[Vfof/layout/index.htmlnuW+A PKY[;%-fof/layout/file.phpnuW+AgetIntegrationObject('filesystem'); if (is_null($this->fullPath) && !empty($this->layoutId)) { $parts = explode('.', $this->layoutId); $file = array_pop($parts); $filePath = implode('/', $parts); $suffixes = FOFPlatform::getInstance()->getTemplateSuffixes(); foreach ($suffixes as $suffix) { $files[] = $file . $suffix . '.php'; } $files[] = $file . '.php'; $platformDirs = FOFPlatform::getInstance()->getPlatformBaseDirs(); $prefix = FOFPlatform::getInstance()->isBackend() ? $platformDirs['admin'] : $platformDirs['root']; $possiblePaths = array( $prefix . '/templates/' . JFactory::getApplication()->getTemplate() . '/html/layouts/' . $filePath, $this->basePath . '/' . $filePath ); reset($files); while ((list(, $fileName) = each($files)) && is_null($this->fullPath)) { $r = $filesystem->pathFind($possiblePaths, $fileName); $this->fullPath = $r === false ? null : $r; } } return $this->fullPath; } } PKY[!fof/layout/helper.phpnuW+Arender($displayData); return $renderedLayout; } } PKY[&)QQfof/input/input.phpnuW+Adata[$name])) { return $this->_cleanVar($this->data[$name], $mask, $filter); } return $default; } /** * Returns a copy of the raw data stored in the class * * @return array */ public function getData() { return $this->data; } /** * Old static methods are now deprecated. This magic method makes sure there * is a continuity in our approach. The downside is that it's only compatible * with PHP 5.3.0. Sorry! * * @param string $name Name of the method we're calling * @param array $arguments The arguments passed to the method * * @return mixed */ public static function __callStatic($name, $arguments) { FOFPlatform::getInstance()->logDeprecated('FOFInput: static getXXX() methods are deprecated. Use the input object\'s methods instead.'); if (substr($name, 0, 3) == 'get') { // Initialise arguments $key = array_shift($arguments); $default = array_shift($arguments); $input = array_shift($arguments); $type = 'none'; $mask = 0; $type = strtolower(substr($name, 3)); if ($type == 'var') { $type = array_shift($arguments); $mask = array_shift($arguments); } if (is_null($type)) { $type = 'none'; } if (is_null($mask)) { $mask = 0; } if (!($input instanceof FOFInput) && !($input instanceof JInput)) { $input = new FOFInput($input); } return $input->get($key, $default, $type, $mask); } return false; } /** * Magic method to get filtered input data. * * @param mixed $name Name of the value to get. * @param string $arguments Default value to return if variable does not exist. * * @return boolean The filtered boolean input value. */ public function __call($name, $arguments) { if (substr($name, 0, 3) == 'get') { $filter = substr($name, 3); $default = null; $mask = 0; if (isset($arguments[1])) { $default = $arguments[1]; } if (isset($arguments[2])) { $mask = $arguments[2]; } return $this->get($arguments[0], $default, $filter, $mask); } } /** * Sets an input variable. WARNING: IT SHOULD NO LONGER BE USED! * * @param string $name The name of the variable to set * @param mixed $value The value to set it to * @param array &$input The input array or FOFInput object * @param boolean $overwrite Should I overwrite existing values (default: true) * * @return string Previous value * * @deprecated */ public static function setVar($name, $value = null, &$input = array(), $overwrite = true) { FOFPlatform::getInstance()->logDeprecated('FOFInput::setVar() is deprecated. Use set() instead.'); if (empty($input)) { return JRequest::setVar($name, $value, 'default', $overwrite); } elseif (is_string($input)) { return JRequest::setVar($name, $value, $input, $overwrite); } else { if (!$overwrite && array_key_exists($name, $input)) { return $input[$name]; } $previous = array_key_exists($name, $input) ? $input[$name] : null; if (is_array($input)) { $input[$name] = $value; } elseif ($input instanceof FOFInput) { $input->set($name, $value); } return $previous; } } /** * Custom filter implementation. Works better with arrays and allows the use * of a filter mask. * * @param mixed $var The variable (value) to clean * @param integer $mask The clean mask * @param string $type The variable type * * @return mixed */ protected function _cleanVar($var, $mask = 0, $type = null) { if (is_array($var)) { $temp = array(); foreach ($var as $k => $v) { $temp[$k] = self::_cleanVar($v, $mask); } return $temp; } // If the no trim flag is not set, trim the variable if (!($mask & 1) && is_string($var)) { $var = trim($var); } // Now we handle input filtering if ($mask & 2) { // If the allow raw flag is set, do not modify the variable $var = $var; } elseif ($mask & 4) { // If the allow HTML flag is set, apply a safe HTML filter to the variable $safeHtmlFilter = JFilterInput::getInstance(null, null, 1, 1); $var = $safeHtmlFilter->clean($var, $type); } else { $var = $this->filter->clean($var, $type); } return $var; } } PKY[k66fof/input/index.htmlnuW+APKY[78fof/version.txtnuW+A2.2.1 2014-03-09 12:54:48PKY[k66fof/string/index.htmlnuW+APKY[` WWfof/string/utils.phpnuW+A 100) { $value = substr($value, 0, 100); } return $value; } /** * Convert common norhern European languages' letters into plain ASCII. This * is a rudimentary transliteration. * * @param string $value The value to convert to ASCII * * @return string The converted string */ public static function toASCII($value) { $string = htmlentities(utf8_decode($value), null, 'ISO-8859-1'); $string = preg_replace( array('/ß/', '/&(..)lig;/', '/&([aouAOU])uml;/', '/&(.)[^;]*;/'), array('ss', "$1", "$1" . 'e', "$1"), $string ); return $string; } /** * Convert a string to a boolean. * * @param string $string The string. * * @return boolean The converted string */ public static function toBool($string) { $string = trim((string) $string); if ($string == 'true') { return true; } if ($string == 'false') { return false; } return (bool) $string; } } PKY[7fof/query/abstract.phpnuW+AlogDeprecated('FOFQueryAbstract is deprecated. Use JDatabaseQuery instead.'); if (is_null($db)) { $ret = FOFPlatform::getInstance()->getDbo()->getQuery(true); } else { $ret = $db->getQuery(true); } return $ret; } } PKY[k66fof/query/index.htmlnuW+APKY[l`]\\#fof/integration/joomla/platform.phpnuW+Aname = 'joomla'; $this->humanReadableName = 'Joomla!'; $this->version = defined('JVERSION') ? JVERSION : '0.0'; } /** * Checks if the current script is run inside a valid CMS execution * * @see FOFPlatformInterface::checkExecution() * * @return bool */ public function checkExecution() { return defined('_JEXEC'); } public function raiseError($code, $message) { if (version_compare($this->version, '3.0', 'ge')) { throw new Exception($message, $code); } else { return JError::raiseError($code, $message); } } /** * Is this platform enabled? * * @see FOFPlatformInterface::isEnabled() * * @return boolean */ public function isEnabled() { if (is_null($this->isEnabled)) { $this->isEnabled = true; // Make sure _JEXEC is defined if (!defined('_JEXEC')) { $this->isEnabled = false; } // We need JVERSION to be defined if ($this->isEnabled) { if (!defined('JVERSION')) { $this->isEnabled = false; } } // Check if JFactory exists if ($this->isEnabled) { if (!class_exists('JFactory')) { $this->isEnabled = false; } } // Check if JApplication exists if ($this->isEnabled) { $appExists = class_exists('JApplication'); $appExists = $appExists || class_exists('JCli'); $appExists = $appExists || class_exists('JApplicationCli'); if (!$appExists) { $this->isEnabled = false; } } } return $this->isEnabled; } /** * Main function to detect if we're running in a CLI environment and we're admin * * @return array isCLI and isAdmin. It's not an associtive array, so we can use list. */ protected function isCliAdmin() { static $isCLI = null; static $isAdmin = null; if (is_null($isCLI) && is_null($isAdmin)) { try { if (is_null(JFactory::$application)) { $isCLI = true; } else { $isCLI = JFactory::getApplication() instanceof JException; } } catch (Exception $e) { $isCLI = true; } if ($isCLI) { $isAdmin = false; } else { $isAdmin = !JFactory::$application ? false : JFactory::getApplication()->isAdmin(); } } return array($isCLI, $isAdmin); } /** * Returns absolute path to directories used by the CMS. * * @see FOFPlatformInterface::getPlatformBaseDirs() * * @return array A hash array with keys root, public, admin, tmp and log. */ public function getPlatformBaseDirs() { return array( 'root' => JPATH_ROOT, 'public' => JPATH_SITE, 'admin' => JPATH_ADMINISTRATOR, 'tmp' => JFactory::getConfig()->get('tmp_dir'), 'log' => JFactory::getConfig()->get('log_dir') ); } /** * Returns the base (root) directories for a given component. * * @param string $component The name of the component. For Joomla! this * is something like "com_example" * * @see FOFPlatformInterface::getComponentBaseDirs() * * @return array A hash array with keys main, alt, site and admin. */ public function getComponentBaseDirs($component) { if ($this->isFrontend()) { $mainPath = JPATH_SITE . '/components/' . $component; $altPath = JPATH_ADMINISTRATOR . '/components/' . $component; } else { $mainPath = JPATH_ADMINISTRATOR . '/components/' . $component; $altPath = JPATH_SITE . '/components/' . $component; } return array( 'main' => $mainPath, 'alt' => $altPath, 'site' => JPATH_SITE . '/components/' . $component, 'admin' => JPATH_ADMINISTRATOR . '/components/' . $component, ); } /** * Return a list of the view template paths for this component. * * @param string $component The name of the component. For Joomla! this * is something like "com_example" * @param string $view The name of the view you're looking a * template for * @param string $layout The layout name to load, e.g. 'default' * @param string $tpl The sub-template name to load (null by default) * @param boolean $strict If true, only the specified layout will be searched for. * Otherwise we'll fall back to the 'default' layout if the * specified layout is not found. * * @see FOFPlatformInterface::getViewTemplateDirs() * * @return array */ public function getViewTemplatePaths($component, $view, $layout = 'default', $tpl = null, $strict = false) { $isAdmin = $this->isBackend(); $basePath = $isAdmin ? 'admin:' : 'site:'; $basePath .= $component . '/'; $altBasePath = $basePath; $basePath .= $view . '/'; $altBasePath .= (FOFInflector::isSingular($view) ? FOFInflector::pluralize($view) : FOFInflector::singularize($view)) . '/'; if ($strict) { $paths = array( $basePath . $layout . ($tpl ? "_$tpl" : ''), $altBasePath . $layout . ($tpl ? "_$tpl" : ''), ); } else { $paths = array( $basePath . $layout . ($tpl ? "_$tpl" : ''), $basePath . $layout, $basePath . 'default' . ($tpl ? "_$tpl" : ''), $basePath . 'default', $altBasePath . $layout . ($tpl ? "_$tpl" : ''), $altBasePath . $layout, $altBasePath . 'default' . ($tpl ? "_$tpl" : ''), $altBasePath . 'default', ); $paths = array_unique($paths); } return $paths; } /** * Get application-specific suffixes to use with template paths. This allows * you to look for view template overrides based on the application version. * * @return array A plain array of suffixes to try in template names */ public function getTemplateSuffixes() { $jversion = new JVersion; $versionParts = explode('.', $jversion->RELEASE); $majorVersion = array_shift($versionParts); $suffixes = array( '.j' . str_replace('.', '', $jversion->getHelpVersion()), '.j' . $majorVersion, ); return $suffixes; } /** * Return the absolute path to the application's template overrides * directory for a specific component. We will use it to look for template * files instead of the regular component directorues. If the application * does not have such a thing as template overrides return an empty string. * * @param string $component The name of the component for which to fetch the overrides * @param boolean $absolute Should I return an absolute or relative path? * * @return string The path to the template overrides directory */ public function getTemplateOverridePath($component, $absolute = true) { list($isCli, $isAdmin) = $this->isCliAdmin(); if (!$isCli) { if ($absolute) { $path = JPATH_THEMES . '/'; } else { $path = $isAdmin ? 'administrator/templates/' : 'templates/'; } if (substr($component, 0, 7) == 'media:/') { $directory = 'media/' . substr($component, 7); } else { $directory = 'html/' . $component; } $path .= JFactory::getApplication()->getTemplate() . '/' . $directory; } else { $path = ''; } return $path; } /** * Load the translation files for a given component. * * @param string $component The name of the component. For Joomla! this * is something like "com_example" * * @see FOFPlatformInterface::loadTranslations() * * @return void */ public function loadTranslations($component) { if ($this->isBackend()) { $paths = array(JPATH_ROOT, JPATH_ADMINISTRATOR); } else { $paths = array(JPATH_ADMINISTRATOR, JPATH_ROOT); } $jlang = JFactory::getLanguage(); $jlang->load($component, $paths[0], 'en-GB', true); $jlang->load($component, $paths[0], null, true); $jlang->load($component, $paths[1], 'en-GB', true); $jlang->load($component, $paths[1], null, true); } /** * Authorise access to the component in the back-end. * * @param string $component The name of the component. * * @see FOFPlatformInterface::authorizeAdmin() * * @return boolean True to allow loading the component, false to halt loading */ public function authorizeAdmin($component) { if ($this->isBackend()) { // Master access check for the back-end, Joomla! 1.6 style. $user = JFactory::getUser(); if (!$user->authorise('core.manage', $component) && !$user->authorise('core.admin', $component)) { return false; } } return true; } /** * Return a user object. * * @param integer $id The user ID to load. Skip or use null to retrieve * the object for the currently logged in user. * * @see FOFPlatformInterface::getUser() * * @return JUser The JUser object for the specified user */ public function getUser($id = null) { return JFactory::getUser($id); } /** * Returns the JDocument object which handles this component's response. * * @see FOFPlatformInterface::getDocument() * * @return JDocument */ public function getDocument() { $document = null; if (!$this->isCli()) { try { $document = JFactory::getDocument(); } catch (Exception $exc) { $document = null; } } return $document; } /** * Returns an object to handle dates * * @param mixed $time The initial time * @param null $tzOffest The timezone offset * @param bool $locale Should I try to load a specific class for current language? * * @return JDate object */ public function getDate($time = 'now', $tzOffest = null, $locale = true) { if($locale) { return JFactory::getDate($time, $tzOffest); } else { return new JDate($time, $tzOffest); } } public function getLanguage() { return JFactory::getLanguage(); } public function getDbo() { return JFactory::getDbo(); } /** * This method will try retrieving a variable from the request (input) data. * * @param string $key The user state key for the variable * @param string $request The request variable name for the variable * @param FOFInput $input The FOFInput object with the request (input) data * @param mixed $default The default value. Default: null * @param string $type The filter type for the variable data. Default: none (no filtering) * @param boolean $setUserState Should I set the user state with the fetched value? * * @see FOFPlatformInterface::getUserStateFromRequest() * * @return mixed The value of the variable */ public function getUserStateFromRequest($key, $request, $input, $default = null, $type = 'none', $setUserState = true) { list($isCLI, $isAdmin) = $this->isCliAdmin(); if ($isCLI) { return $input->get($request, $default, $type); } $app = JFactory::getApplication(); if (method_exists($app, 'getUserState')) { $old_state = $app->getUserState($key, $default); } else { $old_state = null; } $cur_state = (!is_null($old_state)) ? $old_state : $default; $new_state = $input->get($request, null, $type); // Save the new value only if it was set in this request if ($setUserState) { if ($new_state !== null) { $app->setUserState($key, $new_state); } else { $new_state = $cur_state; } } elseif (is_null($new_state)) { $new_state = $cur_state; } return $new_state; } /** * Load plugins of a specific type. Obviously this seems to only be required * in the Joomla! CMS. * * @param string $type The type of the plugins to be loaded * * @see FOFPlatformInterface::importPlugin() * * @return void */ public function importPlugin($type) { if (!$this->isCli()) { JLoader::import('joomla.plugin.helper'); JPluginHelper::importPlugin($type); } } /** * Execute plugins (system-level triggers) and fetch back an array with * their return values. * * @param string $event The event (trigger) name, e.g. onBeforeScratchMyEar * @param array $data A hash array of data sent to the plugins as part of the trigger * * @see FOFPlatformInterface::runPlugins() * * @return array A simple array containing the results of the plugins triggered */ public function runPlugins($event, $data) { if (!$this->isCli()) { // IMPORTANT: DO NOT REPLACE THIS INSTANCE OF JDispatcher WITH ANYTHING ELSE. WE NEED JOOMLA!'S PLUGIN EVENT // DISPATCHER HERE, NOT OUR GENERIC EVENTS DISPATCHER $dispatcher = JDispatcher::getInstance(); return $dispatcher->trigger($event, $data); } else { return array(); } } /** * Perform an ACL check. * * @param string $action The ACL privilege to check, e.g. core.edit * @param string $assetname The asset name to check, typically the component's name * * @see FOFPlatformInterface::authorise() * * @return boolean True if the user is allowed this action */ public function authorise($action, $assetname) { if ($this->isCli()) { return true; } return JFactory::getUser()->authorise($action, $assetname); } /** * Is this the administrative section of the component? * * @see FOFPlatformInterface::isBackend() * * @return boolean */ public function isBackend() { list ($isCli, $isAdmin) = $this->isCliAdmin(); return $isAdmin && !$isCli; } /** * Is this the public section of the component? * * @see FOFPlatformInterface::isFrontend() * * @return boolean */ public function isFrontend() { list ($isCli, $isAdmin) = $this->isCliAdmin(); return !$isAdmin && !$isCli; } /** * Is this a component running in a CLI application? * * @see FOFPlatformInterface::isCli() * * @return boolean */ public function isCli() { list ($isCli, $isAdmin) = $this->isCliAdmin(); return !$isAdmin && $isCli; } /** * Is AJAX re-ordering supported? This is 100% Joomla!-CMS specific. All * other platforms should return false and never ask why. * * @see FOFPlatformInterface::supportsAjaxOrdering() * * @return boolean */ public function supportsAjaxOrdering() { return version_compare(JVERSION, '3.0', 'ge'); } /** * Is the global FOF cache enabled? * * @return boolean */ public function isGlobalFOFCacheEnabled() { return !(defined('JDEBUG') && JDEBUG); } /** * Saves something to the cache. This is supposed to be used for system-wide * FOF data, not application data. * * @param string $key The key of the data to save * @param string $content The actual data to save * * @return boolean True on success */ public function setCache($key, $content) { $registry = $this->getCacheObject(); $registry->set($key, $content); return $this->saveCache(); } /** * Retrieves data from the cache. This is supposed to be used for system-side * FOF data, not application data. * * @param string $key The key of the data to retrieve * @param string $default The default value to return if the key is not found or the cache is not populated * * @return string The cached value */ public function getCache($key, $default = null) { $registry = $this->getCacheObject(); return $registry->get($key, $default); } /** * Gets a reference to the cache object, loading it from the disk if * needed. * * @param boolean $force Should I forcibly reload the registry? * * @return JRegistry */ private function &getCacheObject($force = false) { // Check if we have to load the cache file or we are forced to do that if (is_null($this->_cache) || $force) { // Create a new JRegistry object JLoader::import('joomla.registry.registry'); $this->_cache = new JRegistry; // Try to get data from Joomla!'s cache $cache = JFactory::getCache('fof', ''); $data = $cache->get('cache', 'fof'); // If data is not found, fall back to the legacy (FOF 2.1.rc3 and earlier) method if ($data === false) { // Find the path to the file $cachePath = JPATH_CACHE . '/fof'; $filename = $cachePath . '/cache.php'; $filesystem = $this->getIntegrationObject('filesystem'); // Load the cache file if it exists. JRegistryFormatPHP fails // miserably, so I have to work around it. if ($filesystem->fileExists($filename)) { @include_once $filename; $filesystem->fileDelete($filename); $className = 'FOFCacheStorage'; if (class_exists($className)) { $object = new $className; $this->_cache->loadObject($object); $options = array( 'class' => 'FOFCacheStorage' ); $cache->store($this->_cache, 'cache', 'fof'); } } } else { $this->_cache = $data; } } return $this->_cache; } /** * Save the cache object back to disk * * @return boolean True on success */ private function saveCache() { // Get the JRegistry object of our cached data $registry = $this->getCacheObject(); $cache = JFactory::getCache('fof', ''); return $cache->store($registry, 'cache', 'fof'); } /** * Clears the cache of system-wide FOF data. You are supposed to call this in * your components' installation script post-installation and post-upgrade * methods or whenever you are modifying the structure of database tables * accessed by FOF. Please note that FOF's cache never expires and is not * purged by Joomla!. You MUST use this method to manually purge the cache. * * @return boolean True on success */ public function clearCache() { $false = false; $cache = JFactory::getCache('fof', ''); $cache->store($false, 'cache', 'fof'); } public function getConfig() { return JFactory::getConfig(); } /** * logs in a user * * @param array $authInfo authentification information * * @return boolean True on success */ public function loginUser($authInfo) { JLoader::import('joomla.user.authentication'); $options = array('remember' => false); $authenticate = JAuthentication::getInstance(); $response = $authenticate->authenticate($authInfo, $options); // User failed to authenticate: maybe he enabled two factor authentication? // Let's try again "manually", skipping the check vs two factor auth // Due the big mess with encryption algorithms and libraries, we are doing this extra check only // if we're in Joomla 2.5.18+ or 3.2.1+ if($response->status != JAuthentication::STATUS_SUCCESS && method_exists('JUserHelper', 'verifyPassword')) { $db = JFactory::getDbo(); $query = $db->getQuery(true) ->select('id, password') ->from('#__users') ->where('username=' . $db->quote($authInfo['username'])); $result = $db->setQuery($query)->loadObject(); if ($result) { $match = JUserHelper::verifyPassword($authInfo['password'], $result->password, $result->id); if ($match === true) { // Bring this in line with the rest of the system $user = JUser::getInstance($result->id); $response->email = $user->email; $response->fullname = $user->name; if (JFactory::getApplication()->isAdmin()) { $response->language = $user->getParam('admin_language'); } else { $response->language = $user->getParam('language'); } $response->status = JAuthentication::STATUS_SUCCESS; $response->error_message = ''; } } } if ($response->status == JAuthentication::STATUS_SUCCESS) { $this->importPlugin('user'); $results = $this->runPlugins('onLoginUser', array((array) $response, $options)); JLoader::import('joomla.user.helper'); $userid = JUserHelper::getUserId($response->username); $user = $this->getUser($userid); $session = JFactory::getSession(); $session->set('user', $user); return true; } return false; } /** * logs out a user * * @return boolean True on success */ public function logoutUser() { JLoader::import('joomla.user.authentication'); $app = JFactory::getApplication(); $options = array('remember' => false); $parameters = array('username' => $this->getUser()->username); return $app->triggerEvent('onLogoutUser', array($parameters, $options)); } public function logAddLogger($file) { JLog::addLogger(array('text_file' => $file), JLog::ALL, array('fof')); } /** * Logs a deprecated practice. In Joomla! this results in the $message being output in the * deprecated log file, found in your site's log directory. * * @param string $message The deprecated practice log message * * @return void */ public function logDeprecated($message) { JLog::add($message, JLog::WARNING, 'deprecated'); } public function logDebug($message) { JLog::add($message, JLog::DEBUG, 'fof'); } /** * Returns the root URI for the request. * * @param boolean $pathonly If false, prepend the scheme, host and port information. Default is false. * @param string $path The path * * @return string The root URI string. */ public function URIroot($pathonly = false, $path = null) { JLoader::import('joomla.environment.uri'); return JUri::root($pathonly, $path); } /** * Returns the base URI for the request. * * @param boolean $pathonly If false, prepend the scheme, host and port information. Default is false. * | * @return string The base URI string */ public function URIbase($pathonly = false) { JLoader::import('joomla.environment.uri'); return JUri::base($pathonly); } /** * Method to set a response header. If the replace flag is set then all headers * with the given name will be replaced by the new one (only if the current platform supports header caching) * * @param string $name The name of the header to set. * @param string $value The value of the header to set. * @param boolean $replace True to replace any headers with the same name. * * @return void */ public function setHeader($name, $value, $replace = false) { JResponse::setHeader($name, $value, $replace); } public function sendHeaders() { JResponse::sendHeaders(); } } PKY[;+0fof/integration/joomla/filesystem/filesystem.phpnuW+AgetComponentBaseDirs($component); $fofComponents[$component] = file_exists($componentPaths['admin'] . '/fof.xml'); } return $fofComponents[$component]; } /** * Creates class aliases. On systems where eval() is enabled it creates a * real class. On other systems it merely creates an alias. The eval() * method is preferred as class_aliases result in the name of the class * being instanciated not being available, making it impossible to create * a class instance without passing a $config array :( * * @param string $original The name of the original (existing) class * @param string $alias The name of the new (aliased) class * @param boolean $autoload Should I try to autoload the $original class? * * @return void */ private function class_alias($original, $alias, $autoload = true) { static $hasEval = null; if (is_null($hasEval)) { $hasEval = false; if (function_exists('ini_get')) { $disabled_functions = ini_get('disabled_functions'); if (!is_string($disabled_functions)) { $hasEval = true; } else { $disabled_functions = explode(',', $disabled_functions); $hasEval = !in_array('eval', $disabled_functions); } } } if (!class_exists($original, $autoload)) { return; } if ($hasEval) { $phpCode = "class $alias extends $original {}"; eval($phpCode); } else { class_alias($original, $alias, $autoload); } } /** * Autoload Controllers * * @param string $class_name The name of the class to load * * @return void */ public function autoload_fof_controller($class_name) { FOFPlatform::getInstance()->logDebug(__METHOD__ . "() autoloading $class_name"); static $isCli = null, $isAdmin = null; if (is_null($isCli) && is_null($isAdmin)) { list($isCli, $isAdmin) = FOFDispatcher::isCliAdmin(); } if (strpos($class_name, 'Controller') === false) { return; } // Change from camel cased into a lowercase array $class_modified = preg_replace('/(\s)+/', '_', $class_name); $class_modified = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $class_modified)); $parts = explode('_', $class_modified); // We need three parts in the name if (count($parts) != 3) { return; } // We need the second part to be "controller" if ($parts[1] != 'controller') { return; } // Get the information about this class $component_raw = $parts[0]; $component = 'com_' . $parts[0]; $view = $parts[2]; // Is this an FOF 2.1 or later component? if (!$this->isFOFComponent($component)) { return; } // Get the alternate view and class name (opposite singular/plural name) $alt_view = FOFInflector::isSingular($view) ? FOFInflector::pluralize($view) : FOFInflector::singularize($view); $alt_class = FOFInflector::camelize($component_raw . '_controller_' . $alt_view); // Get the component's paths $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($component); // Get the proper and alternate paths and file names $file = "/controllers/$view.php"; $altFile = "/controllers/$alt_view.php"; $path = $componentPaths['main']; $altPath = $componentPaths['alt']; // Try to find the proper class in the proper path if (file_exists($path . $file)) { @include_once $path . $file; } // Try to find the proper class in the alternate path if (!class_exists($class_name) && file_exists($altPath . $file)) { @include_once $altPath . $file; } // Try to find the alternate class in the proper path if (!class_exists($alt_class) && file_exists($path . $altFile)) { @include_once $path . $altFile; } // Try to find the alternate class in the alternate path if (!class_exists($alt_class) && file_exists($altPath . $altFile)) { @include_once $altPath . $altFile; } // If the alternate class exists just map the class to the alternate if (!class_exists($class_name) && class_exists($alt_class)) { $this->class_alias($alt_class, $class_name); } // No class found? Map to FOFController elseif (!class_exists($class_name)) { if ($view != 'default') { $defaultClass = FOFInflector::camelize($component_raw . '_controller_default'); $this->class_alias($defaultClass, $class_name); } else { $this->class_alias('FOFController', $class_name); } } } /** * Autoload Models * * @param string $class_name The name of the class to load * * @return void */ public function autoload_fof_model($class_name) { FOFPlatform::getInstance()->logDebug(__METHOD__ . "() autoloading $class_name"); static $isCli = null, $isAdmin = null; if (is_null($isCli) && is_null($isAdmin)) { list($isCli, $isAdmin) = FOFDispatcher::isCliAdmin(); } if (strpos($class_name, 'Model') === false) { return; } // Change from camel cased into a lowercase array $class_modified = preg_replace('/(\s)+/', '_', $class_name); $class_modified = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $class_modified)); $parts = explode('_', $class_modified); // We need three parts in the name if (count($parts) != 3) { return; } // We need the second part to be "model" if ($parts[1] != 'model') { return; } // Get the information about this class $component_raw = $parts[0]; $component = 'com_' . $parts[0]; $view = $parts[2]; // Is this an FOF 2.1 or later component? if (!$this->isFOFComponent($component)) { return; } // Get the alternate view and class name (opposite singular/plural name) $alt_view = FOFInflector::isSingular($view) ? FOFInflector::pluralize($view) : FOFInflector::singularize($view); $alt_class = FOFInflector::camelize($component_raw . '_model_' . $alt_view); // Get the proper and alternate paths and file names $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($component); $file = "/models/$view.php"; $altFile = "/models/$alt_view.php"; $path = $componentPaths['main']; $altPath = $componentPaths['alt']; // Try to find the proper class in the proper path if (file_exists($path . $file)) { @include_once $path . $file; } // Try to find the proper class in the alternate path if (!class_exists($class_name) && file_exists($altPath . $file)) { @include_once $altPath . $file; } // Try to find the alternate class in the proper path if (!class_exists($alt_class) && file_exists($path . $altFile)) { @include_once $path . $altFile; } // Try to find the alternate class in the alternate path if (!class_exists($alt_class) && file_exists($altPath . $altFile)) { @include_once $altPath . $altFile; } // If the alternate class exists just map the class to the alternate if (!class_exists($class_name) && class_exists($alt_class)) { $this->class_alias($alt_class, $class_name); } // No class found? Map to FOFModel elseif (!class_exists($class_name)) { if ($view != 'default') { $defaultClass = FOFInflector::camelize($component_raw . '_model_default'); $this->class_alias($defaultClass, $class_name); } else { $this->class_alias('FOFModel', $class_name, true); } } } /** * Autoload Views * * @param string $class_name The name of the class to load * * @return void */ public function autoload_fof_view($class_name) { FOFPlatform::getInstance()->logDebug(__METHOD__ . "() autoloading $class_name"); static $isCli = null, $isAdmin = null; if (is_null($isCli) && is_null($isAdmin)) { list($isCli, $isAdmin) = FOFDispatcher::isCliAdmin(); } if (strpos($class_name, 'View') === false) { return; } // Change from camel cased into a lowercase array $class_modified = preg_replace('/(\s)+/', '_', $class_name); $class_modified = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $class_modified)); $parts = explode('_', $class_modified); // We need at least three parts in the name if (count($parts) < 3) { return; } // We need the second part to be "view" if ($parts[1] != 'view') { return; } // Get the information about this class $component_raw = $parts[0]; $component = 'com_' . $parts[0]; $view = $parts[2]; if (count($parts) > 3) { $format = $parts[3]; } else { $input = new FOFInput; $format = $input->getCmd('format', 'html', 'cmd'); } // Is this an FOF 2.1 or later component? if (!$this->isFOFComponent($component)) { return; } // Get the alternate view and class name (opposite singular/plural name) $alt_view = FOFInflector::isSingular($view) ? FOFInflector::pluralize($view) : FOFInflector::singularize($view); $alt_class = FOFInflector::camelize($component_raw . '_view_' . $alt_view); // Get the proper and alternate paths and file names $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($component); $protoFile = "/models/$view"; $protoAltFile = "/models/$alt_view"; $path = $componentPaths['main']; $altPath = $componentPaths['alt']; $formats = array($format); if ($format != 'html') { $formats[] = 'raw'; } foreach ($formats as $currentFormat) { $file = $protoFile . '.' . $currentFormat . '.php'; $altFile = $protoAltFile . '.' . $currentFormat . '.php'; // Try to find the proper class in the proper path if (!class_exists($class_name) && file_exists($path . $file)) { @include_once $path . $file; } // Try to find the proper class in the alternate path if (!class_exists($class_name) && file_exists($altPath . $file)) { @include_once $altPath . $file; } // Try to find the alternate class in the proper path if (!class_exists($alt_class) && file_exists($path . $altFile)) { @include_once $path . $altFile; } // Try to find the alternate class in the alternate path if (!class_exists($alt_class) && file_exists($altPath . $altFile)) { @include_once $altPath . $altFile; } } // If the alternate class exists just map the class to the alternate if (!class_exists($class_name) && class_exists($alt_class)) { $this->class_alias($alt_class, $class_name); } // No class found? Map to FOFModel elseif (!class_exists($class_name)) { if ($view != 'default') { $defaultClass = FOFInflector::camelize($component_raw . '_view_default'); $this->class_alias($defaultClass, $class_name); } else { if (!file_exists(self::$fofPath . '/view/' . $format . '.php')) { $default_class = 'FOFView'; } else { $default_class = 'FOFView' . ucfirst($format); } $this->class_alias($default_class, $class_name, true); } } } /** * Autoload Tables * * @param string $class_name The name of the class to load * * @return void */ public function autoload_fof_table($class_name) { FOFPlatform::getInstance()->logDebug(__METHOD__ . "() autoloading $class_name"); static $isCli = null, $isAdmin = null; if (is_null($isCli) && is_null($isAdmin)) { list($isCli, $isAdmin) = FOFDispatcher::isCliAdmin(); } if (strpos($class_name, 'Table') === false) { return; } // Change from camel cased into a lowercase array $class_modified = preg_replace('/(\s)+/', '_', $class_name); $class_modified = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $class_modified)); $parts = explode('_', $class_modified); // We need three parts in the name if (count($parts) != 3) { return; } // We need the second part to be "model" if ($parts[1] != 'table') { return; } // Get the information about this class $component_raw = $parts[0]; $component = 'com_' . $parts[0]; $view = $parts[2]; // Is this an FOF 2.1 or later component? if (!$this->isFOFComponent($component)) { return; } // Get the alternate view and class name (opposite singular/plural name) $alt_view = FOFInflector::isSingular($view) ? FOFInflector::pluralize($view) : FOFInflector::singularize($view); $alt_class = FOFInflector::camelize($component_raw . '_table_' . $alt_view); // Get the proper and alternate paths and file names $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($component); $file = "/tables/$view.php"; $altFile = "/tables/$alt_view.php"; $path = $componentPaths['admin']; // Try to find the proper class in the proper path if (file_exists($path . $file)) { @include_once $path . $file; } // Try to find the alternate class in the proper path if (!class_exists($alt_class) && file_exists($path . $altFile)) { @include_once $path . $altFile; } // If the alternate class exists just map the class to the alternate if (!class_exists($class_name) && class_exists($alt_class)) { $this->class_alias($alt_class, $class_name); } // No class found? Map to FOFModel elseif (!class_exists($class_name)) { if ($view != 'default') { $defaultClass = FOFInflector::camelize($component_raw . '_table_default'); $this->class_alias($defaultClass, $class_name); } else { $this->class_alias('FOFTable', $class_name, true); } } } /** * Autoload Helpers * * @param string $class_name The name of the class to load * * @return void */ public function autoload_fof_helper($class_name) { FOFPlatform::getInstance()->logDebug(__METHOD__ . "() autoloading $class_name"); static $isCli = null, $isAdmin = null; if (is_null($isCli) && is_null($isAdmin)) { list($isCli, $isAdmin) = FOFDispatcher::isCliAdmin(); } if (strpos($class_name, 'Helper') === false) { return; } // Change from camel cased into a lowercase array $class_modified = preg_replace('/(\s)+/', '_', $class_name); $class_modified = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $class_modified)); $parts = explode('_', $class_modified); // We need three parts in the name if (count($parts) != 3) { return; } // We need the second part to be "model" if ($parts[1] != 'helper') { return; } // Get the information about this class $component_raw = $parts[0]; $component = 'com_' . $parts[0]; $view = $parts[2]; // Is this an FOF 2.1 or later component? if (!$this->isFOFComponent($component)) { return; } // Get the alternate view and class name (opposite singular/plural name) $alt_view = FOFInflector::isSingular($view) ? FOFInflector::pluralize($view) : FOFInflector::singularize($view); $alt_class = FOFInflector::camelize($component_raw . '_helper_' . $alt_view); // Get the proper and alternate paths and file names $componentPaths = FOFPlatform::getInstance()->getComponentBaseDirs($component); $file = "/helpers/$view.php"; $altFile = "/helpers/$alt_view.php"; $path = $componentPaths['main']; $altPath = $componentPaths['alt']; // Try to find the proper class in the proper path if (file_exists($path . $file)) { @include_once $path . $file; } // Try to find the proper class in the alternate path if (!class_exists($class_name) && file_exists($altPath . $file)) { @include_once $altPath . $file; } // Try to find the alternate class in the proper path if (!class_exists($alt_class) && file_exists($path . $altFile)) { @include_once $path . $altFile; } // Try to find the alternate class in the alternate path if (!class_exists($alt_class) && file_exists($altPath . $altFile)) { @include_once $altPath . $altFile; } // If the alternate class exists just map the class to the alternate if (!class_exists($class_name) && class_exists($alt_class)) { $this->class_alias($alt_class, $class_name); } } /** * Autoload Toolbars * * @param string $class_name The name of the class to load * * @return void */ public function autoload_fof_toolbar($class_name) { FOFPlatform::getInstance()->logDebug(__METHOD__ . "() autoloading $class_name"); static $isCli = null, $isAdmin = null; if (is_null($isCli) && is_null($isAdmin)) { list($isCli, $isAdmin) = FOFDispatcher::isCliAdmin(); } if (strpos($class_name, 'Toolbar') === false) { return; } // Change from camel cased into a lowercase array $class_modified = preg_replace('/(\s)+/', '_', $class_name); $class_modified = strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $class_modified)); $parts = explode('_', $class_modified); // We need two parts in the name if (count($parts) != 2) { return; } // We need the second part to be "model" if ($parts[1] != 'toolbar') { return; } // Get the information about this class $component_raw = $parts[0]; $component = 'com_' . $parts[0]; $platformDirs = FOFPlatform::getInstance()->getPlatformBaseDirs(); // Get the proper and alternate paths and file names $file = "/components/$component/toolbar.php"; $path = ($isAdmin || $isCli) ? $platformDirs['admin'] : $platformDirs['public']; $altPath = ($isAdmin || $isCli) ? $platformDirs['public'] : $platformDirs['admin']; // Try to find the proper class in the proper path if (file_exists($path . $file)) { @include_once $path . $file; } // Try to find the proper class in the alternate path if (!class_exists($class_name) && file_exists($altPath . $file)) { @include_once $altPath . $file; } // No class found? Map to FOFToolbar if (!class_exists($class_name)) { $this->class_alias('FOFToolbar', $class_name, true); } } /** * Autoload Fields * * @param string $class_name The name of the class to load * * @return void */ public function autoload_fof_field($class_name) { FOFPlatform::getInstance()->logDebug(__METHOD__ . "() autoloading $class_name"); // @todo } } PKY[M fof/autoloader/fof.phpnuW+APKY[pH::fof/form/form.phpnuW+Aload($data, $replace, $xpath) == false) { throw new RuntimeException('FOFForm::getInstance could not load form'); } } else { if ($forms[$name]->loadFile($data, $replace, $xpath) == false) { throw new RuntimeException('FOFForm::getInstance could not load file ' . $data . '.xml'); } } } return $forms[$name]; } /** * Returns the value of an attribute of the form itself * * @param string $attribute The name of the attribute * @param mixed $default Optional default value to return * * @return mixed * * @since 2.0 */ public function getAttribute($attribute, $default = null) { $value = $this->xml->attributes()->$attribute; if (is_null($value)) { return $default; } else { return (string) $value; } } /** * Loads the CSS files defined in the form, based on its cssfiles attribute * * @return void * * @since 2.0 */ public function loadCSSFiles() { // Support for CSS files $cssfiles = $this->getAttribute('cssfiles'); if (!empty($cssfiles)) { $cssfiles = explode(',', $cssfiles); foreach ($cssfiles as $cssfile) { FOFTemplateUtils::addCSS(trim($cssfile)); } } // Support for LESS files $lessfiles = $this->getAttribute('lessfiles'); if (!empty($lessfiles)) { $lessfiles = explode(',', $lessfiles); foreach ($lessfiles as $def) { $parts = explode('||', $def, 2); $lessfile = $parts[0]; $alt = (count($parts) > 1) ? trim($parts[1]) : null; FOFTemplateUtils::addLESS(trim($lessfile), $alt); } } } /** * Loads the Javascript files defined in the form, based on its jsfiles attribute * * @return void * * @since 2.0 */ public function loadJSFiles() { $jsfiles = $this->getAttribute('jsfiles'); if (empty($jsfiles)) { return; } $jsfiles = explode(',', $jsfiles); foreach ($jsfiles as $jsfile) { FOFTemplateUtils::addJS(trim($jsfile)); } } /** * Returns a reference to the protected $data object, allowing direct * access to and manipulation of the form's data. * * @return JRegistry The form's data registry * * @since 2.0 */ public function getData() { return $this->data; } /** * Attaches a FOFModel to this form * * @param FOFModel &$model The model to attach to the form * * @return void */ public function setModel(FOFModel &$model) { $this->model = $model; } /** * Returns the FOFModel attached to this form * * @return FOFModel */ public function &getModel() { return $this->model; } /** * Attaches a FOFView to this form * * @param FOFView &$view The view to attach to the form * * @return void */ public function setView(FOFView &$view) { $this->view = $view; } /** * Returns the FOFView attached to this form * * @return FOFView */ public function &getView() { return $this->view; } /** * Method to get an array of FOFFormHeader objects in the headerset. * * @return array The array of FOFFormHeader objects in the headerset. * * @since 2.0 */ public function getHeaderset() { $fields = array(); $elements = $this->findHeadersByGroup(); // If no field elements were found return empty. if (empty($elements)) { return $fields; } // Build the result array from the found field elements. foreach ($elements as $element) { // Get the field groups for the element. $attrs = $element->xpath('ancestor::headers[@name]/@name'); $groups = array_map('strval', $attrs ? $attrs : array()); $group = implode('.', $groups); // If the field is successfully loaded add it to the result array. if ($field = $this->loadHeader($element, $group)) { $fields[$field->id] = $field; } } return $fields; } /** * Method to get an array of
    elements from the form XML document which are * in a control group by name. * * @param mixed $group The optional dot-separated form group path on which to find the fields. * Null will return all fields. False will return fields not in a group. * @param boolean $nested True to also include fields in nested groups that are inside of the * group for which to find fields. * * @return mixed Boolean false on error or array of SimpleXMLElement objects. * * @since 2.0 */ protected function &findHeadersByGroup($group = null, $nested = false) { $false = false; $fields = array(); // Make sure there is a valid JForm XML document. if (!($this->xml instanceof SimpleXMLElement)) { return $false; } // Get only fields in a specific group? if ($group) { // Get the fields elements for a given group. $elements = &$this->findHeader($group); // Get all of the field elements for the fields elements. foreach ($elements as $element) { // If there are field elements add them to the return result. if ($tmp = $element->xpath('descendant::header')) { // If we also want fields in nested groups then just merge the arrays. if ($nested) { $fields = array_merge($fields, $tmp); } // If we want to exclude nested groups then we need to check each field. else { $groupNames = explode('.', $group); foreach ($tmp as $field) { // Get the names of the groups that the field is in. $attrs = $field->xpath('ancestor::headers[@name]/@name'); $names = array_map('strval', $attrs ? $attrs : array()); // If the field is in the specific group then add it to the return list. if ($names == (array) $groupNames) { $fields = array_merge($fields, array($field)); } } } } } } elseif ($group === false) { // Get only field elements not in a group. $fields = $this->xml->xpath('descendant::headers[not(@name)]/header | descendant::headers[not(@name)]/headerset/header '); } else { // Get an array of all the
    elements. $fields = $this->xml->xpath('//header'); } return $fields; } /** * Method to get a header field represented as a FOFFormHeader object. * * @param string $name The name of the header field. * @param string $group The optional dot-separated form group path on which to find the field. * @param mixed $value The optional value to use as the default for the field. * * @return mixed The FOFFormHeader object for the field or boolean false on error. * * @since 2.0 */ public function getHeader($name, $group = null, $value = null) { // Make sure there is a valid FOFForm XML document. if (!($this->xml instanceof SimpleXMLElement)) { return false; } // Attempt to find the field by name and group. $element = $this->findHeader($name, $group); // If the field element was not found return false. if (!$element) { return false; } return $this->loadHeader($element, $group, $value); } /** * Method to get a header field represented as an XML element object. * * @param string $name The name of the form field. * @param string $group The optional dot-separated form group path on which to find the field. * * @return mixed The XML element object for the field or boolean false on error. * * @since 2.0 */ protected function findHeader($name, $group = null) { $element = false; $fields = array(); // Make sure there is a valid JForm XML document. if (!($this->xml instanceof SimpleXMLElement)) { return false; } // Let's get the appropriate field element based on the method arguments. if ($group) { // Get the fields elements for a given group. $elements = &$this->findGroup($group); // Get all of the field elements with the correct name for the fields elements. foreach ($elements as $element) { // If there are matching field elements add them to the fields array. if ($tmp = $element->xpath('descendant::header[@name="' . $name . '"]')) { $fields = array_merge($fields, $tmp); } } // Make sure something was found. if (!$fields) { return false; } // Use the first correct match in the given group. $groupNames = explode('.', $group); foreach ($fields as &$field) { // Get the group names as strings for ancestor fields elements. $attrs = $field->xpath('ancestor::headerfields[@name]/@name'); $names = array_map('strval', $attrs ? $attrs : array()); // If the field is in the exact group use it and break out of the loop. if ($names == (array) $groupNames) { $element = &$field; break; } } } else { // Get an array of fields with the correct name. $fields = $this->xml->xpath('//header[@name="' . $name . '"]'); // Make sure something was found. if (!$fields) { return false; } // Search through the fields for the right one. foreach ($fields as &$field) { // If we find an ancestor fields element with a group name then it isn't what we want. if ($field->xpath('ancestor::headerfields[@name]')) { continue; } // Found it! else { $element = &$field; break; } } } return $element; } /** * Method to load, setup and return a FOFFormHeader object based on field data. * * @param string $element The XML element object representation of the form field. * @param string $group The optional dot-separated form group path on which to find the field. * @param mixed $value The optional value to use as the default for the field. * * @return mixed The FOFFormHeader object for the field or boolean false on error. * * @since 2.0 */ protected function loadHeader($element, $group = null, $value = null) { // Make sure there is a valid SimpleXMLElement. if (!($element instanceof SimpleXMLElement)) { return false; } // Get the field type. $type = $element['type'] ? (string) $element['type'] : 'field'; // Load the JFormField object for the field. $field = $this->loadHeaderType($type); // If the object could not be loaded, get a text field object. if ($field === false) { $field = $this->loadHeaderType('field'); } // Setup the FOFFormHeader object. $field->setForm($this); if ($field->setup($element, $value, $group)) { return $field; } else { return false; } } /** * Proxy for {@link FOFFormHelper::loadFieldType()}. * * @param string $type The field type. * @param boolean $new Flag to toggle whether we should get a new instance of the object. * * @return mixed FOFFormField object on success, false otherwise. * * @since 2.0 */ protected function loadFieldType($type, $new = true) { return FOFFormHelper::loadFieldType($type, $new); } /** * Proxy for {@link FOFFormHelper::loadHeaderType()}. * * @param string $type The field type. * @param boolean $new Flag to toggle whether we should get a new instance of the object. * * @return mixed FOFFormHeader object on success, false otherwise. * * @since 2.0 */ protected function loadHeaderType($type, $new = true) { return FOFFormHelper::loadHeaderType($type, $new); } /** * Proxy for {@link FOFFormHelper::loadRuleType()}. * * @param string $type The rule type. * @param boolean $new Flag to toggle whether we should get a new instance of the object. * * @return mixed JFormRule object on success, false otherwise. * * @see FOFFormHelper::loadRuleType() * @since 2.0 */ protected function loadRuleType($type, $new = true) { return FOFFormHelper::loadRuleType($type, $new); } /** * Proxy for {@link FOFFormHelper::addFieldPath()}. * * @param mixed $new A path or array of paths to add. * * @return array The list of paths that have been added. * * @since 2.0 */ public static function addFieldPath($new = null) { return FOFFormHelper::addFieldPath($new); } /** * Proxy for {@link FOFFormHelper::addHeaderPath()}. * * @param mixed $new A path or array of paths to add. * * @return array The list of paths that have been added. * * @since 2.0 */ public static function addHeaderPath($new = null) { return FOFFormHelper::addHeaderPath($new); } /** * Proxy for FOFFormHelper::addFormPath(). * * @param mixed $new A path or array of paths to add. * * @return array The list of paths that have been added. * * @see FOFFormHelper::addFormPath() * @since 2.0 */ public static function addFormPath($new = null) { return FOFFormHelper::addFormPath($new); } /** * Proxy for FOFFormHelper::addRulePath(). * * @param mixed $new A path or array of paths to add. * * @return array The list of paths that have been added. * * @see FOFFormHelper::addRulePath() * @since 2.0 */ public static function addRulePath($new = null) { return FOFFormHelper::addRulePath($new); } } PKY[u,,fof/form/header.phpnuW+A XML element that describes the header field. * * @var SimpleXMLElement * @since 2.0 */ protected $element; /** * The FOFForm object of the form attached to the header field. * * @var FOFForm * @since 2.0 */ protected $form; /** * The label for the header field. * * @var string * @since 2.0 */ protected $label; /** * The header HTML. * * @var string|null * @since 2.0 */ protected $header; /** * The filter HTML. * * @var string|null * @since 2.0 */ protected $filter; /** * The buttons HTML. * * @var string|null * @since 2.0 */ protected $buttons; /** * The options for a drop-down filter. * * @var array|null * @since 2.0 */ protected $options; /** * The name of the form field. * * @var string * @since 2.0 */ protected $name; /** * The name of the field. * * @var string * @since 2.0 */ protected $fieldname; /** * The group of the field. * * @var string * @since 2.0 */ protected $group; /** * The form field type. * * @var string * @since 2.0 */ protected $type; /** * The value of the filter. * * @var mixed * @since 2.0 */ protected $value; /** * The intended table data width (in pixels or percent). * * @var mixed * @since 2.0 */ protected $tdwidth; /** * The key of the filter value in the model state. * * @var mixed * @since 2.0 */ protected $filterSource; /** * Is this a sortable column? * * @var bool * @since 2.0 */ protected $sortable = false; /** * Method to instantiate the form field object. * * @param FOFForm $form The form to attach to the form field object. * * @since 2.0 */ public function __construct(FOFForm $form = null) { // If there is a form passed into the constructor set the form and form control properties. if ($form instanceof FOFForm) { $this->form = $form; } } /** * Method to get certain otherwise inaccessible properties from the form field object. * * @param string $name The property name for which to the the value. * * @return mixed The property value or null. * * @since 2.0 */ public function __get($name) { switch ($name) { case 'description': case 'name': case 'type': case 'fieldname': case 'group': case 'tdwidth': return $this->$name; break; case 'label': if (empty($this->label)) { $this->label = $this->getLabel(); } return $this->label; case 'value': if (empty($this->value)) { $this->value = $this->getValue(); } return $this->value; break; case 'header': if (empty($this->header)) { $this->header = $this->getHeader(); } return $this->header; break; case 'filter': if (empty($this->filter)) { $this->filter = $this->getFilter(); } return $this->filter; break; case 'buttons': if (empty($this->buttons)) { $this->buttons = $this->getButtons(); } return $this->buttons; break; case 'options': if (empty($this->options)) { $this->options = $this->getOptions(); } return $this->options; break; case 'sortable': if (empty($this->sortable)) { $this->sortable = $this->getSortable(); } return $this->sortable; break; } return null; } /** * Method to attach a JForm object to the field. * * @param FOFForm $form The JForm object to attach to the form field. * * @return FOFFormHeader The form field object so that the method can be used in a chain. * * @since 2.0 */ public function setForm(FOFForm $form) { $this->form = $form; return $this; } /** * Method to attach a FOFForm object to the field. * * @param SimpleXMLElement $element The SimpleXMLElement object representing the tag for the form field object. * @param mixed $value The form field value to validate. * @param string $group The field name group control value. This acts as as an array container for the field. * For example if the field has name="foo" and the group value is set to "bar" then the * full field name would end up being "bar[foo]". * * @return boolean True on success. * * @since 2.0 */ public function setup(SimpleXMLElement $element, $value, $group = null) { // Make sure there is a valid JFormField XML element. if ((string) $element->getName() != 'header') { return false; } // Reset the internal fields $this->label = null; $this->header = null; $this->filter = null; $this->buttons = null; $this->options = null; $this->value = null; $this->filterSource = null; // Set the XML element object. $this->element = $element; // Get some important attributes from the form field element. $class = (string) $element['class']; $id = (string) $element['id']; $name = (string) $element['name']; $filterSource = (string) $element['filter_source']; $tdwidth = (string) $element['tdwidth']; // Set the field description text. $this->description = (string) $element['description']; // Set the group of the field. $this->group = $group; // Set the td width of the field. $this->tdwidth = $tdwidth; // Set the field name and id. $this->fieldname = $this->getFieldName($name); $this->name = $this->getName($this->fieldname); $this->id = $this->getId($id, $this->fieldname); $this->filterSource = $this->getFilterSource($filterSource); // Set the field default value. $this->value = $this->getValue(); return true; } /** * Method to get the id used for the field input tag. * * @param string $fieldId The field element id. * @param string $fieldName The field element name. * * @return string The id to be used for the field input tag. * * @since 2.0 */ protected function getId($fieldId, $fieldName) { $id = ''; // If the field is in a group add the group control to the field id. if ($this->group) { // If we already have an id segment add the group control as another level. if ($id) { $id .= '_' . str_replace('.', '_', $this->group); } else { $id .= str_replace('.', '_', $this->group); } } // If we already have an id segment add the field id/name as another level. if ($id) { $id .= '_' . ($fieldId ? $fieldId : $fieldName); } else { $id .= ($fieldId ? $fieldId : $fieldName); } // Clean up any invalid characters. $id = preg_replace('#\W#', '_', $id); return $id; } /** * Method to get the name used for the field input tag. * * @param string $fieldName The field element name. * * @return string The name to be used for the field input tag. * * @since 2.0 */ protected function getName($fieldName) { $name = ''; // If the field is in a group add the group control to the field name. if ($this->group) { // If we already have a name segment add the group control as another level. $groups = explode('.', $this->group); if ($name) { foreach ($groups as $group) { $name .= '[' . $group . ']'; } } else { $name .= array_shift($groups); foreach ($groups as $group) { $name .= '[' . $group . ']'; } } } // If we already have a name segment add the field name as another level. if ($name) { $name .= '[' . $fieldName . ']'; } else { $name .= $fieldName; } return $name; } /** * Method to get the field name used. * * @param string $fieldName The field element name. * * @return string The field name * * @since 2.0 */ protected function getFieldName($fieldName) { return $fieldName; } /** * Method to get the field label. * * @return string The field label. * * @since 2.0 */ protected function getLabel() { // Get the label text from the XML element, defaulting to the element name. $title = $this->element['label'] ? (string) $this->element['label'] : ''; if (empty($title)) { $view = $this->form->getView(); $params = $view->getViewOptionAndName(); $title = $params['option'] . '_' . FOFInflector::pluralize($params['view']) . '_FIELD_' . (string) $this->element['name']; $title = strtoupper($title); $result = JText::_($title); if ($result === $title) { $title = ucfirst((string) $this->element['name']); } } return $title; } /** * Get the filter value for this header field * * @return mixed The filter value */ protected function getValue() { $model = $this->form->getModel(); return $model->getState($this->filterSource); } /** * Return the key of the filter value in the model state or, if it's not set, * the name of the field. * * @param string $filterSource The filter source value to return * * @return string */ protected function getFilterSource($filterSource) { if ($filterSource) { return $filterSource; } else { return $this->name; } } /** * Is this a sortable field? * * @return boolean True if it's sortable */ protected function getSortable() { $sortable = ($this->element['sortable'] != 'false'); if ($sortable) { if (empty($this->header)) { $this->header = $this->getHeader(); } $sortable = !empty($this->header); } return $sortable; } /** * Returns the HTML for the header row, or null if this element should * render no header element * * @return string|null HTML code or null if nothing is to be rendered * * @since 2.0 */ protected function getHeader() { return null; } /** * Returns the HTML for a text filter to be rendered in the filter row, * or null if this element should render no text input filter. * * @return string|null HTML code or null if nothing is to be rendered * * @since 2.0 */ protected function getFilter() { return null; } /** * Returns the HTML for the buttons to be rendered in the filter row, * next to the text input filter, or null if this element should render no * text input filter buttons. * * @return string|null HTML code or null if nothing is to be rendered * * @since 2.0 */ protected function getButtons() { return null; } /** * Returns the JHtml options for a drop-down filter. Do not include an * empty option, it is added automatically. * * @return array The JHtml options for a drop-down filter * * @since 2.0 */ protected function getOptions() { return array(); } } PKY[{UCCfof/form/helper.phpnuW+AgetIntegrationObject('filesystem'); foreach ($paths as $path) { if ($file = $filesystem->pathFind($path, $type)) { require_once $file; if (class_exists($class)) { break; } elseif (class_exists($altClass)) { break; } } } // Check for all if the class exists. if (class_exists($class)) { return $class; } elseif (class_exists($altClass)) { return $altClass; } else { return false; } } /** * Method to add a path to the list of header include paths. * * @param mixed $new A path or array of paths to add. * * @return array The list of paths that have been added. */ public static function addHeaderPath($new = null) { return self::addPath('header', $new); } } PKY[Uwg g fof/form/field/language.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Method to get the field options. * * @since 2.0 * * @return array The field option objects. */ protected function getOptions() { $options = parent::getOptions(); $noneoption = $this->element['none'] ? $this->element['none'] : null; if ($noneoption) { array_unshift($options, JHtml::_('select.option', '*', JText::_($noneoption))); } return $options; } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; return '' . htmlspecialchars(FOFFormFieldList::getOptionName($this->getOptions(), $this->value), ENT_COMPAT, 'UTF-8') . ''; } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { $class = $this->element['class'] ? (string) $this->element['class'] : ''; return '' . htmlspecialchars(FOFFormFieldList::getOptionName($this->getOptions(), $this->value), ENT_COMPAT, 'UTF-8') . ''; } } PKY[=fof/form/field/captcha.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { return $this->getInput(); } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { return $this->getInput(); } } PKY[jgfof/form/field/published.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Method to get the field options. * * @since 2.0 * * @return array The field option objects. */ protected function getOptions() { $options = parent::getOptions(); if (!empty($options)) { return $options; } // If no custom options were defined let's figure out which ones of the // defaults we shall use... $config = array( 'published' => 1, 'unpublished' => 1, 'archived' => 0, 'trash' => 0, 'all' => 0, ); $configMap = array( 'show_published' => array('published', 1), 'show_unpublished' => array('unpublished', 1), 'show_archived' => array('archived', 0), 'show_trash' => array('trash', 0), 'show_all' => array('all', 0), ); foreach ($configMap as $attribute => $preferences) { list($configKey, $default) = $preferences; switch (strtolower($this->element[$attribute])) { case 'true': case '1': case 'yes': $config[$configKey] = true; case 'false': case '0': case 'no': $config[$configKey] = false; default: $config[$configKey] = $default; } } if ($config['published']) { $stack[] = JHtml::_('select.option', '1', JText::_('JPUBLISHED')); } if ($config['unpublished']) { $stack[] = JHtml::_('select.option', '0', JText::_('JUNPUBLISHED')); } if ($config['archived']) { $stack[] = JHtml::_('select.option', '2', JText::_('JARCHIVED')); } if ($config['trash']) { $stack[] = JHtml::_('select.option', '-2', JText::_('JTRASHED')); } if ($config['all']) { $stack[] = JHtml::_('select.option', '*', JText::_('JALL')); } return $stack; } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; return '' . htmlspecialchars(FOFFormFieldList::getOptionName($this->getOptions(), $this->value), ENT_COMPAT, 'UTF-8') . ''; } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { if (!($this->item instanceof FOFTable)) { throw new Exception(__CLASS__ . ' needs a FOFTable to act upon'); } // Initialise $prefix = ''; $checkbox = 'cb'; $publish_up = null; $publish_down = null; $enabled = true; // Get options if ($this->element['prefix']) { $prefix = (string) $this->element['prefix']; } if ($this->element['checkbox']) { $checkbox = (string) $this->element['checkbox']; } if ($this->element['publish_up']) { $publish_up = (string) $this->element['publish_up']; } if ($this->element['publish_down']) { $publish_down = (string) $this->element['publish_down']; } // @todo Enforce ACL checks to determine if the field should be enabled or not // Get the HTML return JHTML::_('jgrid.published', $this->value, $this->rowid, $prefix, $enabled, $checkbox, $publish_up, $publish_down); } } PKY[v !fof/form/field/sessionhandler.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; return '' . htmlspecialchars(FOFFormFieldList::getOptionName($this->getOptions(), $this->value), ENT_COMPAT, 'UTF-8') . ''; } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { $class = $this->element['class'] ? (string) $this->element['class'] : ''; return '' . htmlspecialchars(FOFFormFieldList::getOptionName($this->getOptions(), $this->value), ENT_COMPAT, 'UTF-8') . ''; } } PKY[; fof/form/field/radio.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; return '' . htmlspecialchars(FOFFormFieldList::getOptionName($this->getOptions(), $this->value), ENT_COMPAT, 'UTF-8') . ''; } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { $class = $this->element['class'] ? (string) $this->element['class'] : ''; return '' . htmlspecialchars(FOFFormFieldList::getOptionName($this->getOptions(), $this->value), ENT_COMPAT, 'UTF-8') . ''; } } PKY[ϐĦfof/form/field/checkbox.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; $value = $this->element['value'] ? (string) $this->element['value'] : '1'; $disabled = ((string) $this->element['disabled'] == 'true') ? ' disabled="disabled"' : ''; $onclick = $this->element['onclick'] ? ' onclick="' . (string) $this->element['onclick'] . '"' : ''; $required = $this->required ? ' required="required" aria-required="true"' : ''; if (empty($this->value)) { $checked = (isset($this->element['checked'])) ? ' checked="checked"' : ''; } else { $checked = ' checked="checked"'; } return '' . '' . ''; } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { $class = $this->element['class'] ? (string) $this->element['class'] : ''; $value = $this->element['value'] ? (string) $this->element['value'] : '1'; $disabled = ((string) $this->element['disabled'] == 'true') ? ' disabled="disabled"' : ''; $onclick = $this->element['onclick'] ? ' onclick="' . (string) $this->element['onclick'] . '"' : ''; $required = $this->required ? ' required="required" aria-required="true"' : ''; if (empty($this->value)) { $checked = (isset($this->element['checked'])) ? ' checked="checked"' : ''; } else { $checked = ' checked="checked"'; } return '' . '' . ''; } } PKY[;;11fof/form/field/tag.phpnuW+Aelement['published']? $this->element['published'] : array(0,1); $name = (string) $this->element['name']; $db = FOFPlatform::getInstance()->getDbo(); $query = $db->getQuery(true) ->select('a.id AS value, a.path, a.title AS text, a.level, a.published') ->from('#__tags AS a') ->join('LEFT', $db->quoteName('#__tags') . ' AS b ON a.lft > b.lft AND a.rgt < b.rgt'); $item = $this->form->getModel()->getItem(); if ($item instanceof FOFTable) { // Fake value for selected tags $keyfield = $item->getKeyName(); $content_id = $item->$keyfield; $type = $item->getContentType(); $selected_query = $db->getQuery(true); $selected_query ->select('tag_id') ->from('#__contentitem_tag_map') ->where('content_item_id = ' . (int) $content_id) ->where('type_alias = ' . $db->quote($type)); $db->setQuery($selected_query); $this->value = $db->loadColumn(); } // Ajax tag only loads assigned values if (!$this->isNested()) { // Only item assigned values $values = (array) $this->value; FOFUtilsArray::toInteger($values); $query->where('a.id IN (' . implode(',', $values) . ')'); } // Filter language if (!empty($this->element['language'])) { $query->where('a.language = ' . $db->quote($this->element['language'])); } $query->where($db->quoteName('a.alias') . ' <> ' . $db->quote('root')); // Filter to only load active items // Filter on the published state if (is_numeric($published)) { $query->where('a.published = ' . (int) $published); } elseif (is_array($published)) { FOFUtilsArray::toInteger($published); $query->where('a.published IN (' . implode(',', $published) . ')'); } $query->group('a.id, a.title, a.level, a.lft, a.rgt, a.parent_id, a.published, a.path') ->order('a.lft ASC'); // Get the options. $db->setQuery($query); try { $options = $db->loadObjectList(); } catch (RuntimeException $e) { return false; } // Prepare nested data if ($this->isNested()) { $this->prepareOptionsNested($options); } else { $options = JHelperTags::convertPathsToNames($options); } return $options; } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { return ''; } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.1 * * @return string The field HTML */ public function getRepeatable() { return ''; } } PKY[=fof/form/field/title.phpnuW+Aelement['slug_field']) { $slug_field = (string) $this->element['slug_field']; } if ($this->element['slug_format']) { $slug_format = (string) $this->element['slug_format']; } if ($this->element['slug_class']) { $slug_class = (string) $this->element['slug_class']; } // Get the regular display $html = parent::getRepeatable(); $slug = $this->item->$slug_field; $html .= '
    ' . ''; $html .= JText::sprintf($slug_format, $slug); $html .= ''; return $html; } } PKY[`յfof/form/field/accesslevel.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; $params = $this->getOptions(); $db = FOFPlatform::getInstance()->getDbo(); $query = $db->getQuery(true); $query->select('a.id AS value, a.title AS text'); $query->from('#__viewlevels AS a'); $query->group('a.id, a.title, a.ordering'); $query->order('a.ordering ASC'); $query->order($query->qn('title') . ' ASC'); // Get the options. $db->setQuery($query); $options = $db->loadObjectList(); // If params is an array, push these options to the array if (is_array($params)) { $options = array_merge($params, $options); } // If all levels is allowed, push it into the array. elseif ($params) { array_unshift($options, JHtml::_('select.option', '', JText::_('JOPTION_ACCESS_SHOW_ALL_LEVELS'))); } return '' . htmlspecialchars(FOFFormFieldList::getOptionName($options, $this->value), ENT_COMPAT, 'UTF-8') . ''; } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { $class = $this->element['class'] ? (string) $this->element['class'] : ''; $params = $this->getOptions(); $db = FOFPlatform::getInstance()->getDbo(); $query = $db->getQuery(true); $query->select('a.id AS value, a.title AS text'); $query->from('#__viewlevels AS a'); $query->group('a.id, a.title, a.ordering'); $query->order('a.ordering ASC'); $query->order($query->qn('title') . ' ASC'); // Get the options. $db->setQuery($query); $options = $db->loadObjectList(); // If params is an array, push these options to the array if (is_array($params)) { $options = array_merge($params, $options); } // If all levels is allowed, push it into the array. elseif ($params) { array_unshift($options, JHtml::_('select.option', '', JText::_('JOPTION_ACCESS_SHOW_ALL_LEVELS'))); } return '' . htmlspecialchars(FOFFormFieldList::getOptionName($options, $this->value), ENT_COMPAT, 'UTF-8') . ''; } } PKY[k66fof/form/field/index.htmlnuW+APKY[w%Oeefof/form/field/actions.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Get the field configuration * * @return array */ protected function getConfig() { // If no custom options were defined let's figure out which ones of the // defaults we shall use... $config = array( 'published' => 1, 'unpublished' => 1, 'archived' => 0, 'trash' => 0, 'all' => 0, ); $stack = array(); if (isset($this->element['show_published'])) { $config['published'] = FOFStringUtils::toBool($this->element['show_published']); } if (isset($this->element['show_unpublished'])) { $config['unpublished'] = FOFStringUtils::toBool($this->element['show_unpublished']); } if (isset($this->element['show_archived'])) { $config['archived'] = FOFStringUtils::toBool($this->element['show_archived']); } if (isset($this->element['show_trash'])) { $config['trash'] = FOFStringUtils::toBool($this->element['show_trash']); } if (isset($this->element['show_all'])) { $config['all'] = FOFStringUtils::toBool($this->element['show_all']); } return $config; } /** * Method to get the field options. * * @since 2.0 * * @return array The field option objects. */ protected function getOptions() { return null; } /** * Method to get a * * @param string $enabledFieldName Name of the enabled/published field * * @return FOFFormFieldPublished Field */ protected function getPublishedField($enabledFieldName) { $attributes = array( 'name' => $enabledFieldName, 'type' => 'published', ); if ($this->element['publish_up']) { $attributes['publish_up'] = (string) $this->element['publish_up']; } if ($this->element['publish_down']) { $attributes['publish_down'] = (string) $this->element['publish_down']; } foreach ($attributes as $name => $value) { if (!is_null($value)) { $renderedAttributes[] = $name . '="' . $value . '"'; } } $publishedXml = new SimpleXMLElement(''); $publishedField = new FOFFormFieldPublished($this->form); // Pass required objects to the field $publishedField->item = $this->item; $publishedField->rowid = $this->rowid; $publishedField->setup($publishedXml, $this->item->{$enabledFieldName}); return $publishedField; } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { throw new Exception(__CLASS__ . ' cannot be used in single item display forms'); } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { if (!($this->item instanceof FOFTable)) { throw new Exception(__CLASS__ . ' needs a FOFTable to act upon'); } $config = $this->getConfig(); // Initialise $prefix = ''; $checkbox = 'cb'; $publish_up = null; $publish_down = null; $enabled = true; $html = '
    '; // Render a published field if ($publishedFieldName = $this->item->getColumnAlias('enabled')) { if ($config['published'] || $config['unpublished']) { // Generate a FOFFormFieldPublished field $publishedField = $this->getPublishedField($publishedFieldName); // Render the publish button $html .= $publishedField->getRepeatable(); } if ($config['archived']) { $archived = $this->item->{$publishedFieldName} == 2 ? true : false; // Create dropdown items $action = $archived ? 'unarchive' : 'archive'; JHtml::_('actionsdropdown.' . $action, 'cb' . $this->rowid, $prefix); } if ($config['trash']) { $trashed = $this->item->{$publishedFieldName} == -2 ? true : false; $action = $trashed ? 'untrash' : 'trash'; JHtml::_('actionsdropdown.' . $action, 'cb' . $this->rowid, $prefix); } // Render dropdown list if ($config['archived'] || $config['trash']) { $html .= JHtml::_('actionsdropdown.render', $this->item->title); } } $html .= '
    '; return $html; } } PKY[&fof/form/field/button.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getInput() { $this->label = ''; $text = $this->element['text']; $class = $this->element['class'] ? (string) $this->element['class'] : ''; $icon = $this->element['icon'] ? (string) $this->element['icon'] : ''; $onclick = $this->element['onclick'] ? 'onclick="' . (string) $this->element['onclick'] . '"' : ''; $this->value = JText::_($text); if ($icon) { $icon = ''; } return ''; } /** * Method to get the field title. * * @return string The field title. */ protected function getTitle() { return null; } } PKY[x> > fof/form/field/timezone.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { $class = $this->element['class'] ? (string) $this->element['class'] : ''; $selected = FOFFormFieldGroupedlist::getOptionName($this->getOptions(), $this->value); if (is_null($selected)) { $selected = array( 'group' => '', 'item' => '' ); } return 'id . '-item" class="fof-groupedlist-item ' . $class . '>' . htmlspecialchars($selected['item'], ENT_COMPAT, 'UTF-8') . ''; } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { return $this->getStatic(); } } PKY[H fof/form/field/cachehandler.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; return '' . htmlspecialchars(FOFFormFieldList::getOptionName($this->getOptions(), $this->value), ENT_COMPAT, 'UTF-8') . ''; } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { $class = $this->element['class'] ? (string) $this->element['class'] : ''; return '' . htmlspecialchars(FOFFormFieldList::getOptionName($this->getOptions(), $this->value), ENT_COMPAT, 'UTF-8') . ''; } } PKY[Rw]_ _ fof/form/field/selectrow.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Method to get the field input markup for this field type. * * @since 2.0 * * @return string The field input markup. */ protected function getInput() { throw new Exception(__CLASS__ . ' cannot be used in input forms'); } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { throw new Exception(__CLASS__ . ' cannot be used in single item display forms'); } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { if (!($this->item instanceof FOFTable)) { throw new Exception(__CLASS__ . ' needs a FOFTable to act upon'); } // Is this record checked out? $checked_out = false; $locked_by_field = $this->item->getColumnAlias('locked_by'); $myId = JFactory::getUser()->get('id', 0); if (property_exists($this->item, $locked_by_field)) { $locked_by = $this->item->$locked_by_field; $checked_out = ($locked_by != 0 && $locked_by != $myId); } // Get the key id for this record $key_field = $this->item->getKeyName(); $key_id = $this->item->$key_field; // Get the HTML return JHTML::_('grid.id', $this->rowid, $key_id, $checked_out); } } PKY[' fof/form/field/usergroup.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; $params = $this->getOptions(); $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('a.id AS value, a.title AS text'); $query->from('#__usergroups AS a'); $query->group('a.id, a.title'); $query->order('a.id ASC'); $query->order($query->qn('title') . ' ASC'); // Get the options. $db->setQuery($query); $options = $db->loadObjectList(); // If params is an array, push these options to the array if (is_array($params)) { $options = array_merge($params, $options); } // If all levels is allowed, push it into the array. elseif ($params) { array_unshift($options, JHtml::_('select.option', '', JText::_('JOPTION_ACCESS_SHOW_ALL_LEVELS'))); } return '' . htmlspecialchars(FOFFormFieldList::getOptionName($options, $this->value), ENT_COMPAT, 'UTF-8') . ''; } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { $class = $this->element['class'] ? (string) $this->element['class'] : ''; $db = JFactory::getDbo(); $query = $db->getQuery(true); $query->select('a.id AS value, a.title AS text'); $query->from('#__usergroups AS a'); $query->group('a.id, a.title'); $query->order('a.id ASC'); $query->order($query->qn('title') . ' ASC'); // Get the options. $db->setQuery($query); $options = $db->loadObjectList(); return '' . htmlspecialchars(FOFFormFieldList::getOptionName($options, $this->value), ENT_COMPAT, 'UTF-8') . ''; } } PKY[ɣ7$$fof/form/field/list.phpnuW+Astatic)) { $this->static = $this->getStatic(); } return $this->static; break; case 'repeatable': if (empty($this->repeatable)) { $this->repeatable = $this->getRepeatable(); } return $this->static; break; default: return parent::__get($name); } } /** * Get the rendering of this field type for static display, e.g. in a single * item view (typically a "read" task). * * @since 2.0 * * @return string The field HTML */ public function getStatic() { $class = $this->element['class'] ? ' class="' . (string) $this->element['class'] . '"' : ''; return '' . htmlspecialchars(self::getOptionName($this->getOptions(), $this->value), ENT_COMPAT, 'UTF-8') . ''; } /** * Get the rendering of this field type for a repeatable (grid) display, * e.g. in a view listing many item (typically a "browse" task) * * @since 2.0 * * @return string The field HTML */ public function getRepeatable() { $show_link = false; $link_url = ''; $class = $this->element['class'] ? (string) $this->element['class'] : ''; if ($this->element['show_link'] == 'true') { $show_link = true; } if ($this->element['url']) { $link_url = $this->element['url']; } else { $show_link = false; } if ($show_link && ($this->item instanceof FOFTable)) { // Replace [ITEM:ID] in the URL with the item's key value (usually: // the auto-incrementing numeric ID) $keyfield = $this->item->getKeyName(); $replace = $this->item->$keyfield; $link_url = str_replace('[ITEM:ID]', $replace, $link_url); // Replace the [ITEMID] in the URL with the current Itemid parameter $link_url = str_replace('[ITEMID]', JFactory::getApplication()->input->getInt('Itemid', 0), $link_url); // Replace other field variables in the URL $fields = $this->item->getFields(); foreach ($fields as $fielddata) { $fieldname = $fielddata->Field; if (empty($fieldname)) { $fieldname = $fielddata->column_name; } $search = '[ITEM:' . strtoupper($fieldname) . ']'; $replace = $this->item->$fieldname; $link_url = str_replace($search, $replace, $link_url); } } else { $show_link = false; } $html = ''; if ($show_link) { $html .= ''; } $html .= htmlspecialchars(self::getOptionName($this->getOptions(), $this->value), ENT_COMPAT, 'UTF-8'); if ($show_link) { $html .= ''; } $html .= ''; return $html; } /** * Gets the active option's label given an array of JHtml options * * @param array $data The JHtml options to parse * @param mixed $selected The currently selected value * @param string $optKey Key name * @param string $optText Value name * * @return mixed The label of the currently selected option */ public static function getOptionName($data, $selected = null, $optKey = 'value', $optText = 'text') { $ret = null; foreach ($data as $elementKey => &$element) { if (is_array($element)) { $key = $optKey === null ? $elementKey : $element[$optKey]; $text = $element[$optText]; } elseif (is_object($element)) { $key = $optKey === null ? $elementKey : $element->$optKey; $text = $element->$optText; } else { // This is a simple associative array $key = $elementKey; $text = $element; } if (is_null($ret)) { $ret = $text; } elseif ($selected == $key) { $ret = $text; } } return $ret; } /** * Method to get the field options. * * Ordering is disabled by default. You can enable ordering by setting the * 'order' element in your form field. The other order values are optional. * * - order What to order. Possible values: 'name' or 'value' (default = false) * - order_dir Order direction. Possible values: 'asc' = Ascending or 'desc' = Descending (default = 'asc') * - order_case_sensitive Order case sensitive. Possible values: 'true' or 'false' (default = false) * * @return array The field option objects. * * @since Ordering is available since FOF 2.1.b2. */ protected function getOptions() { // Ordering is disabled by default for backward compatibility $order = false; // Set default order direction $order_dir = 'asc'; // Set default value for case sensitive sorting $order_case_sensitive = false; if ($this->element['order'] && $this->element['order'] !== 'false') { $order = $this->element['order']; } if ($this->element['order_dir']) { $order_dir = $this->element['order_dir']; } if ($this->element['order_case_sensitive']) { // Override default setting when the form element value is 'true' if ($this->element['order_case_sensitive'] == 'true') { $order_case_sensitive = true; } } // Create a $sortOptions array in order to apply sorting $i = 0; $sortOptions = array(); foreach ($this->element->children() as $option) { $name = JText::alt(trim((string) $option), preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname)); $sortOptions[$i] = new stdClass; $sortOptions[$i]->option = $option; $sortOptions[$i]->value = $option['value']; $sortOptions[$i]->name = $name; $i++; } // Only order if it's set if ($order) { jimport('joomla.utilities.arrayhelper'); FOFUtilsArray::sortObjects($sortOptions, $order, $order_dir == 'asc' ? 1 : -1, $order_case_sensitive, false); } // Initialise the options $options = array(); // Do we have a class and method source for our options? $source_file = empty($this->element['source_file']) ? '' : (string) $this->element['source_file']; $source_class = empty($this->element['source_class']) ? '' : (string) $this->element['source_class']; $source_method = empty($this->element['source_method']) ? '' : (string) $this->element['source_method']; $source_key = empty($this->element['source_key']) ? '*' : (string) $this->element['source_key']; $source_value = empty($this->element['source_value']) ? '*' : (string) $this->element['source_value']; $source_translate = empty($this->element['source_translate']) ? 'true' : (string) $this->element['source_translate']; $source_translate = in_array(strtolower($source_translate), array('true','yes','1','on')) ? true : false; if ($source_class && $source_method) { // Maybe we have to load a file? if (!empty($source_file)) { $source_file = FOFTemplateUtils::parsePath($source_file, true); if (FOFPlatform::getInstance()->getIntegrationObject('filesystem')->fileExists($source_file)) { include_once $source_file; } } // Make sure the class exists if (class_exists($source_class, true)) { // ...and so does the option if (in_array($source_method, get_class_methods($source_class))) { // Get the data from the class $source_data = $source_class::$source_method(); // Loop through the data and prime the $options array foreach ($source_data as $k => $v) { $key = (empty($source_key) || ($source_key == '*')) ? $k : $v[$source_key]; $value = (empty($source_value) || ($source_value == '*')) ? $v : $v[$source_value]; if ($source_translate) { $value = JText::_($value); } $options[] = JHtml::_('select.option', $key, $value, 'value', 'text'); } } } } // Get the field $options foreach ($sortOptions as $sortOption) { $option = $sortOption->option; $name = $sortOption->name; // Only add