repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/src/PHPUnit/Asserts/FileSystemAssertTrait.php | src/PHPUnit/Asserts/FileSystemAssertTrait.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace GeckoPackages\PHPUnit\Asserts;
use GeckoPackages\PHPUnit\Constraints\DirectoryEmptyConstraint;
use GeckoPackages\PHPUnit\Constraints\FileIsLinkConstraint;
use GeckoPackages\PHPUnit\Constraints\FileIsValidLinkConstraint;
use GeckoPackages\PHPUnit\Constraints\FilePermissionsIsIdenticalConstraint;
use GeckoPackages\PHPUnit\Constraints\FilePermissionsMaskConstraint;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\LogicalNot;
/**
* Provides asserts for testing directories, files and symbolic links.
*
* Additional PHPUnit asserts for testing file (system) based logic.
*
* @api
*
* @author SpacePossum
*/
trait FileSystemAssertTrait
{
/**
* Assert that a directory exists and is empty.
*
* @param mixed $filename
* @param string $message
*/
public static function assertDirectoryEmpty($filename, string $message = '')
{
self::assertThatConstraint($filename, $message, 'assertDirectoryEmpty', new DirectoryEmptyConstraint());
}
/**
* Assert that a directory exists and is not empty.
*
* @param mixed $filename
* @param string $message
*/
public static function assertDirectoryNotEmpty($filename, string $message = '')
{
self::assertThatConstraint($filename, $message, 'assertDirectoryNotEmpty', new LogicalNot(new DirectoryEmptyConstraint()));
}
/**
* Asserts that a file permission matches, for example: 'drwxrwxrwx' or '0664'.
*
* @param int|string $permissions > 0 or string; format for example: 'drwxrwxrwx'
* @param mixed $filename
* @param string $message
*/
public static function assertFileHasPermissions($permissions, $filename, string $message = '')
{
if (!is_string($permissions) && !(is_int($permissions) && $permissions >= 0)) {
throw AssertHelper::createArgumentException(__TRAIT__, 'assertFileHasPermissions', 'int (>= 0) or string', $permissions);
}
try {
$constraint = new FilePermissionsIsIdenticalConstraint($permissions);
} catch (\InvalidArgumentException $e) {
throw AssertHelper::createArgumentExceptionWithMessage(
__TRAIT__,
'assertFileHasPermissions',
$permissions,
$e->getMessage()
);
}
self::assertThatConstraint($filename, $message, 'assertFileHasPermissions', $constraint);
}
/**
* Assert that a file is a symbolic link.
*
* @param mixed $filename
* @param string $message
*/
public static function assertFileIsLink($filename, string $message = '')
{
self::assertThatConstraint($filename, $message, 'assertFileIsLink', new FileIsLinkConstraint());
}
/**
* Assert that a file is not a symbolic link.
*
* @param mixed $filename
* @param string $message
*/
public static function assertFileIsNotLink($filename, string $message = '')
{
self::assertThatConstraint($filename, $message, 'assertFileIsNotLink', new LogicalNot(new FileIsLinkConstraint()));
}
/**
* Assert given value is a string, symlink and points to a file or directory that exists.
*
* @param mixed $filename
* @param string $message
*/
public static function assertFileIsValidLink($filename, string $message = '')
{
self::assertThatConstraint($filename, $message, 'assertFileIsValidLink', new FileIsValidLinkConstraint());
}
/**
* Asserts that a file permission matches mask, for example: '0007'.
*
* @param int $permissionMask
* @param mixed $filename
* @param string $message
*/
public static function assertFilePermissionMask($permissionMask, $filename, string $message = '')
{
self::filePermissionMask($permissionMask, $filename, 'assertFilePermissionMask', true, $message);
}
/**
* Asserts that a file permission does not matches mask, for example: '0607'.
*
* @param int $permissionMask
* @param mixed $filename
* @param string $message
*/
public static function assertFilePermissionNotMask($permissionMask, $filename, string $message = '')
{
self::filePermissionMask($permissionMask, $filename, 'assertFilePermissionNotMask', false, $message);
}
/**
* @param mixed $input
* @param string $message
* @param string $method
* @param Constraint $constraint
*/
private static function assertThatConstraint($input, string $message, string $method, Constraint $constraint)
{
AssertHelper::assertMethodDependency(__CLASS__, __TRAIT__, $method, ['assertThat']);
self::assertThat($input, $constraint, $message);
}
/**
* @param int $permissionMask
* @param mixed $filename
* @param string $method
* @param bool $positive
* @param string $message
*/
private static function filePermissionMask($permissionMask, $filename, string $method, bool $positive, string $message = '')
{
if (!is_int($permissionMask)) {
throw AssertHelper::createArgumentException(__TRAIT__, $method, 'int', $permissionMask);
}
$constraint = new FilePermissionsMaskConstraint($permissionMask);
self::assertThatConstraint($filename, $message, $method, $positive ? $constraint : new LogicalNot($constraint));
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/src/PHPUnit/Asserts/RangeAssertTrait.php | src/PHPUnit/Asserts/RangeAssertTrait.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace GeckoPackages\PHPUnit\Asserts;
use GeckoPackages\PHPUnit\Constraints\NumberRangeConstraint;
use GeckoPackages\PHPUnit\Constraints\UnsignedIntConstraint;
use PHPUnit\Framework\Constraint\LogicalNot;
/**
* Provides asserts for testing values with ranges.
*
* Additional PHPUnit asserts for testing if numbers are within or on ranges.
*
* @api
*
* @author SpacePossum
*/
trait RangeAssertTrait
{
/**
* Assert that a number is within a given range (a,b).
*
* @param int|float $lowerBoundary
* @param int|float $upperBoundary
* @param mixed $actual
* @param string $message
*/
public static function assertNumberInRange($lowerBoundary, $upperBoundary, $actual, string $message = '')
{
self::assertNumberRangeMatch($lowerBoundary, $upperBoundary, $actual, $message, 'assertNumberInRange', false, false);
}
/**
* Assert that a number is not within a given range !(a,b).
*
* @param int|float $lowerBoundary
* @param int|float $upperBoundary
* @param mixed $actual
* @param string $message
*/
public static function assertNumberNotInRange($lowerBoundary, $upperBoundary, $actual, string $message = '')
{
self::assertNumberRangeMatch($lowerBoundary, $upperBoundary, $actual, $message, 'assertNumberNotInRange', false, true);
}
/**
* Assert that a number is not within a given range and not on its boundaries ![a,b].
*
* @param int|float $lowerBoundary
* @param int|float $upperBoundary
* @param mixed $actual
* @param string $message
*/
public static function assertNumberNotOnRange($lowerBoundary, $upperBoundary, $actual, string $message = '')
{
self::assertNumberRangeMatch($lowerBoundary, $upperBoundary, $actual, $message, 'assertNumberNotOnRange', true, true);
}
/**
* Assert that a number is within a given range or on its boundaries [a,b].
*
* @param int|float $lowerBoundary
* @param int|float $upperBoundary
* @param mixed $actual
* @param string $message
*/
public static function assertNumberOnRange($lowerBoundary, $upperBoundary, $actual, string $message = '')
{
self::assertNumberRangeMatch($lowerBoundary, $upperBoundary, $actual, $message, 'assertNumberOnRange', true, false);
}
/**
* Assert that given value is an unsigned int (>= 0).
*
* @param mixed $actual
* @param string $message
*/
public function assertUnsignedInt($actual, string $message = '')
{
AssertHelper::assertMethodDependency(__CLASS__, __TRAIT__, 'assertUnsignedInt', ['assertThat']);
self::assertThat($actual, new UnsignedIntConstraint(), $message);
}
/**
* @param int|float $lowerBoundary
* @param int|float $upperBoundary
* @param mixed $actual
* @param string $message
* @param string $method name of method doing the testing
* @param bool $onBoundary test on boundary or between boundary values
* @param bool $negative test as negative
*/
private static function assertNumberRangeMatch(
$lowerBoundary,
$upperBoundary,
$actual,
string $message,
string $method,
bool $onBoundary,
bool $negative
) {
if (!is_int($lowerBoundary) && !is_float($lowerBoundary)) {
throw AssertHelper::createArgumentException(__TRAIT__, $method, 'float or int', $lowerBoundary);
}
if (!is_int($upperBoundary) && !is_float($upperBoundary)) {
throw AssertHelper::createArgumentException(__TRAIT__, $method, 'float or int', $upperBoundary, 2);
}
if ($lowerBoundary >= $upperBoundary) {
$message = sprintf(
'lower boundary %s must be smaller than upper boundary %s.',
is_int($lowerBoundary) ? '%d' : '%.3f',
is_int($upperBoundary) ? '%d' : '%.3f'
);
throw AssertHelper::createArgumentExceptionWithMessage(
__TRAIT__,
$method,
$lowerBoundary,
sprintf($message, $lowerBoundary, $upperBoundary)
);
}
$rangeConstraint = new NumberRangeConstraint($lowerBoundary, $upperBoundary, $onBoundary);
if ($negative) {
$rangeConstraint = new LogicalNot($rangeConstraint);
}
AssertHelper::assertMethodDependency(__CLASS__, __TRAIT__, $method, ['assertThat']);
self::assertThat($actual, $rangeConstraint, $message);
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/src/PHPUnit/Asserts/AssertHelper.php | src/PHPUnit/Asserts/AssertHelper.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace GeckoPackages\PHPUnit\Asserts;
use PHPUnit\Framework\Exception;
/**
* Helper for building exceptions and checking dependencies.
*
* @internal
*
* @author SpacePossum
*/
final class AssertHelper
{
/**
* @param string $class name of the class using trait;
* @param string $trait name of the trait calling method;
* @param string $method called method name
* @param string[] $methodDependencies list of methods the trait relies on
*
* @throws Exception
*/
public static function assertMethodDependency(string $class, string $trait, string $method, array $methodDependencies)
{
$missing = [];
foreach ($methodDependencies as $methodDependency) {
if (!method_exists($class, $methodDependency)) {
$missing[] = sprintf('"%s"', $methodDependency);
}
}
if (0 !== count($missing)) {
throw self::createException(
$trait,
$method,
sprintf('Relies on missing %s %s', count($missing) > 1 ? 'methods' : 'method', implode(', ', $missing))
);
}
}
/**
* @param string $trait name of the trait used
* @param string $method called method name
* @param string $expectedTypeForArgument expected type description
* @param mixed $valueOfArgument given value
* @param int $index argument position
*
* @return Exception
*/
public static function createArgumentException(string $trait, string $method, string $expectedTypeForArgument, $valueOfArgument, int $index = 1): Exception
{
return self::createArgumentExceptionWithMessage(
$trait,
$method,
$valueOfArgument,
sprintf('must be %s.', (in_array($expectedTypeForArgument[0], ['a', 'e', 'i', 'o', 'u'], true) ? 'an' : 'a').' '.$expectedTypeForArgument),
$index
);
}
public static function createArgumentExceptionWithMessage(string $trait, string $method, $valueOfArgument, string $message, int $index = 1): Exception
{
if (is_object($valueOfArgument)) {
$valueOfArgument = sprintf('%s#%s', get_class($valueOfArgument), method_exists($valueOfArgument, '__toString') ? $valueOfArgument->__toString() : '');
} elseif (null === $valueOfArgument) {
$valueOfArgument = 'null';
} else {
$valueOfArgument = gettype($valueOfArgument).'#'.$valueOfArgument;
}
return new Exception(
sprintf(
'Argument #%d (%s) of %s::%s() %s',
$index,
$valueOfArgument,
substr($trait, strrpos($trait, '\\') + 1),
$method,
$message
)
);
}
/**
* @param string $trait name of the trait used
* @param string $method called method name
* @param string $message
*
* @return Exception
*/
private static function createException(string $trait, string $method, string $message): Exception
{
return new Exception(
sprintf(
'%s::%s() %s.',
substr($trait, strrpos($trait, '\\') + 1),
$method,
$message
)
);
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/src/PHPUnit/Asserts/AliasAssertTrait.php | src/PHPUnit/Asserts/AliasAssertTrait.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace GeckoPackages\PHPUnit\Asserts;
use GeckoPackages\PHPUnit\Constraints\ScalarConstraint;
use PHPUnit\Framework\Constraint\Constraint;
use PHPUnit\Framework\Constraint\LogicalNot;
/**
* Provides alias/short hand asserts.
*
* Additional alias/shorthand PHPUnit asserts to test for some types etc.
*
* @api
*
* @author SpacePossum
*/
trait AliasAssertTrait
{
/**
* Assert value is an array.
*
* @param mixed $actual
* @param string $message
*/
public static function assertArray($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertArray', new ScalarConstraint(ScalarConstraint::TYPE_ARRAY));
}
/**
* Assert value is a bool (boolean).
*
* @param mixed $actual
* @param string $message
*/
public static function assertBool($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertBool', new ScalarConstraint(ScalarConstraint::TYPE_BOOL));
}
/**
* Assert value is a float (double, real).
*
* @param mixed $actual
* @param string $message
*/
public static function assertFloat($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertFloat', new ScalarConstraint(ScalarConstraint::TYPE_FLOAT));
}
/**
* Assert value is an int (integer).
*
* @param mixed $actual
* @param string $message
*/
public static function assertInt($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertInt', new ScalarConstraint(ScalarConstraint::TYPE_INT));
}
/**
* Assert value is a scalar.
*
* @param mixed $actual
* @param string $message
*/
public static function assertScalar($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertScalar', new ScalarConstraint(ScalarConstraint::TYPE_SCALAR));
}
/**
* Assert value is a string.
*
* @param mixed $actual
* @param string $message
*/
public static function assertString($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertString', new ScalarConstraint(ScalarConstraint::TYPE_STRING));
}
/**
* Assert value is not an array.
*
* @param mixed $actual
* @param string $message
*/
public static function assertNotArray($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertNotArray', new LogicalNot(new ScalarConstraint(ScalarConstraint::TYPE_ARRAY)));
}
/**
* Assert value is not a bool (boolean).
*
* @param mixed $actual
* @param string $message
*/
public static function assertNotBool($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertNotBool', new LogicalNot(new ScalarConstraint(ScalarConstraint::TYPE_BOOL)));
}
/**
* Assert value is not a float (double, real).
*
* @param mixed $actual
* @param string $message
*/
public static function assertNotFloat($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertNotFloat', new LogicalNot(new ScalarConstraint(ScalarConstraint::TYPE_FLOAT)));
}
/**
* Assert value is not an int (integer).
*
* @param mixed $actual
* @param string $message
*/
public static function assertNotInt($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertNotInt', new LogicalNot(new ScalarConstraint(ScalarConstraint::TYPE_INT)));
}
/**
* Assert value is not a scalar.
*
* @param mixed $actual
* @param string $message
*/
public static function assertNotScalar($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertNotScalar', new LogicalNot(new ScalarConstraint(ScalarConstraint::TYPE_SCALAR)));
}
/**
* Assert value is not a string.
*
* @param mixed $actual
* @param string $message
*/
public static function assertNotString($actual, string $message = '')
{
self::assertTypeOfScalar($actual, $message, 'assertNotString', new LogicalNot(new ScalarConstraint(ScalarConstraint::TYPE_STRING)));
}
/**
* @param mixed $actual
* @param string $message
* @param string $method
* @param Constraint $constraint
*/
private static function assertTypeOfScalar($actual, string $message, string $method, Constraint $constraint)
{
AssertHelper::assertMethodDependency(__CLASS__, __TRAIT__, $method, ['assertThat']);
self::assertThat($actual, $constraint, $message);
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/src/PHPUnit/Asserts/XMLAssertTrait.php | src/PHPUnit/Asserts/XMLAssertTrait.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
namespace GeckoPackages\PHPUnit\Asserts;
use GeckoPackages\PHPUnit\Constraints\XML\XMLMatchesXSDConstraint;
use GeckoPackages\PHPUnit\Constraints\XML\XMLValidConstraint;
/**
* Additional PHPUnit asserts for testing XML based logic.
*
* @requires libxml (https://secure.php.net/manual/en/book.libxml.php)
*
* @api
*
* @author SpacePossum
*/
trait XMLAssertTrait
{
/**
* Assert string is XML formatted as defined by the XML Schema Definition.
*
* @param string $XML
* @param string $XSD
* @param string $message
*/
public static function assertXMLMatchesXSD($XSD, $XML, string $message = '')
{
if (!is_string($XSD)) {
throw AssertHelper::createArgumentException(__TRAIT__, 'assertXMLMatchesXSD', 'string', $XSD);
}
AssertHelper::assertMethodDependency(__CLASS__, __TRAIT__, 'assertXMLMatchesXSD', ['assertThat']);
self::assertThat($XML, new XMLMatchesXSDConstraint($XSD), $message);
}
/**
* Assert string is valid XML.
*
* @param string $XML
* @param string $message
*/
public static function assertXMLValid($XML, string $message = '')
{
AssertHelper::assertMethodDependency(__CLASS__, __TRAIT__, 'assertXMLValid', ['assertThat']);
self::assertThat($XML, new XMLValidConstraint(), $message);
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/autoload.php | tests/autoload.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
try {
@chmod(__DIR__.'/assets/dir', 0755);
@chmod(__DIR__.'/assets/dir/test_file.txt', 0644);
} catch (\Exception $e) {
}
require_once __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/PHPUnit/Tests/GeckoTestCase.php';
require_once __DIR__.'/PHPUnit/Tests/AbstractGeckoPHPUnitTest.php';
require_once __DIR__.'/PHPUnit/Tests/AbstractGeckoPHPUnitFileTest.php';
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/AbstractGeckoPHPUnitTest.php | tests/PHPUnit/Tests/AbstractGeckoPHPUnitTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* @internal
*
* @author SpacePossum
*/
abstract class AbstractGeckoPHPUnitTest extends GeckoTestCase
{
/**
* @return string
*/
protected function getAssetsDir(): string
{
static $assertDir;
if (null === $assertDir) {
$assertDir = realpath(__DIR__.'/../../assets').'/';
}
return $assertDir;
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/AbstractGeckoPHPUnitFileTest.php | tests/PHPUnit/Tests/AbstractGeckoPHPUnitFileTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* @internal
*
* @author SpacePossum
*/
abstract class AbstractGeckoPHPUnitFileTest extends AbstractGeckoPHPUnitTest
{
/**
* @param string $target filesystem path
* @param string $link filesystem path
*/
protected function createSymlink(string $target, string $link)
{
// File_exists returns false if the sym link exits but the target does not.
// Therefor test if the symlink exists first and delete it if the target does not not.
if (is_link($link) && !file_exists($link)) {
unlink($link);
}
if (!file_exists($link) && false === @symlink($target, $link)) {
$error = error_get_last();
$this->fail(sprintf(
'Failed to create symlink "%s" for target "%s"%s.',
$link, $target, $error ? '. Error "'.$error['message'].'"' : ''
));
}
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/GeckoTestCase.php | tests/PHPUnit/Tests/GeckoTestCase.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use PHPUnit\Framework\TestCase;
abstract class GeckoTestCase extends TestCase
{
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/ReadMe/ReadMeTest.php | tests/PHPUnit/Tests/ReadMe/ReadMeTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* @internal
*
* @author SpacePossum
*/
final class ReadMeTest extends GeckoTestCase
{
public function generateReadMe(): string
{
require_once __DIR__.'/ReadMeGenerator.php';
$generator = new ReadMeGenerator();
return $generator->generateReadMe($this->getClasses());
}
public function testReadMe()
{
$this->assertSame(
file_get_contents(__DIR__.'/../../../../README.md'),
$this->generateReadMe(),
'README.md is out of sync, please run `$ ./bin/generate_readme` from the root of the project.'
);
}
/**
* @return string[]
*/
private function getClasses(): array
{
$classDir = new ReflectionClass('GeckoPackages\PHPUnit\Asserts\AssertHelper');
$classDir = $classDir->getFileName();
$classDir = substr($classDir, 0, strrpos($classDir, '/'));
$classes = [];
foreach (new DirectoryIterator($classDir) as $file) {
if ($file->isDir()) {
continue;
}
$classes[] = 'GeckoPackages\\PHPUnit\\Asserts\\'.substr($file->getFilename(), 0, -4);
}
sort($classes);
return $classes;
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/ReadMe/ReadMeGenerator.php | tests/PHPUnit/Tests/ReadMe/ReadMeGenerator.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* @internal
*
* @author SpacePossum
*/
final class ReadMeGenerator
{
/**
* @param string[] $classes
*
* @return string
*/
public function generateReadMe(array $classes): string
{
$docs = [];
foreach ($classes as $class) {
$reflection = new ReflectionClass($class);
$classDoc = $this->getClassDoc($reflection->getDocComment());
if (false === $classDoc) {
throw new \UnexpectedValueException(sprintf('Missing class doc for "%s".', $class));
}
if (array_key_exists('internal', $classDoc['tags'])) {
continue;
}
$docs[$class] = ['classDoc' => $classDoc, 'methods' => []];
$reflectionMethods = $reflection->getMethods();
/** @var ReflectionMethod $method */
foreach ($reflectionMethods as $method) {
$methodName = $method->name;
$method = $reflection->getMethod($methodName);
if (!$method->isPublic()) {
continue;
}
try {
$doc = $this->getMethodDoc($method->getDocComment());
} catch (\UnexpectedValueException $e) {
throw new \UnexpectedValueException(sprintf('Exception when parsing "%s", "%s".', $class, $methodName), 1, $e);
}
if (false === $doc) {
throw new \UnexpectedValueException(sprintf('Missing doc for "%s:%s".', $class, $methodName));
}
if ('' === $doc['doc']) {
throw new \UnexpectedValueException(sprintf('Empty description for doc "%s:%s".', $class, $methodName));
}
$params = $method->getParameters();
if (count($params) !== count($doc['params'])) {
throw new \UnexpectedValueException(sprintf('Parameters description in doc of method "%s:%s" mismatched.', $class, $methodName));
}
foreach ($params as $param) {
if (!array_key_exists($param->getName(), $doc['params'])) {
throw new \UnexpectedValueException(sprintf('Missing parameter description in doc of method "%s:%s" for "%s".', $class, $methodName, $param->getName()));
}
if ($param->isDefaultValueAvailable()) {
$doc['params'][$param->getName()]['default'] = $param->getDefaultValue();
}
}
$docs[$class]['methods'][$methodName] = ['doc' => $doc, 'name' => $methodName];
}
ksort($docs[$class]['methods']);
// Merge negatives
foreach ($docs[$class]['methods'] as $methodName => $values) {
if (0 === strpos($methodName, 'assert') && false !== strpos($methodName, 'Not')) {
$positive = str_replace('Not', '', $methodName);
if (!array_key_exists($positive, $docs[$class]['methods'])) {
continue;
}
$docs[$class]['methods'][$positive]['not'] = $docs[$class]['methods'][$methodName];
unset($docs[$class]['methods'][$methodName]);
}
}
}
ksort($docs);
$doc = '';
$listing = '';
foreach ($docs as $class => $properties) {
$shortClass = substr($class, strrpos($class, '\\') + 1);
$classDoc = $properties['classDoc'];
$listing .= sprintf("\n- **%s**<br/>\n %s", $shortClass, $classDoc['summary']);
$doc .= sprintf("\n## %s\n###### %s\n%s\n", $shortClass, $class, $classDoc['doc']);
if ('' !== $classDoc['doc']) {
$doc .= "\n";
}
if (array_key_exists('requires', $classDoc['tags'])) {
if (1 === count($classDoc['tags']['requires'])) {
$doc .= sprintf("Requires %s.\n", $classDoc['tags']['requires'][0]);
} else {
$doc .= "Requires:\n";
foreach ($classDoc['tags']['requires'] as $reqLine) {
if ('' !== $reqLine) {
$doc .= '* '.$reqLine."\n";
}
}
}
}
$doc .= "\n### Methods\n";
foreach ($properties['methods'] as $method => $methodDescription) {
$doc .= $this->generateMethodDescription($method, $methodDescription['doc']);
if (array_key_exists('not', $methodDescription)) {
$doc .= sprintf("\nThe inverse assertion%s\n", $this->generateMethodDescription($methodDescription['not']['name'], $methodDescription['not']['doc']));
}
}
}
$readMeTemplate = <<<EOF
#### GeckoPackages
# PHPUnit extensions
Provides additional asserts to be used in [PHPUnit](https://phpunit.de/) tests.
The asserts are provided using Traits so no changes are needed in the hierarchy of test classes.
The additional asserts are provided through the Traits:
#GENERATED_LISTING#
See Traits and asserts listing for more details.
### Requirements
PHP 7<br/>
PHPUnit 6
<sub>Use ^v2.0 if you are using PHPUnit 5.</sub>
### Install
The package can be installed using [Composer](https://getcomposer.org/).
Add the package to your `composer.json`.
```
"require-dev": {
"gecko-packages/gecko-php-unit" : "^3.0"
}
```
<sub>Please note we hint `-dev` here because typically you only need tests during development.</sub>
### Usage
Example usage of `FileSystemAssertTrait`.
```php
class myTest extends \PHPUnit_Framework_TestCase
{
use \GeckoPackages\PHPUnit\Asserts\FileSystemAssertTrait;
public function testFilePermissionsOfThisFile()
{
\$this->assertFileHasPermissions('lrwxrwxrwx', __FILE__);
}
}
```
# Traits and asserts listing
#GENERATED_BODY#
### License
The project is released under the MIT license, see the LICENSE file.
### Contributions
Contributions are welcome!<br/>
Visit us on [github :octocat:](https://github.com/GeckoPackages/GeckoPHPUnit)
### Semantic Versioning
This project follows [Semantic Versioning](http://semver.org/).
<sub>Kindly note:
We do not keep a backwards compatible promise on code annotated with `@internal`, the tests and tooling (such as document generation) of the project itself
nor the content and/or format of exception/error messages.</sub>
This project is maintained on [github :octocat:](https://github.com/GeckoPackages/GeckoPHPUnit)
EOF;
$readMeTemplate = str_replace('#GENERATED_LISTING#', $listing, $readMeTemplate);
return str_replace('#GENERATED_BODY#', $doc, $readMeTemplate);
}
private function generateMethodDescription(string $method, array $methodDescription): string
{
$params = '';
foreach ($methodDescription['params'] as $name => $values) {
if (array_key_exists('default', $values)) {
$params .= sprintf(' [,%s $%s = %s]', $values['type'], $name, is_string($values['default']) ? '\''.$values['default'].'\'' : $values['default']);
} else {
$params .= sprintf(', %s $%s', $values['type'], $name);
}
}
return sprintf("\n#### %s()\n###### %s(%s)\n%s\n", $method, $method, substr($params, 2), $methodDescription['doc']);
}
private function getClassDoc(string $docString)
{
preg_match_all("/[^\n\r]+[\r\n]*/", $docString, $matches);
if (count($matches[0]) < 1) {
return false;
}
$doc = ['summary' => '', 'doc' => '', 'tags' => []];
$capture = 'summary';
foreach ($matches[0] as $docLine) {
$docLine = trim($docLine);
if ('/**' === $docLine) { // start of doc
continue;
}
if ('*/' === $docLine) { // end of doc
break;
}
if ('*' === $docLine) { // empty line
$capture = 'doc';
}
if (0 === strpos($docLine, '* @')) {
$docLine = trim(substr($docLine, 2));
$tagDivision = strpos($docLine, ' ');
if (false === $tagDivision) {
$index = substr($docLine, 1);
if (!array_key_exists($index, $doc['tags'])) {
$doc['tags'][$index] = [];
}
$doc['tags'][$index][] = '';
} else {
$index = substr($docLine, 1, $tagDivision - 1);
if (!array_key_exists($index, $doc['tags'])) {
$doc['tags'][$index] = [];
}
$doc['tags'][$index][] = substr($docLine, $tagDivision + 1);
}
} elseif (strlen($docLine) > 2) {
$doc[$capture] .= ltrim(substr($docLine, 2))."\n";
}
}
$doc['summary'] = trim($doc['summary']);
$doc['doc'] = trim($doc['doc']);
return $doc;
}
/**
* Parse a method PHPDoc into an array.
*
* @param string $doc
*
* @return array|false
*/
private function getMethodDoc(string $doc)
{
preg_match_all("/[^\n\r]+[\r\n]*/", $doc, $matches);
if (count($matches[0]) < 1) {
return false;
}
$methodDoc = ['doc' => '', 'long' => '', 'params' => []];
$capture = 'doc';
foreach ($matches[0] as $docLine) {
$docLine = trim($docLine);
if ('/**' === $docLine || '*/' === $docLine) {
continue;
}
if ('*' === $docLine) {
$capture = 'long';
continue;
}
if (0 === strpos($docLine, '* @param')) {
$docLine = substr($docLine, 9);
preg_match('#^(.+?\b)[\s]*\$(.+?\b)[\s]*(.+?\b)*#', $docLine, $matches);
if (count($matches) < 3) {
throw new \UnexpectedValueException(sprintf("Matching failed for:\n------------------\n%s\n------------------", $doc));
}
$type = $matches[1];
$name = $matches[2];
//$description = count($matches[2]) > 2 ? $matches[3] : null;
$methodDoc['params'][$name] = ['type' => $type];
continue;
}
$methodDoc[$capture] .= substr($docLine, 2)."\n";
}
$methodDoc['doc'] = trim($methodDoc['doc']);
$methodDoc['long'] = trim($methodDoc['long']);
return $methodDoc;
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/FilePermissionsMaskConstraintTest.php | tests/PHPUnit/Tests/Constraints/FilePermissionsMaskConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\FilePermissionsMaskConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class FilePermissionsMaskConstraintTest extends AbstractGeckoPHPUnitFileTest
{
/**
* @param int $mask
*
* @dataProvider provideFileMasks
*/
public function testFilePermissionsMaskConstraint(int $mask)
{
$constraint = new FilePermissionsMaskConstraint($mask);
$this->assertTrue($constraint->evaluate($this->getTestFile(), '', true));
}
public function provideFileMasks(): array
{
return [
[0644],
[0000],
[0004],
[0040],
[0044],
[0600],
[0604],
[0640],
];
}
public function testFilePermissionsMaskConstraintBasic()
{
$constraint = new FilePermissionsMaskConstraint(1);
$this->assertSame(1, $constraint->count());
$this->assertSame('permissions matches mask', $constraint->toString());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that boolean\# permissions matches mask\.$#
*/
public function testFilePermissionsMaskConstraintFalse()
{
$constraint = new FilePermissionsMaskConstraint(1);
$constraint->evaluate(false);
}
public function testFilePermissionsMaskConstraintFileLink()
{
$link = $this->getAssetsDir().'test_link_file';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_/placeholder.tmp',
$link
);
$constraint = new FilePermissionsMaskConstraint(0xA000);
$this->assertTrue($constraint->evaluate($link, '', true));
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that not file or directory\#_does_not_exists_ permissions matches mask\.$#
*/
public function testFilePermissionsMaskConstraintFileNotExists()
{
$constraint = new FilePermissionsMaskConstraint(1);
$constraint->evaluate('_does_not_exists_');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that integer\#1443 permissions matches mask\.$#
*/
public function testFilePermissionsMaskConstraintInt()
{
$constraint = new FilePermissionsMaskConstraint(1);
$constraint->evaluate(1443);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that file\#/.*tests/assets/dir/test_file.txt 100644 permissions matches mask 777\.$#
*/
public function testFilePermissionsMaskConstraintMaskMismatch()
{
$constraint = new FilePermissionsMaskConstraint(0777);
$constraint->evaluate($this->getTestFile());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null permissions matches mask\.$#
*/
public function testFilePermissionsMaskConstraintNull()
{
$constraint = new FilePermissionsMaskConstraint(1);
$constraint->evaluate(null);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that stdClass\# permissions matches mask\.$#
*/
public function testFilePermissionsMaskConstraintObject()
{
$constraint = new FilePermissionsMaskConstraint(1);
$constraint->evaluate(new \stdClass());
}
private function getTestFile(): string
{
return realpath($this->getAssetsDir().'/dir/test_file.txt');
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/NumberRangeConstraintTest.php | tests/PHPUnit/Tests/Constraints/NumberRangeConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\NumberRangeConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class NumberRangeConstraintTest extends AbstractGeckoPHPUnitTest
{
public function testNumberRangeConstraintInRange()
{
$lower = -1;
$upper = 5;
$constraint = new NumberRangeConstraint($lower, $upper, true);
$this->assertSame('is in range', $constraint->toString());
for ($i = $lower; $i <= $upper; ++$i) {
$this->assertTrue($constraint->evaluate($i, '', true));
}
}
public function testNumberRangeConstraintWithInRange()
{
$lower = 1;
$upper = 3;
$constraint = new NumberRangeConstraint($lower, $upper, false);
$this->assertSame('is within range', $constraint->toString());
for ($i = $lower + 1; $i < $upper; ++$i) {
$this->assertTrue($constraint->evaluate($i, '', true));
}
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that 1 is within range \(0, 1\)\.$#
*/
public function testNumberRangeConstraintFailOnRange()
{
$upper = 1;
$constraint = new NumberRangeConstraint(0, $upper, false);
$constraint->evaluate($upper);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that 2\.500 is in range \[0\.500, 1\.500\]\.$#
*/
public function testNumberRangeConstraintFailOutOfRange()
{
$upper = 1.5;
$constraint = new NumberRangeConstraint(0.5, $upper, true);
$constraint->evaluate($upper + 1);
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/FileExistsConstraintTest.php | tests/PHPUnit/Tests/Constraints/FileExistsConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\FileExistsConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class FileExistsConstraintTest extends AbstractGeckoPHPUnitFileTest
{
/**
* @param string $file
*
* @dataProvider provideFiles
*/
public function testFileExistsConstraint(string $file)
{
$constraint = new FileExistsConstraint();
$this->assertTrue($constraint->evaluate($file, '', true));
}
public function provideFiles(): array
{
$link = $this->getAssetsDir().'test_link_file';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_/placeholder.tmp',
$link
);
return [
[__FILE__],
[$link],
];
}
public function testFileExistsConstraintBasics()
{
$constraint = new FileExistsConstraint();
$this->assertSame(1, $constraint->count());
$this->assertSame('is a file', $constraint->toString());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that directory\#/.*PHPUnit/tests/PHPUnit/Tests/Constraints is a file\.$#
*/
public function testFileExistsConstraintDir()
{
$constraint = new FileExistsConstraint();
$constraint->evaluate(__DIR__, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that link to directory\#/.*test_link_dir is a file\.$#
*/
public function testFileExistsConstraintFileLink()
{
$link = $this->getAssetsDir().'test_link_dir';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_',
$link
);
$constraint = new FileExistsConstraint();
$constraint->evaluate($link, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that integer\#1 is a file\.$#
*/
public function testFileExistsConstraintInt()
{
$constraint = new FileExistsConstraint();
$constraint->evaluate(1, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null is a file\.$#
*/
public function testFileExistsConstraintNull()
{
$constraint = new FileExistsConstraint();
$constraint->evaluate(null, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that stdClass\# is a file\.$#
*/
public function testFileExistsConstraintObject()
{
$constraint = new FileExistsConstraint();
$constraint->evaluate(new \stdClass(), '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that __does_not_exists__ is a file\.$#
*/
public function testFileExistsConstraintString()
{
$constraint = new FileExistsConstraint();
$constraint->evaluate('__does_not_exists__', '');
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/FilePermissionsIsIdenticalConstraintTest.php | tests/PHPUnit/Tests/Constraints/FilePermissionsIsIdenticalConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\FilePermissionsIsIdenticalConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class FilePermissionsIsIdenticalConstraintTest extends AbstractGeckoPHPUnitFileTest
{
/**
* @param bool $expected
* @param int|string $permission
*
* @dataProvider providePermissionExpected
*/
public function testFilePermissionsMaskConstraint(bool $expected, $permission)
{
$constraint = new FilePermissionsIsIdenticalConstraint($permission);
$this->assertSame($expected, $constraint->evaluate($this->getTestFile(), '', true), 'Permisson evaluation failed.');
}
public function providePermissionExpected(): array
{
return [
[true, 100644],
[true, '100644'],
[true, '100644'],
[true, '0644'],
[true, '-rw-r--r--'],
];
}
public function testFilePermissionsMaskConstraintBasic()
{
$constraint = new FilePermissionsIsIdenticalConstraint(1);
$this->assertSame(1, $constraint->count());
$this->assertSame('permissions are equal', $constraint->toString());
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp #^Invalid value for permission to match "-1", expected int >= 0 or string\.$#
*/
public function testFilePermissionsMaskConstraintInvalidArg1()
{
new FilePermissionsIsIdenticalConstraint(-1);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp #^Permission to match "invalid" is not formatted correctly\.$#
*/
public function testFilePermissionsMaskConstraintInvalidArg2()
{
new FilePermissionsIsIdenticalConstraint('invalid');
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp #^Invalid value for permission to match "stdClass\#", expected int >= 0 or string\.$#
*/
public function testFilePermissionsMaskConstraintInvalidArg3()
{
new FilePermissionsIsIdenticalConstraint(new \stdClass());
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp #^Invalid value for permission to match "null", expected int >= 0 or string\.$#
*/
public function testFilePermissionsMaskConstraintInvalidArg4()
{
new FilePermissionsIsIdenticalConstraint(null);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp #^Invalid value for permission to match "double\#1\.5", expected int >= 0 or string\.$#
*/
public function testFilePermissionsMaskConstraintInvalidArg5()
{
new FilePermissionsIsIdenticalConstraint(1.5);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp #^Permission to match "1\.5" is not formatted correctly\.$#
*/
public function testFilePermissionsMaskConstraintInvalidArg6()
{
new FilePermissionsIsIdenticalConstraint('1.5');
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp #^Permission to match "1,5" is not formatted correctly\.$#
*/
public function testFilePermissionsMaskConstraintInvalidArg7()
{
new FilePermissionsIsIdenticalConstraint('1,5');
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp #^Permission to match "-1" is not formatted correctly\.$#
*/
public function testFilePermissionsMaskConstraintInvalidArg8()
{
new FilePermissionsIsIdenticalConstraint('-1');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that integer\#1 permissions are equal\.$#
*/
public function testFilePermissionsMaskConstraintInt()
{
$c = new FilePermissionsIsIdenticalConstraint(0777);
$c->evaluate(1);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that not file or directory\#_does_not_exists_ permissions are equal\.$#
*/
public function testFilePermissionsMaskConstraintNoFile()
{
$c = new FilePermissionsIsIdenticalConstraint(0777);
$c->evaluate('_does_not_exists_');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null permissions are equal\.$#
*/
public function testFilePermissionsMaskConstraintNull()
{
$c = new FilePermissionsIsIdenticalConstraint(0777);
$c->evaluate(null);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that stdClass\# permissions are equal\.$#
*/
public function testFilePermissionsMaskConstraintObject()
{
$c = new FilePermissionsIsIdenticalConstraint(0777);
$c->evaluate(new \stdClass());
}
public function testFilePermissionsMaskConstraintFileLink()
{
$link = $this->getAssetsDir().'test_link_file';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_/placeholder.tmp',
$link
);
$c = new FilePermissionsIsIdenticalConstraint(0777);
$this->assertTrue($c->evaluate($link, '', true));
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that link\#/.*PHPUnit/tests/assets/test_link_file 0777 permissions are equal to 0111\.$#
*/
public function testFilePermissionsMaskConstraintFileLinkMismatch()
{
$link = $this->getAssetsDir().'test_link_file';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_/placeholder.tmp',
$link
);
$c = new FilePermissionsIsIdenticalConstraint(0111);
$c->evaluate($link);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that file\#/.*tests/assets/dir/test_file\.txt 0644 permissions are equal to 0111\.$#
*/
public function testFilePermissionsMaskConstraintFileMismatch()
{
$c = new FilePermissionsIsIdenticalConstraint(0111);
$c->evaluate($this->getTestFile());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that file\#/.*tests/assets/dir/test_file\.txt 0100644 permissions are equal to 0100775\.$#
*/
public function testFilePermissionsMaskConstraintFileMismatchLarge()
{
$c = new FilePermissionsIsIdenticalConstraint(100775);
$c->evaluate($this->getTestFile());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that file\#/.*tests/assets/dir/test_file\.txt -rw-r--r-- permissions are equal to -rw-rw-rw-\.$#
*/
public function testFilePermissionsMaskConstraintFileMismatchString()
{
$c = new FilePermissionsIsIdenticalConstraint('-rw-rw-rw-');
$c->evaluate($this->getTestFile());
}
public function testPermissionFormat()
{
$refection = new ReflectionClass('GeckoPackages\PHPUnit\Constraints\FilePermissionsIsIdenticalConstraint');
$refectionProperty = $refection->getProperty('permissionFormat');
$refectionProperty->setAccessible(true);
$permissionFormat = $refectionProperty->getValue($this);
$this->assertRegExp($permissionFormat, 'lrwxrwxrwx');
$this->assertRegExp($permissionFormat, '-rw-rw-r--');
$this->assertRegExp($permissionFormat, 'drwxrwxr-x');
$this->assertRegExp($permissionFormat, 'd--s--S--t');
$this->assertNotRegExp($permissionFormat, ' d--s--S--t');
$this->assertNotRegExp($permissionFormat, 'd--s--S--t ');
$this->assertNotRegExp($permissionFormat, 'ad--s--S--t');
$this->assertNotRegExp($permissionFormat, 'd--s--S--ta');
$this->assertNotRegExp($permissionFormat, 'a');
$this->assertNotRegExp($permissionFormat, 'd-');
$this->assertNotRegExp($permissionFormat, '-rw-rw-r-');
$this->assertNotRegExp($permissionFormat, 'lrwxawxrwx');
$this->assertNotRegExp($permissionFormat, 'arwxrwxr-x');
$this->assertNotRegExp($permissionFormat, '-rrrwwwxxx');
}
/**
* @param string $expected
* @param int $input
*
* @dataProvider provideFilePermissions
*/
public function testPermissionsGetAsString(string $expected, int $input)
{
$reflection = new \ReflectionClass('GeckoPackages\PHPUnit\Constraints\FilePermissionsIsIdenticalConstraint');
$method = $reflection->getMethod('getFilePermissionsAsString');
$method->setAccessible(true);
$this->assertSame($expected, $method->invokeArgs($this, [$input]));
}
public function provideFilePermissions(): array
{
return [
['drwxr-xr-x', fileperms($this->getAssetsDir().'/dir')], // 7775
['urwxrwxrwx', 0777],
['prwxrwxrwx', 010777],
['crwxrwxrwx', 020777],
['brwxrwxrwx', 060777],
['srwxrwxrwx', 0140777],
];
}
private function getTestFile(): string
{
return realpath($this->getAssetsDir().'/dir/test_file.txt');
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/DirectoryEmptyConstraintTest.php | tests/PHPUnit/Tests/Constraints/DirectoryEmptyConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\DirectoryEmptyConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class DirectoryEmptyConstraintTest extends AbstractGeckoPHPUnitFileTest
{
public function testDirectoryEmptyConstraint()
{
$dir = $this->getAssetsDir().'emptyDirTest';
if (!is_dir($dir)) {
mkdir($dir);
}
$constraint = new DirectoryEmptyConstraint();
$this->assertTrue($constraint->evaluate($dir, '', true));
@unlink($dir);
}
public function testDirectoryEmptyConstraintBasics()
{
$constraint = new DirectoryEmptyConstraint();
$this->assertSame(1, $constraint->count());
$this->assertSame('is an empty directory', $constraint->toString());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that directory\#/.*PHPUnit/tests/PHPUnit/Tests/Constraints is an empty directory\.$#
*/
public function testDirectoryEmptyConstraintDirWithFiles()
{
$constraint = new DirectoryEmptyConstraint();
$constraint->evaluate(__DIR__, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that file\#/.*PHPUnit/tests/PHPUnit/Tests/Constraints/DirectoryEmptyConstraintTest\.php is an empty directory\.$#
*/
public function testDirectoryEmptyConstraintFile()
{
$constraint = new DirectoryEmptyConstraint();
$constraint->evaluate(__FILE__, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that link to file\#/.*test_link_file is an empty directory\.$#
*/
public function testDirectoryEmptyConstraintFileLink()
{
$link = $this->getAssetsDir().'test_link_file';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_/placeholder.tmp',
$link
);
$constraint = new DirectoryEmptyConstraint();
$constraint->evaluate($link, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that integer\#1 is an empty directory\.$#
*/
public function testDirectoryEmptyConstraintInt()
{
$constraint = new DirectoryEmptyConstraint();
$constraint->evaluate(1, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null is an empty directory\.$#
*/
public function testDirectoryEmptyConstraintNull()
{
$constraint = new DirectoryEmptyConstraint();
$constraint->evaluate(null, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that stdClass\# is an empty directory\.$#
*/
public function testDirectoryEmptyConstraintObject()
{
$constraint = new DirectoryEmptyConstraint();
$constraint->evaluate(new \stdClass(), '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that __does_not_exists__ is an empty directory\.$#
*/
public function testDirectoryEmptyConstraintString()
{
$constraint = new DirectoryEmptyConstraint();
$constraint->evaluate('__does_not_exists__', '');
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/ScalarConstraintTest.php | tests/PHPUnit/Tests/Constraints/ScalarConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\ScalarConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class ScalarConstraintTest extends AbstractGeckoPHPUnitTest
{
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that integer\#1 is of type array\.$#
*/
public function testArray()
{
$constraint = new ScalarConstraint(ScalarConstraint::TYPE_ARRAY);
$this->assertTrue($constraint->evaluate([], '', true));
$this->assertFalse($constraint->evaluate(1, '', false));
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null is of type bool\.$#
*/
public function testBool()
{
$constraint = new ScalarConstraint(ScalarConstraint::TYPE_BOOL);
$this->assertTrue($constraint->evaluate(true, '', true));
$this->assertFalse($constraint->evaluate(null, '', false));
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that stdClass\# is of type float\.$#
*/
public function testFloat()
{
$constraint = new ScalarConstraint(ScalarConstraint::TYPE_FLOAT);
$this->assertTrue($constraint->evaluate(1.1, '', true));
$this->assertFalse($constraint->evaluate(new \stdClass(), '', false));
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null is of type int\.$#
*/
public function testInt()
{
$constraint = new ScalarConstraint(ScalarConstraint::TYPE_INT);
$this->assertTrue($constraint->evaluate(1, '', true));
$this->assertFalse($constraint->evaluate(null, '', false));
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null is of type string\.$#
*/
public function testString()
{
$constraint = new ScalarConstraint(ScalarConstraint::TYPE_STRING);
$this->assertTrue($constraint->evaluate('', '', true));
$this->assertFalse($constraint->evaluate(null, '', false));
}
public function testToString()
{
$constraint = new ScalarConstraint(ScalarConstraint::TYPE_ARRAY);
$this->assertSame('is of type "array".', $constraint->toString());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null is of type scalar\.$#
*/
public function testScalar()
{
$constraint = new ScalarConstraint(ScalarConstraint::TYPE_SCALAR);
$this->assertSame(1, $constraint->count());
$this->assertTrue($constraint->evaluate(1, '', true));
$this->assertFalse($constraint->evaluate(null, '', false));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessageRegExp #^Unknown ScalarConstraint type "integer\#123456789" provided\.$#
*/
public function testUnknownValue()
{
new ScalarConstraint(123456789);
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/UnsignedIntConstraintTest.php | tests/PHPUnit/Tests/Constraints/UnsignedIntConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\UnsignedIntConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class UnsignedIntConstraintTest extends AbstractGeckoPHPUnitTest
{
public function testUnsignedIntConstraint()
{
$constraint = new UnsignedIntConstraint();
$this->assertSame('is unsigned int', $constraint->toString());
$this->assertTrue($constraint->evaluate(0, '', true));
$this->assertTrue($constraint->evaluate(time(), '', true));
$this->assertTrue($constraint->evaluate(PHP_INT_MAX, '', true));
}
/**
* @param mixed $invalid
*
* @dataProvider provideFailCases
*/
public function testUnsignedIntConstraintFail($invalid)
{
$constraint = new UnsignedIntConstraint();
$this->assertFalse($constraint->evaluate($invalid, '', true));
}
public function provideFailCases(): array
{
return [
[-1],
[0.1],
[1.5],
['123'],
[false],
[null],
[new \stdClass()],
];
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null is unsigned int\.$#
*/
public function testUnsignedIntConstraintFailMessage()
{
$constraint = new UnsignedIntConstraint();
$constraint->evaluate(null);
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/SameStringsConstraintTest.php | tests/PHPUnit/Tests/Constraints/SameStringsConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\SameStringsConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class SameStringsConstraintTest extends AbstractGeckoPHPUnitTest
{
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that two strings are identical.[\n] \#Warning\: Strings contain different line endings\! Debug using remapping \[\"\\r\" => \"R\", \"\\n\" => \"N\", \"\\t\" => \"T\"\]\:\n \-N\n \+RN$#
*/
public function testSameStringsConstraintFail()
{
$constraint = new SameStringsConstraint("\r\n");
$constraint->evaluate("\n");
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/FileIsValidLinkConstraintTest.php | tests/PHPUnit/Tests/Constraints/FileIsValidLinkConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\FileIsValidLinkConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class FileIsValidLinkConstraintTest extends AbstractGeckoPHPUnitFileTest
{
public function testFileIsValidLinkToFile()
{
$link = $this->getAssetsDir().'test_link_file';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_/placeholder.tmp',
$link
);
$constraint = new FileIsValidLinkConstraint();
$this->assertTrue($constraint->evaluate($link, '', true));
}
public function testFileIsValidLinkToDir()
{
$link = $this->getAssetsDir().'test_link_dir';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_',
$link
);
$constraint = new FileIsValidLinkConstraint();
$this->assertTrue($constraint->evaluate($link, '', true));
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that link\#/.*tests/assets/invalid_link is a valid link\.$#
*/
public function testFileIsValidLinkToNowhere()
{
$constraint = new FileIsValidLinkConstraint();
$constraint->evaluate($this->getAssetsDir().'invalid_link');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that stdClass\# is a valid link\.$#
*/
public function testFileIsValidLinkObject()
{
$constraint = new FileIsValidLinkConstraint();
$constraint->evaluate(new \stdClass());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null is a valid link\.$#
*/
public function testFileIsValidLinkNull()
{
$constraint = new FileIsValidLinkConstraint();
$constraint->evaluate(null);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that string\#a is a valid link\.$#
*/
public function testFileIsValidLinkString()
{
$constraint = new FileIsValidLinkConstraint();
$constraint->evaluate('a');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that integer\#1 is a valid link\.$#
*/
public function testFileIsValidLinkNotString()
{
$constraint = new FileIsValidLinkConstraint();
$constraint->evaluate(1);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that file\#/.*tests/assets/dir/test_file\.txt is a valid link\.$#
*/
public function testFileIsValidLinkFile()
{
$constraint = new FileIsValidLinkConstraint();
$constraint->evaluate($this->getAssetsDir().'dir/test_file.txt');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that directory\#/.*tests/assets/ is a valid link\.$#
*/
public function testFileIsValidLinkDir()
{
$constraint = new FileIsValidLinkConstraint();
$constraint->evaluate($this->getAssetsDir());
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/FileIsLinkConstraintTest.php | tests/PHPUnit/Tests/Constraints/FileIsLinkConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\FileIsLinkConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class FileIsLinkConstraintTest extends AbstractGeckoPHPUnitFileTest
{
/**
* @param string $link
*
* @dataProvider provideLinks
*/
public function testFileIsLinkConstraint(string $link)
{
$constraint = new FileIsLinkConstraint();
$this->assertTrue($constraint->evaluate($link, '', true));
}
public function provideLinks(): array
{
$link = $this->getAssetsDir().'test_link_file';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_/placeholder.tmp',
$link
);
$dirLink = $this->getAssetsDir().'test_link_dir';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_',
$dirLink
);
return [
[$link],
[$dirLink],
];
}
public function testFileIsLinkConstraintBasics()
{
$constraint = new FileIsLinkConstraint();
$this->assertSame(1, $constraint->count());
$this->assertSame('is a link', $constraint->toString());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that directory\#/.*PHPUnit/tests/PHPUnit/Tests/Constraints is a link\.$#
*/
public function testFileIsLinkConstraintDir()
{
$constraint = new FileIsLinkConstraint();
$constraint->evaluate(__DIR__, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that file\#/.*PHPUnit/tests/PHPUnit/Tests/Constraints/FileIsLinkConstraintTest.php is a link\.$#
*/
public function testFileIsLinkConstraintFile()
{
$constraint = new FileIsLinkConstraint();
$constraint->evaluate(__FILE__, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that integer\#1 is a link\.$#
*/
public function testFileIsLinkConstraintInt()
{
$constraint = new FileIsLinkConstraint();
$constraint->evaluate(1, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null is a link\.$#
*/
public function testFileIsLinkConstraintNull()
{
$constraint = new FileIsLinkConstraint();
$constraint->evaluate(null, '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that stdClass\# is a link\.$#
*/
public function testFileIsLinkConstraintObject()
{
$constraint = new FileIsLinkConstraint();
$constraint->evaluate(new \stdClass(), '');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that __does_not_exists__ is a link\.$#
*/
public function testFileIsLinkConstraintString()
{
$constraint = new FileIsLinkConstraint();
$constraint->evaluate('__does_not_exists__', '');
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/XML/XMLValidConstraintTest.php | tests/PHPUnit/Tests/Constraints/XML/XMLValidConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\XML\XMLValidConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class XMLValidConstraintTest extends AbstractGeckoPHPUnitTest
{
public function testXMLValidConstraint()
{
$constraint = new XMLValidConstraint();
$this->assertTrue($constraint->evaluate('<a></a>', '', true));
}
public function testXMLValidConstraintBasics()
{
$constraint = new XMLValidConstraint();
$this->assertSame(1, $constraint->count());
$this->assertSame('is valid XML', $constraint->toString());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that boolean\# is valid XML\.$#
*/
public function testXMLValidConstraintFalse()
{
$constraint = new XMLValidConstraint();
$constraint->evaluate(false);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that integer\#1 is valid XML\.$#
*/
public function testXMLValidConstraintInt()
{
$constraint = new XMLValidConstraint();
$constraint->evaluate(1);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that <a></b> is valid XML.[\n]\[error \d{1,}\](?s).*\.$#
*/
public function testXMLValidConstraintInvalidXML()
{
$constraint = new XMLValidConstraint();
$constraint->evaluate('<a></b>');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null is valid XML\.$#
*/
public function testXMLValidConstraintNull()
{
$constraint = new XMLValidConstraint();
$constraint->evaluate(null);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that stdClass\# is valid XML\.$#
*/
public function testXMLValidConstraintObject()
{
$constraint = new XMLValidConstraint();
$constraint->evaluate(new \stdClass());
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Constraints/XML/XMLMatchesXSDConstraintTest.php | tests/PHPUnit/Tests/Constraints/XML/XMLMatchesXSDConstraintTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Constraints\XML\XMLMatchesXSDConstraint;
/**
* @internal
*
* @author SpacePossum
*/
final class XMLMatchesXSDConstraintTest extends AbstractGeckoPHPUnitFileTest
{
public function testAssertXMLMatchesXSD()
{
$constraint = new XMLMatchesXSDConstraint($this->getXSD());
$this->assertTrue($constraint->evaluate(file_get_contents($this->getAssetsDir().'XLIFF/xliff_sample.xml'), '', true));
}
public function testXMLValidConstraintBasics()
{
$constraint = new XMLMatchesXSDConstraint('');
$this->assertSame(1, $constraint->count());
$this->assertSame('matches XSD', $constraint->toString());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that boolean\# matches XSD\.$#
*/
public function testXMLValidConstraintFalse()
{
$constraint = new XMLMatchesXSDConstraint($this->getXSD());
$constraint->evaluate(false);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that integer\#1 matches XSD\.$#
*/
public function testXMLValidConstraintInt()
{
$constraint = new XMLMatchesXSDConstraint($this->getXSD());
$constraint->evaluate(1);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that <a></b> matches XSD.[\n]\[error \d{1,}\](?s).*\.$#
*/
public function testXMLValidConstraintInvalidXML()
{
$constraint = new XMLMatchesXSDConstraint($this->getXSD());
$constraint->evaluate('<a></b>');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that <a></a> matches XSD.[\n]\[error \d{1,}\](?s).*\.$#
*/
public function testXMLValidConstraintNotMatchingXML()
{
$constraint = new XMLMatchesXSDConstraint($this->getXSD());
$constraint->evaluate('<a></a>');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that null matches XSD\.$#
*/
public function testXMLValidConstraintNull()
{
$constraint = new XMLMatchesXSDConstraint($this->getXSD());
$constraint->evaluate(null);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that stdClass\# matches XSD\.$#
*/
public function testXMLValidConstraintObject()
{
$constraint = new XMLMatchesXSDConstraint($this->getXSD());
$constraint->evaluate(new \stdClass());
}
/**
* @return string
*/
private function getXSD(): string
{
return file_get_contents($this->getAssetsDir().'XLIFF/xliff-core-1.2-strict.xsd');
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Asserts/StringsAssertTraitTest.php | tests/PHPUnit/Tests/Asserts/StringsAssertTraitTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Asserts\StringsAssertTrait;
/**
* @internal
*
* @author SpacePossum
*/
final class StringsAssertTraitTest extends AbstractGeckoPHPUnitTest
{
use StringsAssertTrait;
public function testAssertNotSameStrings()
{
$this->assertNotSameStrings("\n", "\r\n");
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that two strings are not identical\.$#
*/
public function testAssertNotSameStringsFail()
{
$this->assertNotSameStrings("\r\n", "\r\n");
}
public function testAssertSameStrings()
{
$this->assertSameStrings('a', 'a');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that two strings are identical\.$#
*/
public function testAssertSameStringsFail()
{
$this->assertSameStrings('a', 'b');
}
public function testAssertStringIsEmpty()
{
$this->assertStringIsEmpty('');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that a string is empty\.$#
*/
public function testAssertStringIsEmptyFail()
{
$this->assertStringIsEmpty('a');
}
public function testAssertStringIsNotEmpty()
{
$this->assertStringIsNotEmpty(' a');
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that a string is not empty\.$#
*/
public function testAssertStringIsNotEmptyFail()
{
$this->assertStringIsNotEmpty('');
}
public function testAssertStringIsNotWhiteSpace()
{
$this->assertStringIsNotWhiteSpace("\n\t \n1");
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that a string is not empty\.$#
*/
public function testAssertStringIsNotWhiteSpaceFail()
{
$this->assertStringIsNotWhiteSpace("\n\t \n");
}
public function testAssertStringIsWhiteSpace()
{
$this->assertStringIsWhiteSpace("\n\t \n");
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that a string is empty\.$#
*/
public function testAssertStringIsWhiteSpaceFail()
{
$this->assertStringIsWhiteSpace('test');
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Asserts/AliasAssertTraitTest.php | tests/PHPUnit/Tests/Asserts/AliasAssertTraitTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Asserts\AliasAssertTrait;
/**
* @internal
*
* @author SpacePossum
*/
final class AliasAssertTraitTest extends GeckoTestCase
{
use AliasAssertTrait;
public function testAssertArray()
{
$this->assertArray([]);
}
public function testAssertBool()
{
$this->assertBool(true);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that DateTime\# is of type bool\.$#
*/
public function testAssertBoolFail()
{
$this->assertBool(new \DateTime());
}
public function testAssertFloat()
{
$this->assertFloat(1.0);
}
public function testAssertInt()
{
$this->assertInt(1);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that double\#1 is of type int\.$#
*/
public function testAssertIntFail()
{
$this->assertInt(1.0);
}
public function testAssertScalar()
{
$this->assertScalar(1);
}
public function testAssertString()
{
$this->assertString('test');
}
public function testAssertNotArray()
{
$this->assertNotArray(1);
}
public function testAssertNotBool()
{
$this->assertNotBool('true');
}
public function testAssertNotFloat()
{
$this->assertNotFloat(-9);
}
public function testAssertNotInt()
{
$this->assertNotInt('a');
}
public function testAssertNotScalar()
{
$this->assertNotScalar(new \stdClass());
}
public function testAssertNotString()
{
$this->assertNotString(false);
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Asserts/XMLAssertTraitTest.php | tests/PHPUnit/Tests/Asserts/XMLAssertTraitTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Asserts\XMLAssertTrait;
/**
* @internal
*
* @author SpacePossum
*/
final class XMLAssertTraitTest extends AbstractGeckoPHPUnitTest
{
use XMLAssertTrait;
public function testAssertXMLMatchesXSD()
{
$this->assertXMLMatchesXSD(file_get_contents($this->getAssetsDir().'XLIFF/xliff-core-1.2-strict.xsd'), file_get_contents($this->getAssetsDir().'XLIFF/xliff_sample.xml'));
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that <note><test>Test</test></note> matches XSD\.[\n]\[error 1845\] .+\.$#
*/
public function testAssertXMLMatchesXSDFail()
{
$this->assertXMLMatchesXSD(file_get_contents($this->getAssetsDir().'XLIFF/xliff-core-1.2-strict.xsd'), '<note><test>Test</test></note>');
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that stdClass\# matches XSD\.$#
*/
public function testAssertXMLMatchesXSDInvalidInputXML()
{
$this->assertXMLMatchesXSD('', new \stdClass());
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp /^Argument #1 \(integer#1\) of XMLAssertTrait::assertXMLMatchesXSD\(\) must be a string\.$/
*/
public function testAssertXMLMatchesXSDInvalidInputXSD()
{
$this->assertXMLMatchesXSD(1, '');
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that b matches XSD.[\n]\[fatal 4\] .+\.$#
*/
public function testAssertXMLMatchesXSDInvalidXMLInvalidXSD()
{
$this->assertXMLMatchesXSD('a', 'b');
}
public function testAssertXMLValid()
{
$this->assertXMLValid('<note><test>Test</test></note>');
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that test string is valid XML.[\n]\[fatal 4\] .+\.$#
*/
public function testAssertXMLValidFail()
{
$this->assertXMLValid('test string');
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp /^Failed asserting that integer\#1234 is valid XML\.$/
*/
public function testAssertXMLValidInvalidInput()
{
$this->assertXMLValid(1234);
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Asserts/AssertHelperTest.php | tests/PHPUnit/Tests/Asserts/AssertHelperTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
/**
* @internal
*
* @author SpacePossum
*/
final class AssertHelperTest extends AbstractGeckoPHPUnitTest
{
public static function setUpBeforeClass()
{
require_once __DIR__.'/AssertHelperTestDummies.php';
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^FileExistsAssertTrait::assertFileExists\(\) Relies on missing method "assertThat"\.$#
*/
public function testMissingMethod()
{
$dummy = new TestDummy();
$dummy->assertFileExists(__FILE__);
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Asserts/RangeAssertTraitTest.php | tests/PHPUnit/Tests/Asserts/RangeAssertTraitTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Asserts\RangeAssertTrait;
/**
* @internal
*
* @author SpacePossum
*/
final class RangeAssertTraitTest extends GeckoTestCase
{
use RangeAssertTrait;
public function testAssertNumberInRange()
{
$this->assertNumberInRange(1, 3, 2);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that -0\.500 is within range \(1\.100, 3\.200\)\.$#
*/
public function testAssertNumberInRangeFail()
{
$this->assertNumberInRange(1.1, 3.2, -0.5);
}
public function testAssertNumberNotInRange()
{
$this->assertNumberNotInRange(1, 3, 4);
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Argument \#1 \(null\) of RangeAssertTrait::assertNumberNotInRange\(\) must be a float or int\.$#
*/
public function testAssertNumberNotInRangeInvalidArgumentLower()
{
$this->assertNumberNotInRange(null, 3, 4);
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Argument \#2 \(string\#_invalid_\) of RangeAssertTrait::assertNumberNotInRange\(\) must be a float or int\.$#
*/
public function testAssertNumberNotInRangeInvalidArgumentUpper()
{
$this->assertNumberNotInRange(3, '_invalid_', 4);
}
public function testAssertNumberNotOnRange()
{
$this->assertNumberNotOnRange(-3, -2, -1);
}
public function testAssertNumberOnRange()
{
$this->assertNumberOnRange(1, 3, 3);
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Argument \#1 \(integer\#5\) of RangeAssertTrait::assertNumberOnRange\(\) lower boundary 5 must be smaller than upper boundary -5\.500\.$#
*/
public function testAssertNumberOnRangeInvalidRange()
{
$this->assertNumberOnRange(5, -5.5, 6);
}
public function testAssertUnsignedInt()
{
$this->assertUnsignedInt(4);
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that -4 is unsigned int\.$#
*/
public function testAssertUnsignedIntFail()
{
$this->assertUnsignedInt(-4);
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Asserts/FileExistsAssertTraitTest.php | tests/PHPUnit/Tests/Asserts/FileExistsAssertTraitTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Asserts\FileExistsAssertTrait;
/**
* @internal
*
* @author SpacePossum
*/
final class FileExistsAssertTraitTest extends AbstractGeckoPHPUnitFileTest
{
use FileExistsAssertTrait;
/**
* @param bool $expected
* @param string $file
*
* @dataProvider provideFiles
*/
public function testFileExists(bool $expected, string $file)
{
$expected
? $this->assertFileExists($file)
: $this->assertFileNotExists($file)
;
}
public function provideFiles(): array
{
$dirLink = $this->getAssetsDir().'test_link_dir';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_',
$dirLink
);
$fileLink = $this->getAssetsDir().'test_link_file';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_/placeholder.tmp',
$fileLink
);
return [
[true, __FILE__],
[true, $fileLink],
[false, $dirLink],
[false, __FILE__.time()],
[false, __DIR__],
];
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp %^Failed asserting that directory#/.*PHPUnit/tests/PHPUnit/Tests/Asserts is a file\.$%
*/
public function testAssertFileExistsDirectory()
{
$this->assertFileExists(__DIR__);
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp /^Failed asserting that integer\#123 is a file\.$/
*/
public function testAssertFileExistsInt()
{
$this->assertFileExists(123);
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp /^Failed asserting that _no_file_ is a file\.$/
*/
public function testAssertFileExistsNoFile()
{
$this->assertFileExists('_no_file_');
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp /^Failed asserting that null is a file\.$/
*/
public function testAssertFileExistsNull()
{
$this->assertFileExists(null);
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp /^Failed asserting that stdClass\# is a file\.$/
*/
public function testAssertFileExistsObject()
{
$this->assertFileExists(new \stdClass());
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Asserts/AssertHelperTestDummies.php | tests/PHPUnit/Tests/Asserts/AssertHelperTestDummies.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Asserts\AliasAssertTrait;
use GeckoPackages\PHPUnit\Asserts\FileExistsAssertTrait;
use GeckoPackages\PHPUnit\Asserts\FileSystemAssertTrait;
use GeckoPackages\PHPUnit\Asserts\XMLAssertTrait;
/**
* @internal
*
* @author SpacePossum
*/
final class TestDummy
{
use AliasAssertTrait;
use FileExistsAssertTrait;
use FileSystemAssertTrait;
use XMLAssertTrait;
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
GeckoPackages/GeckoPHPUnit | https://github.com/GeckoPackages/GeckoPHPUnit/blob/a740ef4f1e194ad661e0edddb17823793d46d9e4/tests/PHPUnit/Tests/Asserts/FileSystemAssertTraitTest.php | tests/PHPUnit/Tests/Asserts/FileSystemAssertTraitTest.php | <?php
declare(strict_types=1);
/*
* This file is part of the GeckoPackages.
*
* (c) GeckoPackages https://github.com/GeckoPackages
*
* This source file is subject to the MIT license that is bundled
* with this source code in the file LICENSE.
*/
use GeckoPackages\PHPUnit\Asserts\FileSystemAssertTrait;
/**
* @internal
*
* @author SpacePossum
*/
final class FileSystemAssertTraitTest extends AbstractGeckoPHPUnitFileTest
{
use FileSystemAssertTrait;
private $expectedDirPermissions = 755;
private $expectedFilePermissions = 644;
public function testAssertDirectoryEmpty()
{
$dir = $this->getAssetsDir().time();
mkdir($dir);
$this->assertDirectoryEmpty($dir);
rmdir($dir);
$this->assertDirectoryNotEmpty($this->getTestDir());
}
/**
* @param string|int $permission
* @param string $file
*
* @dataProvider provideFiles
*/
public function testAssertFileHasPermissions($permission, string $file)
{
$this->assertPermissionsFilesToTest();
$this->assertFileHasPermissions($permission, $file);
}
public function provideFiles(): array
{
$link = $this->getAssetsDir().'test_link_dir';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_',
$link
);
return [
[0755, $this->getTestDir()],
['0'.$this->expectedDirPermissions, $this->getTestDir()],
['493', $this->getTestDir()],
['drwxr-xr-x', $this->getTestDir()],
[0644, $this->getTestFile()],
[100644, $this->getTestFile()],
['-rw-r--r--', $this->getTestFile()],
['lrwxrwxrwx', $link],
];
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that directory\#/.*tests/assets/dir 0755 permissions are equal to 0644\.$#
*/
public function testAssertFileHasPermissionsFailureDir()
{
$this->assertPermissionsFilesToTest();
$this->assertFileHasPermissions(0644, $this->getTestDir());
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that file\#/.*tests/assets/dir/test_file\.txt 0644 permissions are equal to 0555\.$#
*/
public function testAssertFileHasPermissionsFailureFile()
{
$this->assertPermissionsFilesToTest();
$this->assertFileHasPermissions(0555, $this->getTestFile());
}
public function testAssertFileIsLink()
{
$link = $this->getAssetsDir().'test_link_dir';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_',
$link
);
$this->assertFileIsLink($link);
$this->assertFileIsNotLink($this->getTestFile());
}
/**
* @param int $mask
*
* @dataProvider provideFileMasks
*/
public function testAssertFilePermissionMask(int $mask)
{
$this->assertPermissionsFilesToTest();
$this->assertFilePermissionMask($mask, $this->getTestFile());
}
public function provideFileMasks(): array
{
return [
[0644],
[0000],
[0004],
[0040],
[0044],
[0600],
[0604],
[0640],
];
}
public function testAssertFilePermissionLink()
{
$link = $this->getAssetsDir().'test_link_dir';
$this->createSymlink(
$this->getAssetsDir().'_link_test_target_dir_',
$link
);
$this->assertFilePermissionMask(0644, $link);
}
/**
* @param int $mask
*
* @dataProvider provideFilePermissionNotMask
*/
public function testAssertFilePermissionNotMask(int $mask)
{
$this->assertPermissionsFilesToTest();
$this->assertFilePermissionNotMask($mask, $this->getTestFile());
}
public function provideFilePermissionNotMask(): array
{
return [
[0007],
[0005],
[0055],
[0777],
[0005],
[0050],
[0764],
[0700],
[0704],
[0650],
[0764],
];
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that directory\#/.*tests/assets/dir is an empty directory\.$#
*/
public function testAssertDirectoryEmptyFail()
{
$this->assertDirectoryEmpty($this->getTestDir());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that file\#/.*tests/assets/dir/test_file.txt is a link\.$#
*/
public function testAssertFileIsLinkFailFile()
{
$this->assertFileIsLink($this->getTestFile());
}
/**
* @expectedException PHPUnit\Framework\ExpectationFailedException
* @expectedExceptionMessageRegExp #^Failed asserting that directory\#/.*tests/assets/dir is a link\.$#
*/
public function testAssertFileIsLinkFailDirectory()
{
$this->assertFileIsLink($this->getTestDir());
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that integer\#678 is a link\.$#
*/
public function testAssertFileIsLinkFailInteger()
{
$this->assertFileIsLink(678);
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Argument \#1 \(null\) of FileSystemAssertTrait::assertFileHasPermissions\(\) must be an int \(>= 0\) or string\.$#
*/
public function testAssertFileHasPermissionsFailNull()
{
$this->assertFileHasPermissions(null, $this->getTestFile());
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Argument \#1 \(stdClass\#\) of FileSystemAssertTrait::assertFileHasPermissions\(\) must be an int \(>= 0\) or string\.$#
*/
public function testAssertFileHasPermissionsFailObject()
{
$this->assertFileHasPermissions(new \stdClass(), $this->getTestFile());
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Argument \#1 \(string\#invalidrwx\) of FileSystemAssertTrait::assertFileHasPermissions\(\) Permission to match "invalidrwx" is not formatted correctly\.$#
*/
public function testAssertFileHasPermissionsFailInvalidPermissionString()
{
$this->assertFileHasPermissions('invalidrwx', $this->getTestFile());
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Argument \#1 \(integer\#-1\) of FileSystemAssertTrait::assertFileHasPermissions\(\) must be an int \(>= 0\) or string\.$#
*/
public function testAssertFileHasPermissionsFailInvalidPermissionValue()
{
$this->assertFileHasPermissions(-1, $this->getTestFile());
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that null permissions are equal\.$#
*/
public function testAssertFileHasPermissionsFailFile()
{
$this->assertPermissionsFilesToTest();
$this->assertFileHasPermissions(0777, null);
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that file\#/.*tests/assets/dir/test_file\.txt 100644 permissions matches mask 777\.$#
*/
public function testAssertFilePermissionMaskFail()
{
$this->assertPermissionsFilesToTest();
$this->assertFilePermissionMask(0777, $this->getTestFile());
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that directory\#/.*tests/assets/dir 40755 permissions does not match mask 755\.$#
*/
public function testAssertFilePermissionNotMaskFail()
{
$this->assertPermissionsFilesToTest();
$this->assertFilePermissionNotMask(0755, $this->getTestDir());
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Argument \#1 \(null\) of FileSystemAssertTrait::assertFilePermissionMask\(\) must be an int\.$#
*/
public function testAssertFilePermissionMaskInvalidArg1()
{
$this->assertPermissionsFilesToTest();
$this->assertFilePermissionMask(null, $this->getTestFile());
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that integer\#89 permissions matches mask\.$#
*/
public function testAssertFilePermissionMaskInvalidArg2()
{
$this->assertFilePermissionMask(0777, 89);
}
/**
* @expectedException PHPUnit\Framework\Exception
* @expectedExceptionMessageRegExp #^Failed asserting that not file or directory\#no_file permissions matches mask\.$#
*/
public function testAssertFilePermissionMaskInvalidArg2File()
{
$this->assertFilePermissionMask(0777, 'no_file');
}
/**
* Assert file and directory used in tests have expected permissions.
*
* Testing with those without the right permissions causes false negatives,
* including in environments like Travis.
*/
private function assertPermissionsFilesToTest()
{
$failures = [];
$perm = fileperms($this->getTestDir());
$perm = sprintf('%o', $perm);
$perm = (int) substr($perm, -3);
if ($this->expectedDirPermissions !== $perm) {
$failures[$this->getTestDir()] = [$perm, $this->expectedDirPermissions];
}
$perm = fileperms($this->getTestFile());
$perm = sprintf('%o', $perm);
$perm = (int) substr($perm, -3);
if (644 !== $perm) {
$failures[$this->getTestFile()] = [$perm, $this->expectedFilePermissions];
}
if (count($failures)) {
$message = '';
foreach ($failures as $item => $fail) {
$message .= sprintf(
"\nFailed test resource \"%s\" has permissions \"%d\", expected \"%d\".",
$item, $fail[0], $fail[1]
);
}
throw new \RuntimeException($message);
}
}
private function getTestDir(): string
{
return realpath($this->getAssetsDir().'/dir');
}
private function getTestFile(): string
{
return $this->getTestDir().'/test_file.txt';
}
}
| php | MIT | a740ef4f1e194ad661e0edddb17823793d46d9e4 | 2026-01-05T04:52:45.776658Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Project/model/UserModel.class.php | Project/model/UserModel.class.php | <?php
namespace App\model;
/**
* 数据模型类演示
* Class UserModel
* @package App\Model
*/
class UserModel
{
public function registerUser()
{
}
} | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Project/home/Index.class.php | Project/home/Index.class.php | <?php
namespace App\home;
use \Framework\Library\Process\Tool;
/**
* 默认首页控制器
* Class Index
* @package App\Home
*/
class Index
{
/**
* 默认首页
* @return mixed
*/
public function index()
{
//演示cli模式下处理
if (Tool::isCli()) {
return 'hello this is cli mode,framework version:'._V.'!';
}
return View('home/index')->data(['show' => 'PHP300Framework - 想象无极限', 'describe' => '每个人的生命都是一只小船,梦想是小船的风帆。'])->get();
}
} | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Project/config/App.cfg.php | Project/config/App.cfg.php | <?php
/**
* 应用配置
*/
return [
/**
* 数据库配置
*/
'db' => [
/**
* 默认连接
*/
'default' => [
/** 目标IP/域名 */
'host' => '127.0.0.1',
/** 目标端口 */
'port' => 3306,
/** 数据库用户名 */
'username' => 'root',
/** 数据库密码 */
'password' => 'root',
/** 数据库名称 */
'database' => 'test',
/** 数据表前缀 */
'tabprefix' => '',
/** 数据库编码 */
'char' => 'utf8',
/**
* 数据库驱动类型
* mysqli
* pdo
*/
'dbType' => 'mysqli',
/** 是否使用该数据库配置 */
'connect' => false
]
],
/**
* 缓存配置
*/
'cache' => [
/**
* 缓存服务类型
* memcache(默认端口:11211)
* redis(默认端口:6379)
* file
*/
'cacheType' => 'file',
/** 缓存服务器IP/域名(类型为file可忽略) */
'ip' => '',
/** 缓存服务器端口(类型为file可忽略) */
'port' => '',
],
/**
* 路由配置
*/
'router' => [
/**
* 演示路由
* 这里的实例名称和控制器名称全部小写
*/
'/home/index/test' => function () {
//这里是自定义操作
return '这是router配置中路由的测试';
},
],
/**
* 安全配置
*/
'safe' => [
/**
* ajax域名白名单(默认只允许当前域名)
*/
'ajax_domain' => [ /* 一行一个域名,需要带上协议,例如:https://www.baidu.com */
]
]
]; | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Class/UploadFile.class.php | Extend/Class/UploadFile.class.php | <?php
/**
* 文件上传 - PHP300扩展类
* Class Upload
*/
class Upload
{
/** @var array 允许的扩展名 */
public $allowExts = array();
/** @var array 允许的文件类型 */
public $allowTypes = array();
/** @var string 文件保存路径 */
public $savePath = './Upload/';
/** @var int|string 最大上传大小 默认最大上传 2M = 2097152 B */
public $maxSize = 2097152;
//最近一次的错误
/** @var bool 自动检测文件 默认未开启 */
public $autoCheck = true;
/** @var bool 是否覆盖同名文件 默认不覆盖 */
public $uploadReplace = false;
private $error = '';
/** @var array 文件上传信息 */
private $uploadFileInfo;
/**
* 架构函数
* Upload constructor.
* @param string $allowExts
* @param string $maxSize
* @param string $allowTypes
*/
public function __construct($allowExts = '', $maxSize = '', $allowTypes = '')
{
//设置文件的后缀
if (!empty($allowExts)) {
if (is_array($allowExts)) {
$this->allowExts = array_map('strtolower', $allowExts);
} else {
$this->allowExts = explode(',', strtolower($allowExts));
}
}
if (!empty($maxSize) && is_numeric($maxSize)) {
$this->maxSize = $maxSize;
}
if (!empty($allowTypes)) {
if (is_array($allowTypes)) {
$this->allowTypes = array_map('strtolower', $allowTypes);
} else {
$this->allowTypes = explode(',', strtolower($allowTypes));
}
}
}
/**
* 上传所有文件
* @param string $savePath
* @return bool
*/
public function upload($savePath = '')
{
if (empty($savePath))
$savePath = $this->savePath;
$savePath = rtrim($savePath, '/') . '/';
if (!is_dir($savePath)) {
$this->createDir($savePath);
if (!is_dir($savePath)) {
$this->error = "目录{$savePath}不存在";
return false;
}
} else {
if (!is_writeable($savePath)) {
$this->error = "目录{$savePath}不可写";
return false;
}
}
$fileInfo = array();
$isUpload = false;
$files = $this->dealFiles($_FILES);
foreach ($files as $key => $file) {
if (!empty($file['name'])) {
$file['key'] = $key;
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
if ($this->autoCheck) {
if (!$this->check($file))
return false;
}
if (!$this->save($file)) return false;
unset($file['tmp_name'], $file['error']);
$fileInfo[] = $file;
$isUpload = true;
}
}
if ($isUpload) {
$this->uploadFileInfo = $fileInfo;
return true;
} else {
$this->error = '没有选择上传文件';
return false;
}
}
/**
* 遍历创建文件夹
* @param $path
*/
private function createDir($path)
{
if (!file_exists($path)) {
$this->createDir(dirname($path));
mkdir($path, 0777);
}
}
/**
* 处理$_FILES信息 将多个file分离
* @param $files
* @return array
*/
private function dealFiles($files)
{
$fileArray = array();
$n = 0;
foreach ($files as $file) {
if (is_array($file['name'])) {
//关联数组
$keys = array_keys($file);
$count = count($file['name']);
for ($i = 0; $i < $count; $i++) {
foreach ($keys as $key) {
$fileArray[$n][$key] = $file[$key][$i];
}
$n++;
}
} else {
$fileArray[$n] = $file;
$n++;
}
}
return $fileArray;
}
/**
* 获取扩展名
* @param $filename
* @return mixed
*/
private function getExt($filename)
{
$pathinfo = pathinfo($filename);
return $pathinfo['extension'];
}
/**
* 文件命名 规则
* @param $file
* @return string
*/
private function getSaveName($file)
{
$saveName = md5(uniqid()) . '.' . $file['extension'];
return $saveName;
}
/**
* 检测文件大小,文件扩展名,文件Mime类型,是否非法上传
* @param $file
* @return bool
*/
private function check($file)
{
if ($file['error'] !== 0) {
$this->error($file['error']);
return false;
}
if (!$this->checkSize($file['size'])) {
$this->error = '上传文件大小不符!';
return false;
}
if (!$this->checkExt($file['extension'])) {
$this->error = '上传文件类型不允许!';
return false;
}
if (!$this->checkType($file['type'])) {
$this->error = '上传文件MIME类型不允许!';
return false;
}
if (!$this->checkUpload($file['tmp_name'])) {
$this->error = '非法上传文件!';
return false;
}
return true;
}
/**
* 捕获错误上传信息
* @param $errorCode
*/
private function error($errorCode)
{
switch ($errorCode) {
case 1:
$this->error = '上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值';
break;
case 2:
$this->error = '上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值';
break;
case 3:
$this->error = '文件只有部分被上传';
break;
case 4:
$this->error = '没有文件被上传';
break;
case 6:
$this->error = '找不到临时文件夹';
break;
case 7:
$this->error = '文件写入失败';
break;
default:
$this->error = '未知上传错误!';
}
return;
}
/**
* 检测文件大小
* @param $size
* @return bool
*/
private function checkSize($size)
{
return $size < $this->maxSize;
}
/**
* 检测文件扩展名
* @param $extension
* @return bool
*/
private function checkExt($extension)
{
if (!empty($this->allowExts))
return in_array(strtolower($extension), $this->allowExts, true);
return true;
}
/**
* 检查文件Mime类型
* @param $type
* @return bool
*/
private function checkType($type)
{
if (!empty($this->allowTypes))
return in_array(strtolower($type), $this->allowTypes, true);
return true;
}
/**
* 检测是否非法上传
* @param $filename
* @return bool
*/
private function checkUpload($filename)
{
return is_uploaded_file($filename);
}
/**
* 保存一个文件
* @param $file
* @return bool
*/
private function save($file)
{
$filename = $file['savepath'] . $file['savename'];
if (!$this->uploadReplace && is_file($filename)) {
$this->error = '文件已经存在!' . $filename;
return false;
}
if (in_array(strtolower($file['extension']), array('gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf')) && false === getimagesize($file['tmp_name'])) {
$this->error = '非法图像文件';
return false;
}
if (!move_uploaded_file($file['tmp_name'], $filename)) {
$this->error = '文件上传保存错误!';
return false;
}
return true;
}
/**
* 通过指定文件的$_FILES['name']上传文件
* @param $file
* @param string $savePath
* @return bool
*/
public function uploadOne($file, $savePath = '')
{
if (empty($savePath))
$savePath = $this->savePath;
$savePath = rtrim($savePath, '/') . '/';
if (!is_dir($savePath)) {
$this->createDir($savePath);
if (!is_dir($savePath)) {
$this->error = "目录{$savePath}不存在";
return false;
}
} else {
if (!is_writeable($savePath)) {
$this->error = '上传目录' . $savePath . '不可写';
return false;
}
}
if (!empty($file['name'])) {
$fileArray = array();
if (is_array($file['name'])) {
$keys = array_keys($file);
$count = count($file['name']);
for ($i = 0; $i < $count; $i++) {
foreach ($keys as $key)
$fileArray[$i][$key] = $file[$key][$i];
}
} else {
$fileArray[] = $file;
}
$fileInfo = array();
foreach ($fileArray as $key => $file) {
$file['extension'] = $this->getExt($file['name']);
$file['savepath'] = $savePath;
$file['savename'] = $this->getSaveName($file);
if ($this->autoCheck) {
if (!$this->check($file))
return false;
}
if (!$this->save($file)) return false;
unset($file['tmp_name'], $file['error']);
$fileInfo[] = $file;
}
$this->uploadFileInfo = $fileInfo;
return true;
} else {
$this->error = '没有选择上传文件';
return false;
}
}
/**
* 获取文件上传成功之后的信息
* @return array 文件上传信息
*/
public function getUploadFileInfo()
{
return $this->uploadFileInfo;
}
/**
* 获取最近一次的错误信息
* @return string
*/
public function getErrorMsg()
{
return $this->error;
}
} | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/Smarty.class.php | Extend/Package/smarty/Smarty.class.php | <?php
/**
* Project: Smarty: the PHP compiling template engine
* File: Smarty.class.php
*
* 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
* For questions, help, comments, discussion, etc., please join the
* Smarty mailing list. Send a blank e-mail to
* smarty-discussion-subscribe@googlegroups.com
*
* @link http://www.smarty.net/
* @copyright 2017 New Digital Group, Inc.
* @copyright 2017 Uwe Tews
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
* @author Rodney Rehm
* @package Smarty
* @version 3.1.32-dev
*/
/**
* set SMARTY_DIR to absolute path to Smarty library files.
* Sets SMARTY_DIR only if user application has not already defined it.
*/
if (!defined('SMARTY_DIR')) {
/**
*
*/
define('SMARTY_DIR', dirname(__FILE__) . DIRECTORY_SEPARATOR);
}
/**
* set SMARTY_SYSPLUGINS_DIR to absolute path to Smarty internal plugins.
* Sets SMARTY_SYSPLUGINS_DIR only if user application has not already defined it.
*/
if (!defined('SMARTY_SYSPLUGINS_DIR')) {
/**
*
*/
define('SMARTY_SYSPLUGINS_DIR', SMARTY_DIR . 'sysplugins' . DIRECTORY_SEPARATOR);
}
if (!defined('SMARTY_PLUGINS_DIR')) {
/**
*
*/
define('SMARTY_PLUGINS_DIR', SMARTY_DIR . 'plugins' . DIRECTORY_SEPARATOR);
}
if (!defined('SMARTY_MBSTRING')) {
/**
*
*/
define('SMARTY_MBSTRING', function_exists('mb_get_info'));
}
if (!defined('SMARTY_RESOURCE_CHAR_SET')) {
// UTF-8 can only be done properly when mbstring is available!
/**
* @deprecated in favor of Smarty::$_CHARSET
*/
define('SMARTY_RESOURCE_CHAR_SET', SMARTY_MBSTRING ? 'UTF-8' : 'ISO-8859-1');
}
if (!defined('SMARTY_RESOURCE_DATE_FORMAT')) {
/**
* @deprecated in favor of Smarty::$_DATE_FORMAT
*/
define('SMARTY_RESOURCE_DATE_FORMAT', '%b %e, %Y');
}
/**
* Load Smarty_Autoloader
*/
if (!class_exists('Smarty_Autoloader')) {
include dirname(__FILE__) . '/bootstrap.php';
}
/**
* Load always needed external class files
*/
require_once SMARTY_SYSPLUGINS_DIR . 'smarty_internal_data.php';
require_once SMARTY_SYSPLUGINS_DIR . 'smarty_internal_extension_handler.php';
require_once SMARTY_SYSPLUGINS_DIR . 'smarty_internal_templatebase.php';
require_once SMARTY_SYSPLUGINS_DIR . 'smarty_internal_template.php';
require_once SMARTY_SYSPLUGINS_DIR . 'smarty_resource.php';
require_once SMARTY_SYSPLUGINS_DIR . 'smarty_variable.php';
require_once SMARTY_SYSPLUGINS_DIR . 'smarty_template_source.php';
require_once SMARTY_SYSPLUGINS_DIR . 'smarty_template_resource_base.php';
require_once SMARTY_SYSPLUGINS_DIR . 'smarty_internal_resource_file.php';
/**
* This is the main Smarty class
*
* @package Smarty
*
* The following methods will be dynamically loaded by the extension handler when they are called.
* They are located in a corresponding Smarty_Internal_Method_xxxx class
*
* @method int clearAllCache(int $exp_time = null, string $type = null)
* @method int clearCache(string $template_name, string $cache_id = null, string $compile_id = null, int $exp_time = null, string $type = null)
* @method int compileAllTemplates(string $extension = '.tpl', bool $force_compile = false, int $time_limit = 0, $max_errors = null)
* @method int compileAllConfig(string $extension = '.conf', bool $force_compile = false, int $time_limit = 0, $max_errors = null)
* @method int clearCompiledTemplate($resource_name = null, $compile_id = null, $exp_time = null)
*/
class Smarty extends Smarty_Internal_TemplateBase
{
/**
* smarty version
*/
const SMARTY_VERSION = '3.1.32-dev-38';
/**
* define variable scopes
*/
const SCOPE_LOCAL = 1;
const SCOPE_PARENT = 2;
const SCOPE_TPL_ROOT = 4;
const SCOPE_ROOT = 8;
const SCOPE_SMARTY = 16;
const SCOPE_GLOBAL = 32;
/**
* define caching modes
*/
const CACHING_OFF = 0;
const CACHING_LIFETIME_CURRENT = 1;
const CACHING_LIFETIME_SAVED = 2;
/**
* define constant for clearing cache files be saved expiration dates
*/
const CLEAR_EXPIRED = -1;
/**
* define compile check modes
*/
const COMPILECHECK_OFF = 0;
const COMPILECHECK_ON = 1;
const COMPILECHECK_CACHEMISS = 2;
/**
* define debug modes
*/
const DEBUG_OFF = 0;
const DEBUG_ON = 1;
const DEBUG_INDIVIDUAL = 2;
/**
* modes for handling of "<?php ... ?>" tags in templates.
*/
const PHP_PASSTHRU = 0; //-> print tags as plain text
const PHP_QUOTE = 1; //-> escape tags as entities
const PHP_REMOVE = 2; //-> escape tags as entities
const PHP_ALLOW = 3; //-> escape tags as entities
/**
* filter types
*/
const FILTER_POST = 'post';
const FILTER_PRE = 'pre';
const FILTER_OUTPUT = 'output';
const FILTER_VARIABLE = 'variable';
/**
* plugin types
*/
const PLUGIN_FUNCTION = 'function';
const PLUGIN_BLOCK = 'block';
const PLUGIN_COMPILER = 'compiler';
const PLUGIN_MODIFIER = 'modifier';
const PLUGIN_MODIFIERCOMPILER = 'modifiercompiler';
/**
* assigned global tpl vars
*/
public static $global_tpl_vars = array();
/**
* Flag denoting if Multibyte String functions are available
*/
public static $_MBSTRING = SMARTY_MBSTRING;
/**
* The character set to adhere to (e.g. "UTF-8")
*/
public static $_CHARSET = SMARTY_RESOURCE_CHAR_SET;
/**
* The date format to be used internally
* (accepts date() and strftime())
*/
public static $_DATE_FORMAT = SMARTY_RESOURCE_DATE_FORMAT;
/**
* Flag denoting if PCRE should run in UTF-8 mode
*/
public static $_UTF8_MODIFIER = 'u';
/**
* Flag denoting if operating system is windows
*/
public static $_IS_WINDOWS = false;
/**
* auto literal on delimiters with whitespace
*
* @var boolean
*/
public $auto_literal = true;
/**
* display error on not assigned variables
*
* @var boolean
*/
public $error_unassigned = false;
/**
* look up relative file path in include_path
*
* @var boolean
*/
public $use_include_path = false;
/**
* flag if template_dir is normalized
*
* @var bool
*/
public $_templateDirNormalized = false;
/**
* joined template directory string used in cache keys
*
* @var string
*/
public $_joined_template_dir = null;
/**
* flag if config_dir is normalized
*
* @var bool
*/
public $_configDirNormalized = false;
/**
* joined config directory string used in cache keys
*
* @var string
*/
public $_joined_config_dir = null;
/**
* default template handler
*
* @var callable
*/
public $default_template_handler_func = null;
/**
* default config handler
*
* @var callable
*/
public $default_config_handler_func = null;
/**
* default plugin handler
*
* @var callable
*/
public $default_plugin_handler_func = null;
/**
* flag if template_dir is normalized
*
* @var bool
*/
public $_compileDirNormalized = false;
/**
* flag if plugins_dir is normalized
*
* @var bool
*/
public $_pluginsDirNormalized = false;
/**
* flag if template_dir is normalized
*
* @var bool
*/
public $_cacheDirNormalized = false;
/**
* force template compiling?
*
* @var boolean
*/
public $force_compile = false;
/**
* use sub dirs for compiled/cached files?
*
* @var boolean
*/
public $use_sub_dirs = false;
/**
* allow ambiguous resources (that are made unique by the resource handler)
*
* @var boolean
*/
public $allow_ambiguous_resources = false;
/**
* merge compiled includes
*
* @var boolean
*/
public $merge_compiled_includes = false;
/*
* flag for behaviour when extends: resource and {extends} tag are used simultaneous
* if false disable execution of {extends} in templates called by extends resource.
* (behaviour as versions < 3.1.28)
*
* @var boolean
*/
public $extends_recursion = true;
/**
* force cache file creation
*
* @var boolean
*/
public $force_cache = false;
/**
* template left-delimiter
*
* @var string
*/
public $left_delimiter = "{";
/**
* template right-delimiter
*
* @var string
*/
public $right_delimiter = "}";
/**
* array of strings which shall be treated as literal by compiler
*
* @var array string
*/
public $literals = array();
/**
* class name
* This should be instance of Smarty_Security.
*
* @var string
* @see Smarty_Security
*/
public $security_class = 'Smarty_Security';
/**
* implementation of security class
*
* @var Smarty_Security
*/
public $security_policy = null;
/**
* controls handling of PHP-blocks
*
* @var integer
*/
public $php_handling = self::PHP_PASSTHRU;
/**
* controls if the php template file resource is allowed
*
* @var bool
*/
public $allow_php_templates = false;
/**
* debug mode
* Setting this to true enables the debug-console.
*
* @var boolean
*/
public $debugging = false;
/**
* This determines if debugging is enable-able from the browser.
* <ul>
* <li>NONE => no debugging control allowed</li>
* <li>URL => enable debugging when SMARTY_DEBUG is found in the URL.</li>
* </ul>
*
* @var string
*/
public $debugging_ctrl = 'NONE';
/**
* Name of debugging URL-param.
* Only used when $debugging_ctrl is set to 'URL'.
* The name of the URL-parameter that activates debugging.
*
* @var string
*/
public $smarty_debug_id = 'SMARTY_DEBUG';
/**
* Path of debug template.
*
* @var string
*/
public $debug_tpl = null;
/**
* When set, smarty uses this value as error_reporting-level.
*
* @var int
*/
public $error_reporting = null;
/**
* Controls whether variables with the same name overwrite each other.
*
* @var boolean
*/
public $config_overwrite = true;
/**
* Controls whether config values of on/true/yes and off/false/no get converted to boolean.
*
* @var boolean
*/
public $config_booleanize = true;
/**
* Controls whether hidden config sections/vars are read from the file.
*
* @var boolean
*/
public $config_read_hidden = false;
/**
* locking concurrent compiles
*
* @var boolean
*/
public $compile_locking = true;
/**
* Controls whether cache resources should use locking mechanism
*
* @var boolean
*/
public $cache_locking = false;
/**
* seconds to wait for acquiring a lock before ignoring the write lock
*
* @var float
*/
public $locking_timeout = 10;
/**
* resource type used if none given
* Must be an valid key of $registered_resources.
*
* @var string
*/
public $default_resource_type = 'file';
/**
* caching type
* Must be an element of $cache_resource_types.
*
* @var string
*/
public $caching_type = 'file';
/**
* config type
*
* @var string
*/
public $default_config_type = 'file';
/**
* check If-Modified-Since headers
*
* @var boolean
*/
public $cache_modified_check = false;
/**
* registered plugins
*
* @var array
*/
public $registered_plugins = array();
/**
* registered objects
*
* @var array
*/
public $registered_objects = array();
/**
* registered classes
*
* @var array
*/
public $registered_classes = array();
/**
* registered filters
*
* @var array
*/
public $registered_filters = array();
/**
* registered resources
*
* @var array
*/
public $registered_resources = array();
/**
* registered cache resources
*
* @var array
*/
public $registered_cache_resources = array();
/**
* autoload filter
*
* @var array
*/
public $autoload_filters = array();
/**
* default modifier
*
* @var array
*/
public $default_modifiers = array();
/**
* autoescape variable output
*
* @var boolean
*/
public $escape_html = false;
/**
* start time for execution time calculation
*
* @var int
*/
public $start_time = 0;
/**
* required by the compiler for BC
*
* @var string
*/
public $_current_file = null;
/**
* internal flag to enable parser debugging
*
* @var bool
*/
public $_parserdebug = false;
/**
* This object type (Smarty = 1, template = 2, data = 4)
*
* @var int
*/
public $_objType = 1;
/**
* Debug object
*
* @var Smarty_Internal_Debug
*/
public $_debug = null;
/**
* template directory
*
* @var array
*/
protected $template_dir = array('./templates/');
/**
* flags for normalized template directory entries
*
* @var array
*/
protected $_processedTemplateDir = array();
/**
* config directory
*
* @var array
*/
protected $config_dir = array('./configs/');
/**
* flags for normalized template directory entries
*
* @var array
*/
protected $_processedConfigDir = array();
/**
* compile directory
*
* @var string
*/
protected $compile_dir = './templates_c/';
/**
* plugins directory
*
* @var array
*/
protected $plugins_dir = array();
/**
* cache directory
*
* @var string
*/
protected $cache_dir = './cache/';
/**
* removed properties
*
* @var string[]
*/
protected $obsoleteProperties = array('resource_caching', 'template_resource_caching', 'direct_access_security',
'_dir_perms', '_file_perms', 'plugin_search_order',
'inheritance_merge_compiled_includes', 'resource_cache_mode',);
/**
* List of private properties which will call getter/setter on a direct access
*
* @var string[]
*/
protected $accessMap = array('template_dir' => 'TemplateDir', 'config_dir' => 'ConfigDir',
'plugins_dir' => 'PluginsDir', 'compile_dir' => 'CompileDir',
'cache_dir' => 'CacheDir',);
/**
* Initialize new Smarty object
*/
public function __construct()
{
$this->_clearTemplateCache();
parent::__construct();
if (is_callable('mb_internal_encoding')) {
mb_internal_encoding(Smarty::$_CHARSET);
}
$this->start_time = microtime(true);
if (isset($_SERVER[ 'SCRIPT_NAME' ])) {
Smarty::$global_tpl_vars[ 'SCRIPT_NAME' ] = new Smarty_Variable($_SERVER[ 'SCRIPT_NAME' ]);
}
// Check if we're running on windows
Smarty::$_IS_WINDOWS = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN';
// let PCRE (preg_*) treat strings as ISO-8859-1 if we're not dealing with UTF-8
if (Smarty::$_CHARSET !== 'UTF-8') {
Smarty::$_UTF8_MODIFIER = '';
}
}
/**
* Enable error handler to mute expected messages
*
* @return boolean
* @deprecated
*/
public static function muteExpectedErrors()
{
return Smarty_Internal_ErrorHandler::muteExpectedErrors();
}
/**
* Disable error handler muting expected messages
*
* @deprecated
*/
public static function unmuteExpectedErrors()
{
restore_error_handler();
}
/**
* Check if a template resource exists
*
* @param string $resource_name template name
*
* @return bool status
* @throws \SmartyException
*/
public function templateExists($resource_name)
{
// create source object
$source = Smarty_Template_Source::load(null, $this, $resource_name);
return $source->exists;
}
/**
* Loads security class and enables security
*
* @param string|Smarty_Security $security_class if a string is used, it must be class-name
*
* @return Smarty current Smarty instance for chaining
* @throws SmartyException when an invalid class name is provided
*/
public function enableSecurity($security_class = null)
{
Smarty_Security::enableSecurity($this, $security_class);
return $this;
}
/**
* Disable security
*
* @return Smarty current Smarty instance for chaining
*/
public function disableSecurity()
{
$this->security_policy = null;
return $this;
}
/**
* Add template directory(s)
*
* @param string|array $template_dir directory(s) of template sources
* @param string $key of the array element to assign the template dir to
* @param bool $isConfig true for config_dir
*
* @return Smarty current Smarty instance for chaining
*/
public function addTemplateDir($template_dir, $key = null, $isConfig = false)
{
if ($isConfig) {
$processed = &$this->_processedConfigDir;
$dir = &$this->config_dir;
$this->_configDirNormalized = false;
} else {
$processed = &$this->_processedTemplateDir;
$dir = &$this->template_dir;
$this->_templateDirNormalized = false;
}
if (is_array($template_dir)) {
foreach ($template_dir as $k => $v) {
if (is_int($k)) {
// indexes are not merged but appended
$dir[] = $v;
} else {
// string indexes are overridden
$dir[ $k ] = $v;
unset($processed[ $key ]);
}
}
} else {
if ($key !== null) {
// override directory at specified index
$dir[ $key ] = $template_dir;
unset($processed[ $key ]);
} else {
// append new directory
$dir[] = $template_dir;
}
}
return $this;
}
/**
* Get template directories
*
* @param mixed $index index of directory to get, null to get all
* @param bool $isConfig true for config_dir
*
* @return array list of template directories, or directory of $index
*/
public function getTemplateDir($index = null, $isConfig = false)
{
if ($isConfig) {
$dir = &$this->config_dir;
} else {
$dir = &$this->template_dir;
}
if ($isConfig ? !$this->_configDirNormalized : !$this->_templateDirNormalized) {
$this->_normalizeTemplateConfig($isConfig);
}
if ($index !== null) {
return isset($dir[ $index ]) ? $dir[ $index ] : null;
}
return $dir;
}
/**
* Set template directory
*
* @param string|array $template_dir directory(s) of template sources
* @param bool $isConfig true for config_dir
*
* @return \Smarty current Smarty instance for chaining
*/
public function setTemplateDir($template_dir, $isConfig = false)
{
if ($isConfig) {
$this->config_dir = array();
$this->_processedConfigDir = array();
} else {
$this->template_dir = array();
$this->_processedTemplateDir = array();
}
$this->addTemplateDir($template_dir, null, $isConfig);
return $this;
}
/**
* Add config directory(s)
*
* @param string|array $config_dir directory(s) of config sources
* @param mixed $key key of the array element to assign the config dir to
*
* @return Smarty current Smarty instance for chaining
*/
public function addConfigDir($config_dir, $key = null)
{
return $this->addTemplateDir($config_dir, $key, true);
}
/**
* Get config directory
*
* @param mixed $index index of directory to get, null to get all
*
* @return array configuration directory
*/
public function getConfigDir($index = null)
{
return $this->getTemplateDir($index, true);
}
/**
* Set config directory
*
* @param $config_dir
*
* @return Smarty current Smarty instance for chaining
*/
public function setConfigDir($config_dir)
{
return $this->setTemplateDir($config_dir, true);
}
/**
* Adds directory of plugin files
*
* @param null|array|string $plugins_dir
*
* @return Smarty current Smarty instance for chaining
*/
public function addPluginsDir($plugins_dir)
{
if (empty($this->plugins_dir)) {
$this->plugins_dir[] = SMARTY_PLUGINS_DIR;
}
$this->plugins_dir = array_merge($this->plugins_dir, (array)$plugins_dir);
$this->_pluginsDirNormalized = false;
return $this;
}
/**
* Get plugin directories
*
* @return array list of plugin directories
*/
public function getPluginsDir()
{
if (empty($this->plugins_dir)) {
$this->plugins_dir[] = SMARTY_PLUGINS_DIR;
$this->_pluginsDirNormalized = false;
}
if (!$this->_pluginsDirNormalized) {
if (!is_array($this->plugins_dir)) {
$this->plugins_dir = (array)$this->plugins_dir;
}
foreach ($this->plugins_dir as $k => $v) {
$this->plugins_dir[ $k ] = $this->_realpath(rtrim($v, "/\\") . DIRECTORY_SEPARATOR, true);
}
$this->_cache[ 'plugin_files' ] = array();
$this->_pluginsDirNormalized = true;
}
return $this->plugins_dir;
}
/**
* Set plugins directory
*
* @param string|array $plugins_dir directory(s) of plugins
*
* @return Smarty current Smarty instance for chaining
*/
public function setPluginsDir($plugins_dir)
{
$this->plugins_dir = (array)$plugins_dir;
$this->_pluginsDirNormalized = false;
return $this;
}
/**
* Get compiled directory
*
* @return string path to compiled templates
*/
public function getCompileDir()
{
if (!$this->_compileDirNormalized) {
$this->_normalizeDir('compile_dir', $this->compile_dir);
$this->_compileDirNormalized = true;
}
return $this->compile_dir;
}
/**
*
* @param string $compile_dir directory to store compiled templates in
*
* @return Smarty current Smarty instance for chaining
*/
public function setCompileDir($compile_dir)
{
$this->_normalizeDir('compile_dir', $compile_dir);
$this->_compileDirNormalized = true;
return $this;
}
/**
* Get cache directory
*
* @return string path of cache directory
*/
public function getCacheDir()
{
if (!$this->_cacheDirNormalized) {
$this->_normalizeDir('cache_dir', $this->cache_dir);
$this->_cacheDirNormalized = true;
}
return $this->cache_dir;
}
/**
* Set cache directory
*
* @param string $cache_dir directory to store cached templates in
*
* @return Smarty current Smarty instance for chaining
*/
public function setCacheDir($cache_dir)
{
$this->_normalizeDir('cache_dir', $cache_dir);
$this->_cacheDirNormalized = true;
return $this;
}
/**
* creates a template object
*
* @param string $template the resource handle of the template file
* @param mixed $cache_id cache id to be used with this template
* @param mixed $compile_id compile id to be used with this template
* @param object $parent next higher level of Smarty variables
* @param boolean $do_clone flag is Smarty object shall be cloned
*
* @return \Smarty_Internal_Template template object
* @throws \SmartyException
*/
public function createTemplate($template, $cache_id = null, $compile_id = null, $parent = null, $do_clone = true)
{
if ($cache_id !== null && (is_object($cache_id) || is_array($cache_id))) {
$parent = $cache_id;
$cache_id = null;
}
if ($parent !== null && is_array($parent)) {
$data = $parent;
$parent = null;
} else {
$data = null;
}
if (!$this->_templateDirNormalized) {
$this->_normalizeTemplateConfig(false);
}
$_templateId = $this->_getTemplateId($template, $cache_id, $compile_id);
$tpl = null;
if ($this->caching && isset(Smarty_Internal_Template::$isCacheTplObj[ $_templateId ])) {
$tpl = $do_clone ? clone Smarty_Internal_Template::$isCacheTplObj[ $_templateId ] :
Smarty_Internal_Template::$isCacheTplObj[ $_templateId ];
$tpl->inheritance = null;
$tpl->tpl_vars = $tpl->config_vars = array();
} else if (!$do_clone && isset(Smarty_Internal_Template::$tplObjCache[ $_templateId ])) {
$tpl = clone Smarty_Internal_Template::$tplObjCache[ $_templateId ];
$tpl->inheritance = null;
$tpl->tpl_vars = $tpl->config_vars = array();
} else {
/* @var Smarty_Internal_Template $tpl */
$tpl = new $this->template_class($template, $this, null, $cache_id, $compile_id, null, null);
$tpl->templateId = $_templateId;
}
if ($do_clone) {
$tpl->smarty = clone $tpl->smarty;
}
$tpl->parent = $parent ? $parent : $this;
// fill data if present
if (!empty($data) && is_array($data)) {
// set up variable values
foreach ($data as $_key => $_val) {
$tpl->tpl_vars[ $_key ] = new Smarty_Variable($_val);
}
}
if ($this->debugging || $this->debugging_ctrl === 'URL') {
$tpl->smarty->_debug = new Smarty_Internal_Debug();
// check URL debugging control
if (!$this->debugging && $this->debugging_ctrl === 'URL') {
$tpl->smarty->_debug->debugUrl($tpl->smarty);
}
}
return $tpl;
}
/**
* Takes unknown classes and loads plugin files for them
* class name format: Smarty_PluginType_PluginName
* plugin filename format: plugintype.pluginname.php
*
* @param string $plugin_name class plugin name to load
* @param bool $check check if already loaded
*
* @throws SmartyException
* @return string |boolean filepath of loaded file or false
*/
public function loadPlugin($plugin_name, $check = true)
{
return $this->ext->loadPlugin->loadPlugin($this, $plugin_name, $check);
}
/**
* Get unique template id
*
* @param string $template_name
* @param null|mixed $cache_id
* @param null|mixed $compile_id
* @param null $caching
* @param \Smarty_Internal_Template $template
*
* @return string
* @throws \SmartyException
*/
public function _getTemplateId($template_name,
$cache_id = null,
$compile_id = null,
$caching = null,
Smarty_Internal_Template $template = null)
{
$template_name = (strpos($template_name, ':') === false) ? "{$this->default_resource_type}:{$template_name}" :
$template_name;
$cache_id = $cache_id === null ? $this->cache_id : $cache_id;
$compile_id = $compile_id === null ? $this->compile_id : $compile_id;
$caching = (int)($caching === null ? $this->caching : $caching);
if ((isset($template) && strpos($template_name, ':.') !== false) || $this->allow_ambiguous_resources) {
$_templateId =
Smarty_Resource::getUniqueTemplateName((isset($template) ? $template : $this), $template_name) .
"#{$cache_id}#{$compile_id}#{$caching}";
} else {
$_templateId = $this->_joined_template_dir . "#{$template_name}#{$cache_id}#{$compile_id}#{$caching}";
}
if (isset($_templateId[ 150 ])) {
$_templateId = sha1($_templateId);
}
return $_templateId;
}
/**
* Normalize path
* - remove /./ and /../
* - make it absolute if required
*
* @param string $path file path
* @param bool $realpath if true - convert to absolute
* false - convert to relative
* null - keep as it is but remove /./ /../
*
* @return string
*/
public function _realpath($path, $realpath = null)
{
$nds = DIRECTORY_SEPARATOR === '/' ? '\\' : '/';
// normalize DIRECTORY_SEPARATOR
$path = str_replace($nds, DIRECTORY_SEPARATOR, $path);
preg_match('%^(?<root>(?:[[:alpha:]]:[\\\\]|/|[\\\\]{2}[[:alpha:]]+|[[:print:]]{2,}:[/]{2}|[\\\\])?)(?<path>(.*))$%u',
$path,
$parts);
$path = $parts[ 'path' ];
if ($parts[ 'root' ] === '\\') {
$parts[ 'root' ] = substr(getcwd(), 0, 2) . $parts[ 'root' ];
} else {
if ($realpath !== null && !$parts[ 'root' ]) {
$path = getcwd() . DIRECTORY_SEPARATOR . $path;
}
}
// remove noop 'DIRECTORY_SEPARATOR DIRECTORY_SEPARATOR' and 'DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR' patterns
$path = preg_replace('#([\\\\/]([.]?[\\\\/])+)#u', DIRECTORY_SEPARATOR, $path);
// resolve '..DIRECTORY_SEPARATOR' pattern, smallest first
if (strpos($path, '..' . DIRECTORY_SEPARATOR) !== false &&
preg_match_all('#(([.]?[\\\\/])*([.][.])[\\\\/]([.]?[\\\\/])*)+#u', $path, $match)
) {
$counts = array();
foreach ($match[ 0 ] as $m) {
$counts[] = (int)((strlen($m) - 1) / 3);
}
sort($counts);
foreach ($counts as $count) {
$path = preg_replace('#(([\\\\/]([.]?[\\\\/])*[^\\\\/.]+){' . $count .
'}[\\\\/]([.]?[\\\\/])*([.][.][\\\\/]([.]?[\\\\/])*){' . $count . '})(?=[^.])#u',
DIRECTORY_SEPARATOR,
$path);
}
}
return $parts[ 'root' ] . $path;
}
/**
* Empty template objects cache
*/
public function _clearTemplateCache()
{
Smarty_Internal_Template::$isCacheTplObj = array();
Smarty_Internal_Template::$tplObjCache = array();
}
/**
* @param boolean $use_sub_dirs
*/
public function setUseSubDirs($use_sub_dirs)
{
$this->use_sub_dirs = $use_sub_dirs;
}
/**
* @param int $error_reporting
*/
public function setErrorReporting($error_reporting)
{
$this->error_reporting = $error_reporting;
}
/**
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | true |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/SmartyBC.class.php | Extend/Package/smarty/SmartyBC.class.php | <?php
/**
* Project: Smarty: the PHP compiling template engine
* File: SmartyBC.class.php
* SVN: $Id: $
* 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
* For questions, help, comments, discussion, etc., please join the
* Smarty mailing list. Send a blank e-mail to
* smarty-discussion-subscribe@googlegroups.com
*
* @link http://www.smarty.net/
* @copyright 2008 New Digital Group, Inc.
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
* @author Rodney Rehm
* @package Smarty
*/
/**
* @ignore
*/
require_once(dirname(__FILE__) . '/Smarty.class.php');
/**
* Smarty Backward Compatibility Wrapper Class
*
* @package Smarty
*/
class SmartyBC extends Smarty
{
/**
* Smarty 2 BC
*
* @var string
*/
public $_version = self::SMARTY_VERSION;
/**
* This is an array of directories where trusted php scripts reside.
*
* @var array
*/
public $trusted_dir = array();
/**
* Initialize new SmartyBC object
*
*/
public function __construct()
{
parent::__construct();
}
/**
* wrapper for assign_by_ref
*
* @param string $tpl_var the template variable name
* @param mixed &$value the referenced value to assign
*/
public function assign_by_ref($tpl_var, &$value)
{
$this->assignByRef($tpl_var, $value);
}
/**
* wrapper for append_by_ref
*
* @param string $tpl_var the template variable name
* @param mixed &$value the referenced value to append
* @param boolean $merge flag if array elements shall be merged
*/
public function append_by_ref($tpl_var, &$value, $merge = false)
{
$this->appendByRef($tpl_var, $value, $merge);
}
/**
* clear the given assigned template variable.
*
* @param string $tpl_var the template variable to clear
*/
public function clear_assign($tpl_var)
{
$this->clearAssign($tpl_var);
}
/**
* Registers custom function to be used in templates
*
* @param string $function the name of the template function
* @param string $function_impl the name of the PHP function to register
* @param bool $cacheable
* @param mixed $cache_attrs
*
* @throws \SmartyException
*/
public function register_function($function, $function_impl, $cacheable = true, $cache_attrs = null)
{
$this->registerPlugin('function', $function, $function_impl, $cacheable, $cache_attrs);
}
/**
* Unregister custom function
*
* @param string $function name of template function
*/
public function unregister_function($function)
{
$this->unregisterPlugin('function', $function);
}
/**
* Registers object to be used in templates
*
* @param string $object name of template object
* @param object $object_impl the referenced PHP object to register
* @param array $allowed list of allowed methods (empty = all)
* @param boolean $smarty_args smarty argument format, else traditional
* @param array $block_methods list of methods that are block format
*
* @throws SmartyException
* @internal param array $block_functs list of methods that are block format
*/
public function register_object($object, $object_impl, $allowed = array(), $smarty_args = true,
$block_methods = array())
{
settype($allowed, 'array');
settype($smarty_args, 'boolean');
$this->registerObject($object, $object_impl, $allowed, $smarty_args, $block_methods);
}
/**
* Unregister object
*
* @param string $object name of template object
*/
public function unregister_object($object)
{
$this->unregisterObject($object);
}
/**
* Registers block function to be used in templates
*
* @param string $block name of template block
* @param string $block_impl PHP function to register
* @param bool $cacheable
* @param mixed $cache_attrs
*
* @throws \SmartyException
*/
public function register_block($block, $block_impl, $cacheable = true, $cache_attrs = null)
{
$this->registerPlugin('block', $block, $block_impl, $cacheable, $cache_attrs);
}
/**
* Unregister block function
*
* @param string $block name of template function
*/
public function unregister_block($block)
{
$this->unregisterPlugin('block', $block);
}
/**
* Registers compiler function
*
* @param string $function name of template function
* @param string $function_impl name of PHP function to register
* @param bool $cacheable
*
* @throws \SmartyException
*/
public function register_compiler_function($function, $function_impl, $cacheable = true)
{
$this->registerPlugin('compiler', $function, $function_impl, $cacheable);
}
/**
* Unregister compiler function
*
* @param string $function name of template function
*/
public function unregister_compiler_function($function)
{
$this->unregisterPlugin('compiler', $function);
}
/**
* Registers modifier to be used in templates
*
* @param string $modifier name of template modifier
* @param string $modifier_impl name of PHP function to register
*
* @throws \SmartyException
*/
public function register_modifier($modifier, $modifier_impl)
{
$this->registerPlugin('modifier', $modifier, $modifier_impl);
}
/**
* Unregister modifier
*
* @param string $modifier name of template modifier
*/
public function unregister_modifier($modifier)
{
$this->unregisterPlugin('modifier', $modifier);
}
/**
* Registers a resource to fetch a template
*
* @param string $type name of resource
* @param array $functions array of functions to handle resource
*/
public function register_resource($type, $functions)
{
$this->registerResource($type, $functions);
}
/**
* Unregister a resource
*
* @param string $type name of resource
*/
public function unregister_resource($type)
{
$this->unregisterResource($type);
}
/**
* Registers a prefilter function to apply
* to a template before compiling
*
* @param callable $function
*
* @throws \SmartyException
*/
public function register_prefilter($function)
{
$this->registerFilter('pre', $function);
}
/**
* Unregister a prefilter function
*
* @param callable $function
*/
public function unregister_prefilter($function)
{
$this->unregisterFilter('pre', $function);
}
/**
* Registers a postfilter function to apply
* to a compiled template after compilation
*
* @param callable $function
*
* @throws \SmartyException
*/
public function register_postfilter($function)
{
$this->registerFilter('post', $function);
}
/**
* Unregister a postfilter function
*
* @param callable $function
*/
public function unregister_postfilter($function)
{
$this->unregisterFilter('post', $function);
}
/**
* Registers an output filter function to apply
* to a template output
*
* @param callable $function
*
* @throws \SmartyException
*/
public function register_outputfilter($function)
{
$this->registerFilter('output', $function);
}
/**
* Unregister an outputfilter function
*
* @param callable $function
*/
public function unregister_outputfilter($function)
{
$this->unregisterFilter('output', $function);
}
/**
* load a filter of specified type and name
*
* @param string $type filter type
* @param string $name filter name
*
* @throws \SmartyException
*/
public function load_filter($type, $name)
{
$this->loadFilter($type, $name);
}
/**
* clear cached content for the given template and cache id
*
* @param string $tpl_file name of template file
* @param string $cache_id name of cache_id
* @param string $compile_id name of compile_id
* @param string $exp_time expiration time
*
* @return boolean
*/
public function clear_cache($tpl_file = null, $cache_id = null, $compile_id = null, $exp_time = null)
{
return $this->clearCache($tpl_file, $cache_id, $compile_id, $exp_time);
}
/**
* clear the entire contents of cache (all templates)
*
* @param string $exp_time expire time
*
* @return boolean
*/
public function clear_all_cache($exp_time = null)
{
return $this->clearCache(null, null, null, $exp_time);
}
/**
* test to see if valid cache exists for this template
*
* @param string $tpl_file name of template file
* @param string $cache_id
* @param string $compile_id
*
* @return bool
* @throws \Exception
* @throws \SmartyException
*/
public function is_cached($tpl_file, $cache_id = null, $compile_id = null)
{
return $this->isCached($tpl_file, $cache_id, $compile_id);
}
/**
* clear all the assigned template variables.
*/
public function clear_all_assign()
{
$this->clearAllAssign();
}
/**
* clears compiled version of specified template resource,
* or all compiled template files if one is not specified.
* This function is for advanced use only, not normally needed.
*
* @param string $tpl_file
* @param string $compile_id
* @param string $exp_time
*
* @return boolean results of {@link smarty_core_rm_auto()}
*/
public function clear_compiled_tpl($tpl_file = null, $compile_id = null, $exp_time = null)
{
return $this->clearCompiledTemplate($tpl_file, $compile_id, $exp_time);
}
/**
* Checks whether requested template exists.
*
* @param string $tpl_file
*
* @return bool
* @throws \SmartyException
*/
public function template_exists($tpl_file)
{
return $this->templateExists($tpl_file);
}
/**
* Returns an array containing template variables
*
* @param string $name
*
* @return array
*/
public function get_template_vars($name = null)
{
return $this->getTemplateVars($name);
}
/**
* Returns an array containing config variables
*
* @param string $name
*
* @return array
*/
public function get_config_vars($name = null)
{
return $this->getConfigVars($name);
}
/**
* load configuration values
*
* @param string $file
* @param string $section
* @param string $scope
*/
public function config_load($file, $section = null, $scope = 'global')
{
$this->ConfigLoad($file, $section, $scope);
}
/**
* return a reference to a registered object
*
* @param string $name
*
* @return object
*/
public function get_registered_object($name)
{
return $this->getRegisteredObject($name);
}
/**
* clear configuration values
*
* @param string $var
*/
public function clear_config($var = null)
{
$this->clearConfig($var);
}
/**
* trigger Smarty error
*
* @param string $error_msg
* @param integer $error_type
*/
public function trigger_error($error_msg, $error_type = E_USER_WARNING)
{
trigger_error("Smarty error: $error_msg", $error_type);
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/Autoloader.php | Extend/Package/smarty/Autoloader.php | <?php
/**
* Smarty Autoloader
*
* @package Smarty
*/
/**
* Smarty Autoloader
*
* @package Smarty
* @author Uwe Tews
* Usage:
* require_once '...path/Autoloader.php';
* Smarty_Autoloader::register();
* or
* include '...path/bootstrap.php';
*
* $smarty = new Smarty();
*/
class Smarty_Autoloader
{
/**
* Filepath to Smarty root
*
* @var string
*/
public static $SMARTY_DIR = null;
/**
* Filepath to Smarty internal plugins
*
* @var string
*/
public static $SMARTY_SYSPLUGINS_DIR = null;
/**
* Array with Smarty core classes and their filename
*
* @var array
*/
public static $rootClasses = array('smarty' => 'Smarty.class.php', 'smartybc' => 'SmartyBC.class.php',);
/**
* Registers Smarty_Autoloader backward compatible to older installations.
*
* @param bool $prepend Whether to prepend the autoloader or not.
*/
public static function registerBC($prepend = false)
{
/**
* register the class autoloader
*/
if (!defined('SMARTY_SPL_AUTOLOAD')) {
define('SMARTY_SPL_AUTOLOAD', 0);
}
if (SMARTY_SPL_AUTOLOAD &&
set_include_path(get_include_path() . PATH_SEPARATOR . SMARTY_SYSPLUGINS_DIR) !== false
) {
$registeredAutoLoadFunctions = spl_autoload_functions();
if (!isset($registeredAutoLoadFunctions[ 'spl_autoload' ])) {
spl_autoload_register();
}
} else {
self::register($prepend);
}
}
/**
* Registers Smarty_Autoloader as an SPL autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not.
*/
public static function register($prepend = false)
{
self::$SMARTY_DIR = defined('SMARTY_DIR') ? SMARTY_DIR : dirname(__FILE__) . DIRECTORY_SEPARATOR;
self::$SMARTY_SYSPLUGINS_DIR = defined('SMARTY_SYSPLUGINS_DIR') ? SMARTY_SYSPLUGINS_DIR :
self::$SMARTY_DIR . 'sysplugins' . DIRECTORY_SEPARATOR;
if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
spl_autoload_register(array(__CLASS__, 'autoload'), true, $prepend);
} else {
spl_autoload_register(array(__CLASS__, 'autoload'));
}
}
/**
* Handles auto loading of classes.
*
* @param string $class A class name.
*/
public static function autoload($class)
{
if ($class[ 0 ] !== 'S' && strpos($class, 'Smarty') !== 0) {
return;
}
$_class = strtolower($class);
if (isset(self::$rootClasses[ $_class ])) {
$file = self::$SMARTY_DIR . self::$rootClasses[ $_class ];
if (is_file($file)) {
include $file;
}
} else {
$file = self::$SMARTY_SYSPLUGINS_DIR . $_class . '.php';
if (is_file($file)) {
include $file;
}
}
return;
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/bootstrap.php | Extend/Package/smarty/bootstrap.php | <?php
if (!class_exists('Smarty_Autoloader')) {
require dirname(__FILE__) . '/Autoloader.php';
}
Smarty_Autoloader::register(true);
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.counter.php | Extend/Package/smarty/plugins/function.counter.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {counter} function plugin
* Type: function
* Name: counter
* Purpose: print out a counter value
*
* @author Monte Ohrt <monte at ohrt dot com>
* @link http://www.smarty.net/manual/en/language.function.counter.php {counter}
* (Smarty online manual)
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string|null
*/
function smarty_function_counter($params, $template)
{
static $counters = array();
$name = (isset($params[ 'name' ])) ? $params[ 'name' ] : 'default';
if (!isset($counters[ $name ])) {
$counters[ $name ] = array('start' => 1, 'skip' => 1, 'direction' => 'up', 'count' => 1);
}
$counter =& $counters[ $name ];
if (isset($params[ 'start' ])) {
$counter[ 'start' ] = $counter[ 'count' ] = (int) $params[ 'start' ];
}
if (!empty($params[ 'assign' ])) {
$counter[ 'assign' ] = $params[ 'assign' ];
}
if (isset($counter[ 'assign' ])) {
$template->assign($counter[ 'assign' ], $counter[ 'count' ]);
}
if (isset($params[ 'print' ])) {
$print = (bool) $params[ 'print' ];
} else {
$print = empty($counter[ 'assign' ]);
}
if ($print) {
$retval = $counter[ 'count' ];
} else {
$retval = null;
}
if (isset($params[ 'skip' ])) {
$counter[ 'skip' ] = $params[ 'skip' ];
}
if (isset($params[ 'direction' ])) {
$counter[ 'direction' ] = $params[ 'direction' ];
}
if ($counter[ 'direction' ] === 'down') {
$counter[ 'count' ] -= $counter[ 'skip' ];
} else {
$counter[ 'count' ] += $counter[ 'skip' ];
}
return $retval;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.html_image.php | Extend/Package/smarty/plugins/function.html_image.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_image} function plugin
* Type: function
* Name: html_image
* Date: Feb 24, 2003
* Purpose: format HTML tags for the image
* Examples: {html_image file="/images/masthead.gif"}
* Output: <img src="/images/masthead.gif" width=400 height=23>
* Params:
*
* - file - (required) - file (and path) of image
* - height - (optional) - image height (default actual height)
* - width - (optional) - image width (default actual width)
* - basedir - (optional) - base directory for absolute paths, default is environment variable DOCUMENT_ROOT
* - path_prefix - prefix for path output (optional, default empty)
*
*
* @link http://www.smarty.net/manual/en/language.function.html.image.php {html_image}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author credits to Duda <duda@big.hu>
* @version 1.0
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @throws SmartyException
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_image($params, $template)
{
if (!isset($template->smarty->_cache[ '_required_sesc' ])) {
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
$template->smarty->_cache[ '_required_sesc' ] = true;
}
$alt = '';
$file = '';
$height = '';
$width = '';
$extra = '';
$prefix = '';
$suffix = '';
$path_prefix = '';
$basedir = isset($_SERVER[ 'DOCUMENT_ROOT' ]) ? $_SERVER[ 'DOCUMENT_ROOT' ] : '';
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'file':
case 'height':
case 'width':
case 'dpi':
case 'path_prefix':
case 'basedir':
$$_key = $_val;
break;
case 'alt':
if (!is_array($_val)) {
$$_key = smarty_function_escape_special_chars($_val);
} else {
throw new SmartyException ("html_image: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE);
}
break;
case 'link':
case 'href':
$prefix = '<a href="' . $_val . '">';
$suffix = '</a>';
break;
default:
if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
} else {
throw new SmartyException ("html_image: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (empty($file)) {
trigger_error('html_image: missing \'file\' parameter', E_USER_NOTICE);
return;
}
if ($file[ 0 ] === '/') {
$_image_path = $basedir . $file;
} else {
$_image_path = $file;
}
// strip file protocol
if (stripos($params[ 'file' ], 'file://') === 0) {
$params[ 'file' ] = substr($params[ 'file' ], 7);
}
$protocol = strpos($params[ 'file' ], '://');
if ($protocol !== false) {
$protocol = strtolower(substr($params[ 'file' ], 0, $protocol));
}
if (isset($template->smarty->security_policy)) {
if ($protocol) {
// remote resource (or php stream, …)
if (!$template->smarty->security_policy->isTrustedUri($params[ 'file' ])) {
return;
}
} else {
// local file
if (!$template->smarty->security_policy->isTrustedResourceDir($_image_path)) {
return;
}
}
}
if (!isset($params[ 'width' ]) || !isset($params[ 'height' ])) {
// FIXME: (rodneyrehm) getimagesize() loads the complete file off a remote resource, use custom [jpg,png,gif]header reader!
if (!$_image_data = @getimagesize($_image_path)) {
if (!file_exists($_image_path)) {
trigger_error("html_image: unable to find '{$_image_path}'", E_USER_NOTICE);
return;
} elseif (!is_readable($_image_path)) {
trigger_error("html_image: unable to read '{$_image_path}'", E_USER_NOTICE);
return;
} else {
trigger_error("html_image: '{$_image_path}' is not a valid image file", E_USER_NOTICE);
return;
}
}
if (!isset($params[ 'width' ])) {
$width = $_image_data[ 0 ];
}
if (!isset($params[ 'height' ])) {
$height = $_image_data[ 1 ];
}
}
if (isset($params[ 'dpi' ])) {
if (strstr($_SERVER[ 'HTTP_USER_AGENT' ], 'Mac')) {
// FIXME: (rodneyrehm) wrong dpi assumption
// don't know who thought this up… even if it was true in 1998, it's definitely wrong in 2011.
$dpi_default = 72;
} else {
$dpi_default = 96;
}
$_resize = $dpi_default / $params[ 'dpi' ];
$width = round($width * $_resize);
$height = round($height * $_resize);
}
return $prefix . '<img src="' . $path_prefix . $file . '" alt="' . $alt . '" width="' . $width . '" height="' .
$height . '"' . $extra . ' />' . $suffix;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.count_characters.php | Extend/Package/smarty/plugins/modifiercompiler.count_characters.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty count_characters modifier plugin
* Type: modifier
* Name: count_characters
* Purpose: count the number of characters in a text
*
* @link http://www.smarty.net/manual/en/language.modifier.count.characters.php count_characters (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_characters($params)
{
if (!isset($params[ 1 ]) || $params[ 1 ] !== 'true') {
return 'preg_match_all(\'/[^\s]/' . Smarty::$_UTF8_MODIFIER . '\',' . $params[ 0 ] . ', $tmp)';
}
if (Smarty::$_MBSTRING) {
return 'mb_strlen(' . $params[ 0 ] . ', \'' . addslashes(Smarty::$_CHARSET) . '\')';
}
// no MBString fallback
return 'strlen(' . $params[ 0 ] . ')';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifier.escape.php | Extend/Package/smarty/plugins/modifier.escape.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty escape modifier plugin
* Type: modifier
* Name: escape
* Purpose: escape string for output
*
* @link http://www.smarty.net/docs/en/language.modifier.escape
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param string $esc_type escape type
* @param string $char_set character set, used for htmlspecialchars() or htmlentities()
* @param boolean $double_encode encode already encoded entitites again, used for htmlspecialchars() or htmlentities()
*
* @return string escaped input string
*/
function smarty_modifier_escape($string, $esc_type = 'html', $char_set = null, $double_encode = true)
{
static $_double_encode = null;
static $is_loaded1 = false;
if ($_double_encode === null) {
$_double_encode = version_compare(PHP_VERSION, '5.2.3', '>=');
}
if (!$char_set) {
$char_set = Smarty::$_CHARSET;
}
switch ($esc_type) {
case 'html':
if ($_double_encode) {
// php >=5.3.2 - go native
return htmlspecialchars($string, ENT_QUOTES, $char_set, $double_encode);
} else {
if ($double_encode) {
// php <5.2.3 - only handle double encoding
return htmlspecialchars($string, ENT_QUOTES, $char_set);
} else {
// php <5.2.3 - prevent double encoding
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
$string = str_replace(array('%%%SMARTY_START%%%',
'%%%SMARTY_END%%%'), array('&',
';'), $string);
return $string;
}
}
case 'htmlall':
if (Smarty::$_MBSTRING) {
// mb_convert_encoding ignores htmlspecialchars()
if ($_double_encode) {
// php >=5.3.2 - go native
$string = htmlspecialchars($string, ENT_QUOTES, $char_set, $double_encode);
} else {
if ($double_encode) {
// php <5.2.3 - only handle double encoding
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
} else {
// php <5.2.3 - prevent double encoding
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string, ENT_QUOTES, $char_set);
$string =
str_replace(array('%%%SMARTY_START%%%',
'%%%SMARTY_END%%%'), array('&',
';'), $string);
return $string;
}
}
// htmlentities() won't convert everything, so use mb_convert_encoding
return mb_convert_encoding($string, 'HTML-ENTITIES', $char_set);
}
// no MBString fallback
if ($_double_encode) {
return htmlentities($string, ENT_QUOTES, $char_set, $double_encode);
} else {
if ($double_encode) {
return htmlentities($string, ENT_QUOTES, $char_set);
} else {
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlentities($string, ENT_QUOTES, $char_set);
$string = str_replace(array('%%%SMARTY_START%%%',
'%%%SMARTY_END%%%'), array('&',
';'), $string);
return $string;
}
}
case 'url':
return rawurlencode($string);
case 'urlpathinfo':
return str_replace('%2F', '/', rawurlencode($string));
case 'quotes':
// escape unescaped single quotes
return preg_replace("%(?<!\\\\)'%", "\\'", $string);
case 'hex':
// escape every byte into hex
// Note that the UTF-8 encoded character ä will be represented as %c3%a4
$return = '';
$_length = strlen($string);
for ($x = 0; $x < $_length; $x ++) {
$return .= '%' . bin2hex($string[ $x ]);
}
return $return;
case 'hexentity':
$return = '';
if (Smarty::$_MBSTRING) {
if (!$is_loaded1) {
if (!is_callable('smarty_mb_to_unicode')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php');
$is_loaded1 = true;
}
}
$return = '';
foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) {
$return .= '&#x' . strtoupper(dechex($unicode)) . ';';
}
return $return;
}
// no MBString fallback
$_length = strlen($string);
for ($x = 0; $x < $_length; $x ++) {
$return .= '&#x' . bin2hex($string[ $x ]) . ';';
}
return $return;
case 'decentity':
$return = '';
if (Smarty::$_MBSTRING) {
if (!$is_loaded1) {
if (!is_callable('smarty_mb_to_unicode')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php');
}
$is_loaded1 = true;
}
$return = '';
foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) {
$return .= '&#' . $unicode . ';';
}
return $return;
}
// no MBString fallback
$_length = strlen($string);
for ($x = 0; $x < $_length; $x ++) {
$return .= '&#' . ord($string[ $x ]) . ';';
}
return $return;
case 'javascript':
// escape quotes and backslashes, newlines, etc.
return strtr($string, array('\\' => '\\\\',
"'" => "\\'",
'"' => '\\"',
"\r" => '\\r',
"\n" => '\\n',
'</' => '<\/'));
case 'mail':
if (Smarty::$_MBSTRING) {
if (!is_callable('smarty_mb_str_replace')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php');
}
return smarty_mb_str_replace(array('@',
'.'), array(' [AT] ',
' [DOT] '), $string);
}
// no MBString fallback
return str_replace(array('@',
'.'), array(' [AT] ',
' [DOT] '), $string);
case 'nonstd':
// escape non-standard chars, such as ms document quotes
$return = '';
if (Smarty::$_MBSTRING) {
if (!$is_loaded1) {
if (!is_callable('smarty_mb_to_unicode')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_unicode.php');
}
$is_loaded1 = true;
}
foreach (smarty_mb_to_unicode($string, Smarty::$_CHARSET) as $unicode) {
if ($unicode >= 126) {
$return .= '&#' . $unicode . ';';
} else {
$return .= chr($unicode);
}
}
return $return;
}
$_length = strlen($string);
for ($_i = 0; $_i < $_length; $_i ++) {
$_ord = ord(substr($string, $_i, 1));
// non-standard char, escape it
if ($_ord >= 126) {
$return .= '&#' . $_ord . ';';
} else {
$return .= substr($string, $_i, 1);
}
}
return $return;
default:
return $string;
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.html_radios.php | Extend/Package/smarty/plugins/function.html_radios.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_radios} function plugin
* File: function.html_radios.php
* Type: function
* Name: html_radios
* Date: 24.Feb.2003
* Purpose: Prints out a list of radio input types
* Params:
*
* - name (optional) - string default "radio"
* - values (required) - array
* - options (required) - associative array
* - checked (optional) - array default not set
* - separator (optional) - ie <br> or
* - output (optional) - the output next to each radio button
* - assign (optional) - assign the output as an array to this variable
* - escape (optional) - escape the content (not value), defaults to true
*
* Examples:
*
* {html_radios values=$ids output=$names}
* {html_radios values=$ids name='box' separator='<br>' output=$names}
* {html_radios values=$ids checked=$checked separator='<br>' output=$names}
*
*
* @link http://smarty.php.net/manual/en/language.function.html.radios.php {html_radios}
* (Smarty online manual)
* @author Christopher Kvarme <christopher.kvarme@flashjab.com>
* @author credits to Monte Ohrt <monte at ohrt dot com>
* @version 1.0
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_radios($params, $template)
{
if (!isset($template->smarty->_cache[ '_required_sesc' ])) {
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
$template->smarty->_cache[ '_required_sesc' ] = true;
}
$name = 'radio';
$values = null;
$options = null;
$selected = null;
$separator = '';
$escape = true;
$labels = true;
$label_ids = false;
$output = null;
$extra = '';
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'name':
case 'separator':
$$_key = (string) $_val;
break;
case 'checked':
case 'selected':
if (is_array($_val)) {
trigger_error('html_radios: the "' . $_key . '" attribute cannot be an array', E_USER_WARNING);
} elseif (is_object($_val)) {
if (method_exists($_val, '__toString')) {
$selected = smarty_function_escape_special_chars((string) $_val->__toString());
} else {
trigger_error('html_radios: selected attribute is an object of class \'' . get_class($_val) .
'\' without __toString() method', E_USER_NOTICE);
}
} else {
$selected = (string) $_val;
}
break;
case 'escape':
case 'labels':
case 'label_ids':
$$_key = (bool) $_val;
break;
case 'options':
$$_key = (array) $_val;
break;
case 'values':
case 'output':
$$_key = array_values((array) $_val);
break;
case 'radios':
trigger_error('html_radios: the use of the "radios" attribute is deprecated, use "options" instead',
E_USER_WARNING);
$options = (array) $_val;
break;
case 'assign':
break;
case 'strict':
break;
case 'disabled':
case 'readonly':
if (!empty($params[ 'strict' ])) {
if (!is_scalar($_val)) {
trigger_error("html_options: {$_key} attribute must be a scalar, only boolean true or string '$_key' will actually add the attribute",
E_USER_NOTICE);
}
if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
}
break;
}
// omit break; to fall through!
default:
if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
} else {
trigger_error("html_radios: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (!isset($options) && !isset($values)) {
/* raise error here? */
return '';
}
$_html_result = array();
if (isset($options)) {
foreach ($options as $_key => $_val) {
$_html_result[] =
smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels,
$label_ids, $escape);
}
} else {
foreach ($values as $_i => $_key) {
$_val = isset($output[ $_i ]) ? $output[ $_i ] : '';
$_html_result[] =
smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels,
$label_ids, $escape);
}
}
if (!empty($params[ 'assign' ])) {
$template->assign($params[ 'assign' ], $_html_result);
} else {
return implode("\n", $_html_result);
}
}
/**
* @param $name
* @param $value
* @param $output
* @param $selected
* @param $extra
* @param $separator
* @param $labels
* @param $label_ids
* @param $escape
*
* @return string
*/
function smarty_function_html_radios_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids,
$escape)
{
$_output = '';
if (is_object($value)) {
if (method_exists($value, '__toString')) {
$value = (string) $value->__toString();
} else {
trigger_error('html_options: value is an object of class \'' . get_class($value) .
'\' without __toString() method', E_USER_NOTICE);
return '';
}
} else {
$value = (string) $value;
}
if (is_object($output)) {
if (method_exists($output, '__toString')) {
$output = (string) $output->__toString();
} else {
trigger_error('html_options: output is an object of class \'' . get_class($output) .
'\' without __toString() method', E_USER_NOTICE);
return '';
}
} else {
$output = (string) $output;
}
if ($labels) {
if ($label_ids) {
$_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_',
$name . '_' . $value));
$_output .= '<label for="' . $_id . '">';
} else {
$_output .= '<label>';
}
}
$name = smarty_function_escape_special_chars($name);
$value = smarty_function_escape_special_chars($value);
if ($escape) {
$output = smarty_function_escape_special_chars($output);
}
$_output .= '<input type="radio" name="' . $name . '" value="' . $value . '"';
if ($labels && $label_ids) {
$_output .= ' id="' . $_id . '"';
}
if ($value === $selected) {
$_output .= ' checked="checked"';
}
$_output .= $extra . ' />' . $output;
if ($labels) {
$_output .= '</label>';
}
$_output .= $separator;
return $_output;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.cat.php | Extend/Package/smarty/plugins/modifiercompiler.cat.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty cat modifier plugin
* Type: modifier
* Name: cat
* Date: Feb 24, 2003
* Purpose: catenate a value to a variable
* Input: string to catenate
* Example: {$var|cat:"foo"}
*
* @link http://smarty.php.net/manual/en/language.modifier.cat.php cat
* (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_cat($params)
{
return '(' . implode(').(', $params) . ')';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.html_checkboxes.php | Extend/Package/smarty/plugins/function.html_checkboxes.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_checkboxes} function plugin
* File: function.html_checkboxes.php
* Type: function
* Name: html_checkboxes
* Date: 24.Feb.2003
* Purpose: Prints out a list of checkbox input types
* Examples:
*
* {html_checkboxes values=$ids output=$names}
* {html_checkboxes values=$ids name='box' separator='<br>' output=$names}
* {html_checkboxes values=$ids checked=$checked separator='<br>' output=$names}
*
* Params:
*
* - name (optional) - string default "checkbox"
* - values (required) - array
* - options (optional) - associative array
* - checked (optional) - array default not set
* - separator (optional) - ie <br> or
* - output (optional) - the output next to each checkbox
* - assign (optional) - assign the output as an array to this variable
* - escape (optional) - escape the content (not value), defaults to true
*
*
* @link http://www.smarty.net/manual/en/language.function.html.checkboxes.php {html_checkboxes}
* (Smarty online manual)
* @author Christopher Kvarme <christopher.kvarme@flashjab.com>
* @author credits to Monte Ohrt <monte at ohrt dot com>
* @version 1.0
*
* @param array $params parameters
* @param object $template template object
*
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_checkboxes($params, $template)
{
if (!isset($template->smarty->_cache[ '_required_sesc' ])) {
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
$template->smarty->_cache[ '_required_sesc' ] = true;
}
$name = 'checkbox';
$values = null;
$options = null;
$selected = array();
$separator = '';
$escape = true;
$labels = true;
$label_ids = false;
$output = null;
$extra = '';
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'name':
case 'separator':
$$_key = (string) $_val;
break;
case 'escape':
case 'labels':
case 'label_ids':
$$_key = (bool) $_val;
break;
case 'options':
$$_key = (array) $_val;
break;
case 'values':
case 'output':
$$_key = array_values((array) $_val);
break;
case 'checked':
case 'selected':
if (is_array($_val)) {
$selected = array();
foreach ($_val as $_sel) {
if (is_object($_sel)) {
if (method_exists($_sel, '__toString')) {
$_sel = smarty_function_escape_special_chars((string) $_sel->__toString());
} else {
trigger_error('html_checkboxes: selected attribute contains an object of class \'' .
get_class($_sel) . '\' without __toString() method', E_USER_NOTICE);
continue;
}
} else {
$_sel = smarty_function_escape_special_chars((string) $_sel);
}
$selected[ $_sel ] = true;
}
} elseif (is_object($_val)) {
if (method_exists($_val, '__toString')) {
$selected = smarty_function_escape_special_chars((string) $_val->__toString());
} else {
trigger_error('html_checkboxes: selected attribute is an object of class \'' . get_class($_val) .
'\' without __toString() method', E_USER_NOTICE);
}
} else {
$selected = smarty_function_escape_special_chars((string) $_val);
}
break;
case 'checkboxes':
trigger_error('html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead',
E_USER_WARNING);
$options = (array) $_val;
break;
case 'assign':
break;
case 'strict':
break;
case 'disabled':
case 'readonly':
if (!empty($params[ 'strict' ])) {
if (!is_scalar($_val)) {
trigger_error("html_options: {$_key} attribute must be a scalar, only boolean true or string '{$_key}' will actually add the attribute",
E_USER_NOTICE);
}
if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
}
break;
}
// omit break; to fall through!
default:
if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
} else {
trigger_error("html_checkboxes: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (!isset($options) && !isset($values)) {
return '';
} /* raise error here? */
$_html_result = array();
if (isset($options)) {
foreach ($options as $_key => $_val) {
$_html_result[] =
smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels,
$label_ids, $escape);
}
} else {
foreach ($values as $_i => $_key) {
$_val = isset($output[ $_i ]) ? $output[ $_i ] : '';
$_html_result[] =
smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels,
$label_ids, $escape);
}
}
if (!empty($params[ 'assign' ])) {
$template->assign($params[ 'assign' ], $_html_result);
} else {
return implode("\n", $_html_result);
}
}
/**
* @param $name
* @param $value
* @param $output
* @param $selected
* @param $extra
* @param $separator
* @param $labels
* @param $label_ids
* @param bool $escape
*
* @return string
*/
function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels,
$label_ids, $escape = true)
{
$_output = '';
if (is_object($value)) {
if (method_exists($value, '__toString')) {
$value = (string) $value->__toString();
} else {
trigger_error('html_options: value is an object of class \'' . get_class($value) .
'\' without __toString() method', E_USER_NOTICE);
return '';
}
} else {
$value = (string) $value;
}
if (is_object($output)) {
if (method_exists($output, '__toString')) {
$output = (string) $output->__toString();
} else {
trigger_error('html_options: output is an object of class \'' . get_class($output) .
'\' without __toString() method', E_USER_NOTICE);
return '';
}
} else {
$output = (string) $output;
}
if ($labels) {
if ($label_ids) {
$_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!' . Smarty::$_UTF8_MODIFIER, '_',
$name . '_' . $value));
$_output .= '<label for="' . $_id . '">';
} else {
$_output .= '<label>';
}
}
$name = smarty_function_escape_special_chars($name);
$value = smarty_function_escape_special_chars($value);
if ($escape) {
$output = smarty_function_escape_special_chars($output);
}
$_output .= '<input type="checkbox" name="' . $name . '[]" value="' . $value . '"';
if ($labels && $label_ids) {
$_output .= ' id="' . $_id . '"';
}
if (is_array($selected)) {
if (isset($selected[ $value ])) {
$_output .= ' checked="checked"';
}
} elseif ($value === $selected) {
$_output .= ' checked="checked"';
}
$_output .= $extra . ' />' . $output;
if ($labels) {
$_output .= '</label>';
}
$_output .= $separator;
return $_output;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.count_sentences.php | Extend/Package/smarty/plugins/modifiercompiler.count_sentences.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty count_sentences modifier plugin
* Type: modifier
* Name: count_sentences
* Purpose: count the number of sentences in a text
*
* @link http://www.smarty.net/manual/en/language.modifier.count.paragraphs.php
* count_sentences (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_sentences($params)
{
// find periods, question marks, exclamation marks with a word before but not after.
return 'preg_match_all("#\w[\.\?\!](\W|$)#S' . Smarty::$_UTF8_MODIFIER . '", ' . $params[ 0 ] . ', $tmp)';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.count_words.php | Extend/Package/smarty/plugins/modifiercompiler.count_words.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty count_words modifier plugin
* Type: modifier
* Name: count_words
* Purpose: count the number of words in a text
*
* @link http://www.smarty.net/manual/en/language.modifier.count.words.php count_words (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_words($params)
{
if (Smarty::$_MBSTRING) {
// return 'preg_match_all(\'#[\w\pL]+#' . Smarty::$_UTF8_MODIFIER . '\', ' . $params[0] . ', $tmp)';
// expression taken from http://de.php.net/manual/en/function.str-word-count.php#85592
return 'preg_match_all(\'/\p{L}[\p{L}\p{Mn}\p{Pd}\\\'\x{2019}]*/' . Smarty::$_UTF8_MODIFIER . '\', ' .
$params[ 0 ] . ', $tmp)';
}
// no MBString fallback
return 'str_word_count(' . $params[ 0 ] . ')';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/block.textformat.php | Extend/Package/smarty/plugins/block.textformat.php | <?php
/**
* Smarty plugin to format text blocks
*
* @package Smarty
* @subpackage PluginsBlock
*/
/**
* Smarty {textformat}{/textformat} block plugin
* Type: block function
* Name: textformat
* Purpose: format text a certain way with preset styles
* or custom wrap/indent settings
* Params:
*
* - style - string (email)
* - indent - integer (0)
* - wrap - integer (80)
* - wrap_char - string ("\n")
* - indent_char - string (" ")
* - wrap_boundary - boolean (true)
*
*
* @link http://www.smarty.net/manual/en/language.function.textformat.php {textformat}
* (Smarty online manual)
*
* @param array $params parameters
* @param string $content contents of the block
* @param Smarty_Internal_Template $template template object
* @param boolean &$repeat repeat flag
*
* @return string content re-formatted
* @author Monte Ohrt <monte at ohrt dot com>
*/
function smarty_block_textformat($params, $content, $template, &$repeat)
{
static $mb_wordwrap_loaded = false;
if (is_null($content)) {
return;
}
if (Smarty::$_MBSTRING && !$mb_wordwrap_loaded) {
if (!is_callable('smarty_modifier_mb_wordwrap')) {
require_once(SMARTY_PLUGINS_DIR . 'modifier.mb_wordwrap.php');
}
$mb_wordwrap_loaded = true;
}
$style = null;
$indent = 0;
$indent_first = 0;
$indent_char = ' ';
$wrap = 80;
$wrap_char = "\n";
$wrap_cut = false;
$assign = null;
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'style':
case 'indent_char':
case 'wrap_char':
case 'assign':
$$_key = (string) $_val;
break;
case 'indent':
case 'indent_first':
case 'wrap':
$$_key = (int) $_val;
break;
case 'wrap_cut':
$$_key = (bool) $_val;
break;
default:
trigger_error("textformat: unknown attribute '{$_key}'");
}
}
if ($style === 'email') {
$wrap = 72;
}
// split into paragraphs
$_paragraphs = preg_split('![\r\n]{2}!', $content);
foreach ($_paragraphs as &$_paragraph) {
if (!$_paragraph) {
continue;
}
// convert mult. spaces & special chars to single space
$_paragraph =
preg_replace(array('!\s+!' . Smarty::$_UTF8_MODIFIER,
'!(^\s+)|(\s+$)!' . Smarty::$_UTF8_MODIFIER),
array(' ',
''), $_paragraph);
// indent first line
if ($indent_first > 0) {
$_paragraph = str_repeat($indent_char, $indent_first) . $_paragraph;
}
// wordwrap sentences
if (Smarty::$_MBSTRING) {
$_paragraph = smarty_modifier_mb_wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut);
} else {
$_paragraph = wordwrap($_paragraph, $wrap - $indent, $wrap_char, $wrap_cut);
}
// indent lines
if ($indent > 0) {
$_paragraph = preg_replace('!^!m', str_repeat($indent_char, $indent), $_paragraph);
}
}
$_output = implode($wrap_char . $wrap_char, $_paragraphs);
if ($assign) {
$template->assign($assign, $_output);
} else {
return $_output;
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.default.php | Extend/Package/smarty/plugins/modifiercompiler.default.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty default modifier plugin
* Type: modifier
* Name: default
* Purpose: designate default value for empty variables
*
* @link http://www.smarty.net/manual/en/language.modifier.default.php default (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_default($params)
{
$output = $params[ 0 ];
if (!isset($params[ 1 ])) {
$params[ 1 ] = "''";
}
array_shift($params);
foreach ($params as $param) {
$output = '(($tmp = @' . $output . ')===null||$tmp===\'\' ? ' . $param . ' : $tmp)';
}
return $output;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.strip_tags.php | Extend/Package/smarty/plugins/modifiercompiler.strip_tags.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty strip_tags modifier plugin
* Type: modifier
* Name: strip_tags
* Purpose: strip html tags from text
*
* @link http://www.smarty.net/docs/en/language.modifier.strip.tags.tpl strip_tags (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_strip_tags($params)
{
if (!isset($params[ 1 ]) || $params[ 1 ] === true || trim($params[ 1 ], '"') === 'true') {
return "preg_replace('!<[^>]*?>!', ' ', {$params[0]})";
} else {
return 'strip_tags(' . $params[ 0 ] . ')';
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifier.mb_wordwrap.php | Extend/Package/smarty/plugins/modifier.mb_wordwrap.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty wordwrap modifier plugin
* Type: modifier
* Name: mb_wordwrap
* Purpose: Wrap a string to a given number of characters
*
* @link http://php.net/manual/en/function.wordwrap.php for similarity
*
* @param string $str the string to wrap
* @param int $width the width of the output
* @param string $break the character used to break the line
* @param boolean $cut ignored parameter, just for the sake of
*
* @return string wrapped string
* @author Rodney Rehm
*/
function smarty_modifier_mb_wordwrap($str, $width = 75, $break = "\n", $cut = false)
{
// break words into tokens using white space as a delimiter
$tokens = preg_split('!(\s)!S' . Smarty::$_UTF8_MODIFIER, $str, -1, PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
$length = 0;
$t = '';
$_previous = false;
$_space = false;
foreach ($tokens as $_token) {
$token_length = mb_strlen($_token, Smarty::$_CHARSET);
$_tokens = array($_token);
if ($token_length > $width) {
if ($cut) {
$_tokens = preg_split('!(.{' . $width . '})!S' . Smarty::$_UTF8_MODIFIER,
$_token,
-1,
PREG_SPLIT_NO_EMPTY + PREG_SPLIT_DELIM_CAPTURE);
}
}
foreach ($_tokens as $token) {
$_space = !!preg_match('!^\s$!S' . Smarty::$_UTF8_MODIFIER, $token);
$token_length = mb_strlen($token, Smarty::$_CHARSET);
$length += $token_length;
if ($length > $width) {
// remove space before inserted break
if ($_previous) {
$t = mb_substr($t, 0, -1, Smarty::$_CHARSET);
}
if (!$_space) {
// add the break before the token
if (!empty($t)) {
$t .= $break;
}
$length = $token_length;
}
} else if ($token === "\n") {
// hard break must reset counters
$length = 0;
}
$_previous = $_space;
// add the token
$t .= $token;
}
}
return $t;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/shared.literal_compiler_param.php | Extend/Package/smarty/plugins/shared.literal_compiler_param.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsShared
*/
/**
* evaluate compiler parameter
*
* @param array $params parameter array as given to the compiler function
* @param integer $index array index of the parameter to convert
* @param mixed $default value to be returned if the parameter is not present
*
* @return mixed evaluated value of parameter or $default
* @throws SmartyException if parameter is not a literal (but an expression, variable, …)
* @author Rodney Rehm
*/
function smarty_literal_compiler_param($params, $index, $default = null)
{
// not set, go default
if (!isset($params[ $index ])) {
return $default;
}
// test if param is a literal
if (!preg_match('/^([\'"]?)[a-zA-Z0-9-]+(\\1)$/', $params[ $index ])) {
throw new SmartyException('$param[' . $index .
'] is not a literal and is thus not evaluatable at compile time');
}
$t = null;
eval("\$t = " . $params[ $index ] . ";");
return $t;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.html_select_date.php | Extend/Package/smarty/plugins/function.html_select_date.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_select_date} plugin
* Type: function
* Name: html_select_date
* Purpose: Prints the dropdowns for date selection.
* ChangeLog:
*
* - 1.0 initial release
* - 1.1 added support for +/- N syntax for begin
* and end year values. (Monte)
* - 1.2 added support for yyyy-mm-dd syntax for
* time value. (Jan Rosier)
* - 1.3 added support for choosing format for
* month values (Gary Loescher)
* - 1.3.1 added support for choosing format for
* day values (Marcus Bointon)
* - 1.3.2 support negative timestamps, force year
* dropdown to include given date unless explicitly set (Monte)
* - 1.3.4 fix behaviour of 0000-00-00 00:00:00 dates to match that
* of 0000-00-00 dates (cybot, boots)
* - 2.0 complete rewrite for performance,
* added attributes month_names, *_id
*
*
* @link http://www.smarty.net/manual/en/language.function.html.select.date.php {html_select_date}
* (Smarty online manual)
* @version 2.0
* @author Andrei Zmievski
* @author Monte Ohrt <monte at ohrt dot com>
* @author Rodney Rehm
*
* @param array $params parameters
*
* @param \Smarty_Internal_Template $template
*
* @return string
*/
function smarty_function_html_select_date($params, Smarty_Internal_Template $template)
{
if (!isset($template->smarty->_cache[ '_required_sesc' ])) {
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
$template->smarty->_cache[ '_required_sesc' ] = true;
}
if (!isset($template->smarty->_cache[ '_required_smt' ])) {
require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php');
$template->smarty->_cache[ '_required_smt' ] = true;
}
// generate timestamps used for month names only
static $_month_timestamps = null;
static $_current_year = null;
if ($_month_timestamps === null) {
$_current_year = date('Y');
$_month_timestamps = array();
for ($i = 1; $i <= 12; $i ++) {
$_month_timestamps[ $i ] = mktime(0, 0, 0, $i, 1, 2000);
}
}
/* Default values. */
$prefix = 'Date_';
$start_year = null;
$end_year = null;
$display_days = true;
$display_months = true;
$display_years = true;
$month_format = '%B';
/* Write months as numbers by default GL */
$month_value_format = '%m';
$day_format = '%02d';
/* Write day values using this format MB */
$day_value_format = '%d';
$year_as_text = false;
/* Display years in reverse order? Ie. 2000,1999,.... */
$reverse_years = false;
/* Should the select boxes be part of an array when returned from PHP?
e.g. setting it to "birthday", would create "birthday[Day]",
"birthday[Month]" & "birthday[Year]". Can be combined with prefix */
$field_array = null;
/* <select size>'s of the different <select> tags.
If not set, uses default dropdown. */
$day_size = null;
$month_size = null;
$year_size = null;
/* Unparsed attributes common to *ALL* the <select>/<input> tags.
An example might be in the template: all_extra ='class ="foo"'. */
$all_extra = null;
/* Separate attributes for the tags. */
$day_extra = null;
$month_extra = null;
$year_extra = null;
/* Order in which to display the fields.
"D" -> day, "M" -> month, "Y" -> year. */
$field_order = 'MDY';
/* String printed between the different fields. */
$field_separator = "\n";
$option_separator = "\n";
$time = null;
// $all_empty = null;
// $day_empty = null;
// $month_empty = null;
// $year_empty = null;
$extra_attrs = '';
$all_id = null;
$day_id = null;
$month_id = null;
$year_id = null;
foreach ($params as $_key => $_value) {
switch ($_key) {
case 'time':
if (!is_array($_value) && $_value !== null) {
$time = smarty_make_timestamp($_value);
}
break;
case 'month_names':
if (is_array($_value) && count($_value) === 12) {
$$_key = $_value;
} else {
trigger_error('html_select_date: month_names must be an array of 12 strings', E_USER_NOTICE);
}
break;
case 'prefix':
case 'field_array':
case 'start_year':
case 'end_year':
case 'day_format':
case 'day_value_format':
case 'month_format':
case 'month_value_format':
case 'day_size':
case 'month_size':
case 'year_size':
case 'all_extra':
case 'day_extra':
case 'month_extra':
case 'year_extra':
case 'field_order':
case 'field_separator':
case 'option_separator':
case 'all_empty':
case 'month_empty':
case 'day_empty':
case 'year_empty':
case 'all_id':
case 'month_id':
case 'day_id':
case 'year_id':
$$_key = (string) $_value;
break;
case 'display_days':
case 'display_months':
case 'display_years':
case 'year_as_text':
case 'reverse_years':
$$_key = (bool) $_value;
break;
default:
if (!is_array($_value)) {
$extra_attrs .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_value) . '"';
} else {
trigger_error("html_select_date: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE);
}
break;
}
}
// Note: date() is faster than strftime()
// Note: explode(date()) is faster than date() date() date()
if (isset($params[ 'time' ]) && is_array($params[ 'time' ])) {
if (isset($params[ 'time' ][ $prefix . 'Year' ])) {
// $_REQUEST[$field_array] given
foreach (array('Y' => 'Year',
'm' => 'Month',
'd' => 'Day') as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName);
$$_variableName =
isset($params[ 'time' ][ $prefix . $_elementName ]) ? $params[ 'time' ][ $prefix . $_elementName ] :
date($_elementKey);
}
} elseif (isset($params[ 'time' ][ $field_array ][ $prefix . 'Year' ])) {
// $_REQUEST given
foreach (array('Y' => 'Year',
'm' => 'Month',
'd' => 'Day') as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName);
$$_variableName = isset($params[ 'time' ][ $field_array ][ $prefix . $_elementName ]) ?
$params[ 'time' ][ $field_array ][ $prefix . $_elementName ] : date($_elementKey);
}
} else {
// no date found, use NOW
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d'));
}
} elseif ($time === null) {
if (array_key_exists('time', $params)) {
$_year = $_month = $_day = $time = null;
} else {
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d'));
}
} else {
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d', $time));
}
// make syntax "+N" or "-N" work with $start_year and $end_year
// Note preg_match('!^(\+|\-)\s*(\d+)$!', $end_year, $match) is slower than trim+substr
foreach (array('start',
'end') as $key) {
$key .= '_year';
$t = $$key;
if ($t === null) {
$$key = (int) $_current_year;
} elseif ($t[ 0 ] === '+') {
$$key = (int) ($_current_year + (int) trim(substr($t, 1)));
} elseif ($t[ 0 ] === '-') {
$$key = (int) ($_current_year - (int) trim(substr($t, 1)));
} else {
$$key = (int) $$key;
}
}
// flip for ascending or descending
if (($start_year > $end_year && !$reverse_years) || ($start_year < $end_year && $reverse_years)) {
$t = $end_year;
$end_year = $start_year;
$start_year = $t;
}
// generate year <select> or <input>
if ($display_years) {
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Year]') : ($prefix . 'Year');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($year_extra) {
$_extra .= ' ' . $year_extra;
}
if ($year_as_text) {
$_html_years =
'<input type="text" name="' . $_name . '" value="' . $_year . '" size="4" maxlength="4"' . $_extra .
$extra_attrs . ' />';
} else {
$_html_years = '<select name="' . $_name . '"';
if ($year_id !== null || $all_id !== null) {
$_html_years .= ' id="' . smarty_function_escape_special_chars($year_id !== null ?
($year_id ? $year_id : $_name) :
($all_id ? ($all_id . $_name) :
$_name)) . '"';
}
if ($year_size) {
$_html_years .= ' size="' . $year_size . '"';
}
$_html_years .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($year_empty) || isset($all_empty)) {
$_html_years .= '<option value="">' . (isset($year_empty) ? $year_empty : $all_empty) . '</option>' .
$option_separator;
}
$op = $start_year > $end_year ? - 1 : 1;
for ($i = $start_year; $op > 0 ? $i <= $end_year : $i >= $end_year; $i += $op) {
$_html_years .= '<option value="' . $i . '"' . ($_year == $i ? ' selected="selected"' : '') . '>' . $i .
'</option>' . $option_separator;
}
$_html_years .= '</select>';
}
}
// generate month <select> or <input>
if ($display_months) {
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Month]') : ($prefix . 'Month');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($month_extra) {
$_extra .= ' ' . $month_extra;
}
$_html_months = '<select name="' . $_name . '"';
if ($month_id !== null || $all_id !== null) {
$_html_months .= ' id="' . smarty_function_escape_special_chars($month_id !== null ?
($month_id ? $month_id : $_name) :
($all_id ? ($all_id . $_name) :
$_name)) . '"';
}
if ($month_size) {
$_html_months .= ' size="' . $month_size . '"';
}
$_html_months .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($month_empty) || isset($all_empty)) {
$_html_months .= '<option value="">' . (isset($month_empty) ? $month_empty : $all_empty) . '</option>' .
$option_separator;
}
for ($i = 1; $i <= 12; $i ++) {
$_val = sprintf('%02d', $i);
$_text = isset($month_names) ? smarty_function_escape_special_chars($month_names[ $i ]) :
($month_format === '%m' ? $_val : strftime($month_format, $_month_timestamps[ $i ]));
$_value = $month_value_format === '%m' ? $_val : strftime($month_value_format, $_month_timestamps[ $i ]);
$_html_months .= '<option value="' . $_value . '"' . ($_val == $_month ? ' selected="selected"' : '') .
'>' . $_text . '</option>' . $option_separator;
}
$_html_months .= '</select>';
}
// generate day <select> or <input>
if ($display_days) {
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Day]') : ($prefix . 'Day');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($day_extra) {
$_extra .= ' ' . $day_extra;
}
$_html_days = '<select name="' . $_name . '"';
if ($day_id !== null || $all_id !== null) {
$_html_days .= ' id="' .
smarty_function_escape_special_chars($day_id !== null ? ($day_id ? $day_id : $_name) :
($all_id ? ($all_id . $_name) : $_name)) . '"';
}
if ($day_size) {
$_html_days .= ' size="' . $day_size . '"';
}
$_html_days .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($day_empty) || isset($all_empty)) {
$_html_days .= '<option value="">' . (isset($day_empty) ? $day_empty : $all_empty) . '</option>' .
$option_separator;
}
for ($i = 1; $i <= 31; $i ++) {
$_val = sprintf('%02d', $i);
$_text = $day_format === '%02d' ? $_val : sprintf($day_format, $i);
$_value = $day_value_format === '%02d' ? $_val : sprintf($day_value_format, $i);
$_html_days .= '<option value="' . $_value . '"' . ($_val == $_day ? ' selected="selected"' : '') . '>' .
$_text . '</option>' . $option_separator;
}
$_html_days .= '</select>';
}
// order the fields for output
$_html = '';
for ($i = 0; $i <= 2; $i ++) {
switch ($field_order[ $i ]) {
case 'Y':
case 'y':
if (isset($_html_years)) {
if ($_html) {
$_html .= $field_separator;
}
$_html .= $_html_years;
}
break;
case 'm':
case 'M':
if (isset($_html_months)) {
if ($_html) {
$_html .= $field_separator;
}
$_html .= $_html_months;
}
break;
case 'd':
case 'D':
if (isset($_html_days)) {
if ($_html) {
$_html .= $field_separator;
}
$_html .= $_html_days;
}
break;
}
}
return $_html;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/shared.escape_special_chars.php | Extend/Package/smarty/plugins/shared.escape_special_chars.php | <?php
/**
* Smarty shared plugin
*
* @package Smarty
* @subpackage PluginsShared
*/
/**
* escape_special_chars common function
* Function: smarty_function_escape_special_chars
* Purpose: used by other smarty functions to escape
* special chars except for already escaped ones
*
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string text that should by escaped
*
* @return string
*/
function smarty_function_escape_special_chars($string)
{
if (!is_array($string)) {
if (version_compare(PHP_VERSION, '5.2.3', '>=')) {
$string = htmlspecialchars($string, ENT_COMPAT, Smarty::$_CHARSET, false);
} else {
$string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string);
$string = htmlspecialchars($string);
$string = str_replace(array('%%%SMARTY_START%%%', '%%%SMARTY_END%%%'), array('&', ';'), $string);
}
}
return $string;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/shared.make_timestamp.php | Extend/Package/smarty/plugins/shared.make_timestamp.php | <?php
/**
* Smarty shared plugin
*
* @package Smarty
* @subpackage PluginsShared
*/
/**
* Function: smarty_make_timestamp
* Purpose: used by other smarty functions to make a timestamp from a string.
*
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param DateTime|int|string $string date object, timestamp or string that can be converted using strtotime()
*
* @return int
*/
function smarty_make_timestamp($string)
{
if (empty($string)) {
// use "now":
return time();
} elseif ($string instanceof DateTime ||
(interface_exists('DateTimeInterface', false) && $string instanceof DateTimeInterface)
) {
return (int) $string->format('U'); // PHP 5.2 BC
} elseif (strlen($string) === 14 && ctype_digit($string)) {
// it is mysql timestamp format of YYYYMMDDHHMMSS?
return mktime(substr($string, 8, 2), substr($string, 10, 2), substr($string, 12, 2), substr($string, 4, 2),
substr($string, 6, 2), substr($string, 0, 4));
} elseif (is_numeric($string)) {
// it is a numeric string, we handle it as timestamp
return (int) $string;
} else {
// strtotime should handle it
$time = strtotime($string);
if ($time === - 1 || $time === false) {
// strtotime() was not able to parse $string, use "now":
return time();
}
return $time;
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/shared.mb_unicode.php | Extend/Package/smarty/plugins/shared.mb_unicode.php | <?php
/**
* Smarty shared plugin
*
* @package Smarty
* @subpackage PluginsShared
*/
/**
* convert characters to their decimal unicode equivalents
*
* @link http://www.ibm.com/developerworks/library/os-php-unicode/index.html#listing3 for inspiration
*
* @param string $string characters to calculate unicode of
* @param string $encoding encoding of $string, if null mb_internal_encoding() is used
*
* @return array sequence of unicodes
* @author Rodney Rehm
*/
function smarty_mb_to_unicode($string, $encoding = null)
{
if ($encoding) {
$expanded = mb_convert_encoding($string, 'UTF-32BE', $encoding);
} else {
$expanded = mb_convert_encoding($string, 'UTF-32BE');
}
return unpack('N*', $expanded);
}
/**
* convert unicodes to the character of given encoding
*
* @link http://www.ibm.com/developerworks/library/os-php-unicode/index.html#listing3 for inspiration
*
* @param integer|array $unicode single unicode or list of unicodes to convert
* @param string $encoding encoding of returned string, if null mb_internal_encoding() is used
*
* @return string unicode as character sequence in given $encoding
* @author Rodney Rehm
*/
function smarty_mb_from_unicode($unicode, $encoding = null)
{
$t = '';
if (!$encoding) {
$encoding = mb_internal_encoding();
}
foreach ((array) $unicode as $utf32be) {
$character = pack('N*', $utf32be);
$t .= mb_convert_encoding($character, $encoding, 'UTF-32BE');
}
return $t;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.upper.php | Extend/Package/smarty/plugins/modifiercompiler.upper.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty upper modifier plugin
* Type: modifier
* Name: lower
* Purpose: convert string to uppercase
*
* @link http://smarty.php.net/manual/en/language.modifier.upper.php lower (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_upper($params)
{
if (Smarty::$_MBSTRING) {
return 'mb_strtoupper(' . $params[ 0 ] . ', \'' . addslashes(Smarty::$_CHARSET) . '\')';
}
// no MBString fallback
return 'strtoupper(' . $params[ 0 ] . ')';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.to_charset.php | Extend/Package/smarty/plugins/modifiercompiler.to_charset.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty to_charset modifier plugin
* Type: modifier
* Name: to_charset
* Purpose: convert character encoding from internal encoding to $charset
*
* @author Rodney Rehm
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_to_charset($params)
{
if (!Smarty::$_MBSTRING) {
// FIXME: (rodneyrehm) shouldn't this throw an error?
return $params[ 0 ];
}
if (!isset($params[ 1 ])) {
$params[ 1 ] = '"ISO-8859-1"';
}
return 'mb_convert_encoding(' . $params[ 0 ] . ', ' . $params[ 1 ] . ', "' . addslashes(Smarty::$_CHARSET) . '")';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifier.replace.php | Extend/Package/smarty/plugins/modifier.replace.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty replace modifier plugin
* Type: modifier
* Name: replace
* Purpose: simple search/replace
*
* @link http://smarty.php.net/manual/en/language.modifier.replace.php replace (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
*
* @param string $string input string
* @param string $search text to search for
* @param string $replace replacement text
*
* @return string
*/
function smarty_modifier_replace($string, $search, $replace)
{
static $is_loaded = false;
if (Smarty::$_MBSTRING) {
if (!$is_loaded) {
if (!is_callable('smarty_mb_str_replace')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.mb_str_replace.php');
}
$is_loaded = true;
}
return smarty_mb_str_replace($search, $replace, $string);
}
return str_replace($search, $replace, $string);
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.cycle.php | Extend/Package/smarty/plugins/function.cycle.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {cycle} function plugin
* Type: function
* Name: cycle
* Date: May 3, 2002
* Purpose: cycle through given values
* Params:
*
* - name - name of cycle (optional)
* - values - comma separated list of values to cycle, or an array of values to cycle
* (this can be left out for subsequent calls)
* - reset - boolean - resets given var to true
* - print - boolean - print var or not. default is true
* - advance - boolean - whether or not to advance the cycle
* - delimiter - the value delimiter, default is ","
* - assign - boolean, assigns to template var instead of printed.
*
* Examples:
*
* {cycle values="#eeeeee,#d0d0d0d"}
* {cycle name=row values="one,two,three" reset=true}
* {cycle name=row}
*
*
* @link http://www.smarty.net/manual/en/language.function.cycle.php {cycle}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author credit to Mark Priatel <mpriatel@rogers.com>
* @author credit to Gerard <gerard@interfold.com>
* @author credit to Jason Sweat <jsweat_php@yahoo.com>
* @version 1.3
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string|null
*/
function smarty_function_cycle($params, $template)
{
static $cycle_vars;
$name = (empty($params[ 'name' ])) ? 'default' : $params[ 'name' ];
$print = (isset($params[ 'print' ])) ? (bool) $params[ 'print' ] : true;
$advance = (isset($params[ 'advance' ])) ? (bool) $params[ 'advance' ] : true;
$reset = (isset($params[ 'reset' ])) ? (bool) $params[ 'reset' ] : false;
if (!isset($params[ 'values' ])) {
if (!isset($cycle_vars[ $name ][ 'values' ])) {
trigger_error('cycle: missing \'values\' parameter');
return;
}
} else {
if (isset($cycle_vars[ $name ][ 'values' ]) && $cycle_vars[ $name ][ 'values' ] !== $params[ 'values' ]) {
$cycle_vars[ $name ][ 'index' ] = 0;
}
$cycle_vars[ $name ][ 'values' ] = $params[ 'values' ];
}
if (isset($params[ 'delimiter' ])) {
$cycle_vars[ $name ][ 'delimiter' ] = $params[ 'delimiter' ];
} elseif (!isset($cycle_vars[ $name ][ 'delimiter' ])) {
$cycle_vars[ $name ][ 'delimiter' ] = ',';
}
if (is_array($cycle_vars[ $name ][ 'values' ])) {
$cycle_array = $cycle_vars[ $name ][ 'values' ];
} else {
$cycle_array = explode($cycle_vars[ $name ][ 'delimiter' ], $cycle_vars[ $name ][ 'values' ]);
}
if (!isset($cycle_vars[ $name ][ 'index' ]) || $reset) {
$cycle_vars[ $name ][ 'index' ] = 0;
}
if (isset($params[ 'assign' ])) {
$print = false;
$template->assign($params[ 'assign' ], $cycle_array[ $cycle_vars[ $name ][ 'index' ] ]);
}
if ($print) {
$retval = $cycle_array[ $cycle_vars[ $name ][ 'index' ] ];
} else {
$retval = null;
}
if ($advance) {
if ($cycle_vars[ $name ][ 'index' ] >= count($cycle_array) - 1) {
$cycle_vars[ $name ][ 'index' ] = 0;
} else {
$cycle_vars[ $name ][ 'index' ] ++;
}
}
return $retval;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.string_format.php | Extend/Package/smarty/plugins/modifiercompiler.string_format.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty string_format modifier plugin
* Type: modifier
* Name: string_format
* Purpose: format strings via sprintf
*
* @link http://www.smarty.net/manual/en/language.modifier.string.format.php string_format (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_string_format($params)
{
return 'sprintf(' . $params[ 1 ] . ',' . $params[ 0 ] . ')';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.wordwrap.php | Extend/Package/smarty/plugins/modifiercompiler.wordwrap.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty wordwrap modifier plugin
* Type: modifier
* Name: wordwrap
* Purpose: wrap a string of text at a given length
*
* @link http://smarty.php.net/manual/en/language.modifier.wordwrap.php wordwrap (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
* @param \Smarty_Internal_TemplateCompilerBase $compiler
*
* @return string with compiled code
* @throws \SmartyException
*/
function smarty_modifiercompiler_wordwrap($params, Smarty_Internal_TemplateCompilerBase $compiler)
{
if (!isset($params[ 1 ])) {
$params[ 1 ] = 80;
}
if (!isset($params[ 2 ])) {
$params[ 2 ] = '"\n"';
}
if (!isset($params[ 3 ])) {
$params[ 3 ] = 'false';
}
$function = 'wordwrap';
if (Smarty::$_MBSTRING) {
$function = $compiler->getPlugin('mb_wordwrap','modifier');
}
return $function . '(' . $params[ 0 ] . ',' . $params[ 1 ] . ',' . $params[ 2 ] . ',' . $params[ 3 ] . ')';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifier.regex_replace.php | Extend/Package/smarty/plugins/modifier.regex_replace.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty regex_replace modifier plugin
* Type: modifier
* Name: regex_replace
* Purpose: regular expression search/replace
*
* @link http://smarty.php.net/manual/en/language.modifier.regex.replace.php
* regex_replace (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param string|array $search regular expression(s) to search for
* @param string|array $replace string(s) that should be replaced
* @param int $limit the maximum number of replacements
*
* @return string
*/
function smarty_modifier_regex_replace($string, $search, $replace, $limit = - 1)
{
if (is_array($search)) {
foreach ($search as $idx => $s) {
$search[ $idx ] = _smarty_regex_replace_check($s);
}
} else {
$search = _smarty_regex_replace_check($search);
}
return preg_replace($search, $replace, $string, $limit);
}
/**
* @param string $search string(s) that should be replaced
*
* @return string
* @ignore
*/
function _smarty_regex_replace_check($search)
{
// null-byte injection detection
// anything behind the first null-byte is ignored
if (($pos = strpos($search, "\0")) !== false) {
$search = substr($search, 0, $pos);
}
// remove eval-modifier from $search
if (preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[ 1 ], 'e') !== false)) {
$search = substr($search, 0, - strlen($match[ 1 ])) . preg_replace('![e\s]+!', '', $match[ 1 ]);
}
return $search;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.html_options.php | Extend/Package/smarty/plugins/function.html_options.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_options} function plugin
* Type: function
* Name: html_options
* Purpose: Prints the list of <option> tags generated from
* the passed parameters
* Params:
*
* - name (optional) - string default "select"
* - values (required) - if no options supplied) - array
* - options (required) - if no values supplied) - associative array
* - selected (optional) - string default not set
* - output (required) - if not options supplied) - array
* - id (optional) - string default not set
* - class (optional) - string default not set
*
*
* @link http://www.smarty.net/manual/en/language.function.html.options.php {html_image}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author Ralf Strehle (minor optimization) <ralf dot strehle at yahoo dot de>
*
* @param array $params parameters
*
* @param \Smarty_Internal_Template $template
*
* @return string
* @uses smarty_function_escape_special_chars()
*/
function smarty_function_html_options($params, Smarty_Internal_Template $template)
{
if (!isset($template->smarty->_cache[ '_required_sesc' ])) {
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
$template->smarty->_cache[ '_required_sesc' ] = true;
}
$name = null;
$values = null;
$options = null;
$selected = null;
$output = null;
$id = null;
$class = null;
$extra = '';
foreach ($params as $_key => $_val) {
switch ($_key) {
case 'name':
case 'class':
case 'id':
$$_key = (string) $_val;
break;
case 'options':
$options = (array) $_val;
break;
case 'values':
case 'output':
$$_key = array_values((array) $_val);
break;
case 'selected':
if (is_array($_val)) {
$selected = array();
foreach ($_val as $_sel) {
if (is_object($_sel)) {
if (method_exists($_sel, '__toString')) {
$_sel = smarty_function_escape_special_chars((string) $_sel->__toString());
} else {
trigger_error('html_options: selected attribute contains an object of class \'' .
get_class($_sel) . '\' without __toString() method', E_USER_NOTICE);
continue;
}
} else {
$_sel = smarty_function_escape_special_chars((string) $_sel);
}
$selected[ $_sel ] = true;
}
} elseif (is_object($_val)) {
if (method_exists($_val, '__toString')) {
$selected = smarty_function_escape_special_chars((string) $_val->__toString());
} else {
trigger_error('html_options: selected attribute is an object of class \'' . get_class($_val) .
'\' without __toString() method', E_USER_NOTICE);
}
} else {
$selected = smarty_function_escape_special_chars((string) $_val);
}
break;
case 'strict':
break;
case 'disabled':
case 'readonly':
if (!empty($params[ 'strict' ])) {
if (!is_scalar($_val)) {
trigger_error("html_options: {$_key} attribute must be a scalar, only boolean true or string '{$_key}' will actually add the attribute",
E_USER_NOTICE);
}
if ($_val === true || $_val === $_key) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_key) . '"';
}
break;
}
// omit break; to fall through!
default:
if (!is_array($_val)) {
$extra .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_val) . '"';
} else {
trigger_error("html_options: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (!isset($options) && !isset($values)) {
/* raise error here? */
return '';
}
$_html_result = '';
$_idx = 0;
if (isset($options)) {
foreach ($options as $_key => $_val) {
$_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $_idx);
}
} else {
foreach ($values as $_i => $_key) {
$_val = isset($output[ $_i ]) ? $output[ $_i ] : '';
$_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected, $id, $class, $_idx);
}
}
if (!empty($name)) {
$_html_class = !empty($class) ? ' class="' . $class . '"' : '';
$_html_id = !empty($id) ? ' id="' . $id . '"' : '';
$_html_result =
'<select name="' . $name . '"' . $_html_class . $_html_id . $extra . '>' . "\n" . $_html_result .
'</select>' . "\n";
}
return $_html_result;
}
/**
* @param $key
* @param $value
* @param $selected
* @param $id
* @param $class
* @param $idx
*
* @return string
*/
function smarty_function_html_options_optoutput($key, $value, $selected, $id, $class, &$idx)
{
if (!is_array($value)) {
$_key = smarty_function_escape_special_chars($key);
$_html_result = '<option value="' . $_key . '"';
if (is_array($selected)) {
if (isset($selected[ $_key ])) {
$_html_result .= ' selected="selected"';
}
} elseif ($_key === $selected) {
$_html_result .= ' selected="selected"';
}
$_html_class = !empty($class) ? ' class="' . $class . ' option"' : '';
$_html_id = !empty($id) ? ' id="' . $id . '-' . $idx . '"' : '';
if (is_object($value)) {
if (method_exists($value, '__toString')) {
$value = smarty_function_escape_special_chars((string) $value->__toString());
} else {
trigger_error('html_options: value is an object of class \'' . get_class($value) .
'\' without __toString() method', E_USER_NOTICE);
return '';
}
} else {
$value = smarty_function_escape_special_chars((string) $value);
}
$_html_result .= $_html_class . $_html_id . '>' . $value . '</option>' . "\n";
$idx ++;
} else {
$_idx = 0;
$_html_result =
smarty_function_html_options_optgroup($key, $value, $selected, !empty($id) ? ($id . '-' . $idx) : null,
$class, $_idx);
$idx ++;
}
return $_html_result;
}
/**
* @param $key
* @param $values
* @param $selected
* @param $id
* @param $class
* @param $idx
*
* @return string
*/
function smarty_function_html_options_optgroup($key, $values, $selected, $id, $class, &$idx)
{
$optgroup_html = '<optgroup label="' . smarty_function_escape_special_chars($key) . '">' . "\n";
foreach ($values as $key => $value) {
$optgroup_html .= smarty_function_html_options_optoutput($key, $value, $selected, $id, $class, $idx);
}
$optgroup_html .= "</optgroup>\n";
return $optgroup_html;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifier.capitalize.php | Extend/Package/smarty/plugins/modifier.capitalize.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty capitalize modifier plugin
* Type: modifier
* Name: capitalize
* Purpose: capitalize words in the string
* {@internal {$string|capitalize:true:true} is the fastest option for MBString enabled systems }}
*
* @param string $string string to capitalize
* @param boolean $uc_digits also capitalize "x123" to "X123"
* @param boolean $lc_rest capitalize first letters, lowercase all following letters "aAa" to "Aaa"
*
* @return string capitalized string
* @author Monte Ohrt <monte at ohrt dot com>
* @author Rodney Rehm
*/
function smarty_modifier_capitalize($string, $uc_digits = false, $lc_rest = false)
{
if (Smarty::$_MBSTRING) {
if ($lc_rest) {
// uppercase (including hyphenated words)
$upper_string = mb_convert_case($string, MB_CASE_TITLE, Smarty::$_CHARSET);
} else {
// uppercase word breaks
$upper_string = preg_replace_callback("!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER,
'smarty_mod_cap_mbconvert_cb', $string);
}
// check uc_digits case
if (!$uc_digits) {
if (preg_match_all("!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER, $string, $matches,
PREG_OFFSET_CAPTURE)) {
foreach ($matches[ 1 ] as $match) {
$upper_string =
substr_replace($upper_string, mb_strtolower($match[ 0 ], Smarty::$_CHARSET), $match[ 1 ],
strlen($match[ 0 ]));
}
}
}
$upper_string =
preg_replace_callback("!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_mbconvert2_cb',
$upper_string);
return $upper_string;
}
// lowercase first
if ($lc_rest) {
$string = strtolower($string);
}
// uppercase (including hyphenated words)
$upper_string =
preg_replace_callback("!(^|[^\p{L}'])([\p{Ll}])!S" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_ucfirst_cb',
$string);
// check uc_digits case
if (!$uc_digits) {
if (preg_match_all("!\b([\p{L}]*[\p{N}]+[\p{L}]*)\b!" . Smarty::$_UTF8_MODIFIER, $string, $matches,
PREG_OFFSET_CAPTURE)) {
foreach ($matches[ 1 ] as $match) {
$upper_string =
substr_replace($upper_string, strtolower($match[ 0 ]), $match[ 1 ], strlen($match[ 0 ]));
}
}
}
$upper_string = preg_replace_callback("!((^|\s)['\"])(\w)!" . Smarty::$_UTF8_MODIFIER, 'smarty_mod_cap_ucfirst2_cb',
$upper_string);
return $upper_string;
}
/*
*
* Bug: create_function() use exhausts memory when used in long loops
* Fix: use declared functions for callbacks instead of using create_function()
* Note: This can be fixed using anonymous functions instead, but that requires PHP >= 5.3
*
* @author Kyle Renfrow
*/
/**
* @param $matches
*
* @return string
*/
function smarty_mod_cap_mbconvert_cb($matches)
{
return stripslashes($matches[ 1 ]) . mb_convert_case(stripslashes($matches[ 2 ]), MB_CASE_UPPER, Smarty::$_CHARSET);
}
/**
* @param $matches
*
* @return string
*/
function smarty_mod_cap_mbconvert2_cb($matches)
{
return stripslashes($matches[ 1 ]) . mb_convert_case(stripslashes($matches[ 3 ]), MB_CASE_UPPER, Smarty::$_CHARSET);
}
/**
* @param $matches
*
* @return string
*/
function smarty_mod_cap_ucfirst_cb($matches)
{
return stripslashes($matches[ 1 ]) . ucfirst(stripslashes($matches[ 2 ]));
}
/**
* @param $matches
*
* @return string
*/
function smarty_mod_cap_ucfirst2_cb($matches)
{
return stripslashes($matches[ 1 ]) . ucfirst(stripslashes($matches[ 3 ]));
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.html_select_time.php | Extend/Package/smarty/plugins/function.html_select_time.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_select_time} function plugin
* Type: function
* Name: html_select_time
* Purpose: Prints the dropdowns for time selection
*
* @link http://www.smarty.net/manual/en/language.function.html.select.time.php {html_select_time}
* (Smarty online manual)
* @author Roberto Berto <roberto@berto.net>
* @author Monte Ohrt <monte AT ohrt DOT com>
*
* @param array $params parameters
*
* @param \Smarty_Internal_Template $template
*
* @return string
* @uses smarty_make_timestamp()
*/
function smarty_function_html_select_time($params, Smarty_Internal_Template $template)
{
if (!isset($template->smarty->_cache[ '_required_sesc' ])) {
require_once(SMARTY_PLUGINS_DIR . 'shared.escape_special_chars.php');
$template->smarty->_cache[ '_required_sesc' ] = true;
}
if (!isset($template->smarty->_cache[ '_required_smt' ])) {
require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php');
$template->smarty->_cache[ '_required_smt' ] = true;
}
$prefix = 'Time_';
$field_array = null;
$field_separator = "\n";
$option_separator = "\n";
$time = null;
$display_hours = true;
$display_minutes = true;
$display_seconds = true;
$display_meridian = true;
$hour_format = '%02d';
$hour_value_format = '%02d';
$minute_format = '%02d';
$minute_value_format = '%02d';
$second_format = '%02d';
$second_value_format = '%02d';
$hour_size = null;
$minute_size = null;
$second_size = null;
$meridian_size = null;
$all_empty = null;
$hour_empty = null;
$minute_empty = null;
$second_empty = null;
$meridian_empty = null;
$all_id = null;
$hour_id = null;
$minute_id = null;
$second_id = null;
$meridian_id = null;
$use_24_hours = true;
$minute_interval = 1;
$second_interval = 1;
$extra_attrs = '';
$all_extra = null;
$hour_extra = null;
$minute_extra = null;
$second_extra = null;
$meridian_extra = null;
foreach ($params as $_key => $_value) {
switch ($_key) {
case 'time':
if (!is_array($_value) && $_value !== null) {
$time = smarty_make_timestamp($_value);
}
break;
case 'prefix':
case 'field_array':
case 'field_separator':
case 'option_separator':
case 'all_extra':
case 'hour_extra':
case 'minute_extra':
case 'second_extra':
case 'meridian_extra':
case 'all_empty':
case 'hour_empty':
case 'minute_empty':
case 'second_empty':
case 'meridian_empty':
case 'all_id':
case 'hour_id':
case 'minute_id':
case 'second_id':
case 'meridian_id':
case 'hour_format':
case 'hour_value_format':
case 'minute_format':
case 'minute_value_format':
case 'second_format':
case 'second_value_format':
$$_key = (string) $_value;
break;
case 'display_hours':
case 'display_minutes':
case 'display_seconds':
case 'display_meridian':
case 'use_24_hours':
$$_key = (bool) $_value;
break;
case 'minute_interval':
case 'second_interval':
case 'hour_size':
case 'minute_size':
case 'second_size':
case 'meridian_size':
$$_key = (int) $_value;
break;
default:
if (!is_array($_value)) {
$extra_attrs .= ' ' . $_key . '="' . smarty_function_escape_special_chars($_value) . '"';
} else {
trigger_error("html_select_date: extra attribute '{$_key}' cannot be an array", E_USER_NOTICE);
}
break;
}
}
if (isset($params[ 'time' ]) && is_array($params[ 'time' ])) {
if (isset($params[ 'time' ][ $prefix . 'Hour' ])) {
// $_REQUEST[$field_array] given
foreach (array('H' => 'Hour',
'i' => 'Minute',
's' => 'Second') as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName);
$$_variableName =
isset($params[ 'time' ][ $prefix . $_elementName ]) ? $params[ 'time' ][ $prefix . $_elementName ] :
date($_elementKey);
}
$_meridian =
isset($params[ 'time' ][ $prefix . 'Meridian' ]) ? (' ' . $params[ 'time' ][ $prefix . 'Meridian' ]) :
'';
$time = strtotime($_hour . ':' . $_minute . ':' . $_second . $_meridian);
list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time));
} elseif (isset($params[ 'time' ][ $field_array ][ $prefix . 'Hour' ])) {
// $_REQUEST given
foreach (array('H' => 'Hour',
'i' => 'Minute',
's' => 'Second') as $_elementKey => $_elementName) {
$_variableName = '_' . strtolower($_elementName);
$$_variableName = isset($params[ 'time' ][ $field_array ][ $prefix . $_elementName ]) ?
$params[ 'time' ][ $field_array ][ $prefix . $_elementName ] : date($_elementKey);
}
$_meridian = isset($params[ 'time' ][ $field_array ][ $prefix . 'Meridian' ]) ?
(' ' . $params[ 'time' ][ $field_array ][ $prefix . 'Meridian' ]) : '';
$time = strtotime($_hour . ':' . $_minute . ':' . $_second . $_meridian);
list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time));
} else {
// no date found, use NOW
list($_year, $_month, $_day) = $time = explode('-', date('Y-m-d'));
}
} elseif ($time === null) {
if (array_key_exists('time', $params)) {
$_hour = $_minute = $_second = $time = null;
} else {
list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s'));
}
} else {
list($_hour, $_minute, $_second) = $time = explode('-', date('H-i-s', $time));
}
// generate hour <select>
if ($display_hours) {
$_html_hours = '';
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Hour]') : ($prefix . 'Hour');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($hour_extra) {
$_extra .= ' ' . $hour_extra;
}
$_html_hours = '<select name="' . $_name . '"';
if ($hour_id !== null || $all_id !== null) {
$_html_hours .= ' id="' .
smarty_function_escape_special_chars($hour_id !== null ? ($hour_id ? $hour_id : $_name) :
($all_id ? ($all_id . $_name) : $_name)) . '"';
}
if ($hour_size) {
$_html_hours .= ' size="' . $hour_size . '"';
}
$_html_hours .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($hour_empty) || isset($all_empty)) {
$_html_hours .= '<option value="">' . (isset($hour_empty) ? $hour_empty : $all_empty) . '</option>' .
$option_separator;
}
$start = $use_24_hours ? 0 : 1;
$end = $use_24_hours ? 23 : 12;
for ($i = $start; $i <= $end; $i ++) {
$_val = sprintf('%02d', $i);
$_text = $hour_format === '%02d' ? $_val : sprintf($hour_format, $i);
$_value = $hour_value_format === '%02d' ? $_val : sprintf($hour_value_format, $i);
if (!$use_24_hours) {
$_hour12 = $_hour == 0 ? 12 : ($_hour <= 12 ? $_hour : $_hour - 12);
}
$selected = $_hour !== null ? ($use_24_hours ? $_hour == $_val : $_hour12 == $_val) : null;
$_html_hours .= '<option value="' . $_value . '"' . ($selected ? ' selected="selected"' : '') . '>' .
$_text . '</option>' . $option_separator;
}
$_html_hours .= '</select>';
}
// generate minute <select>
if ($display_minutes) {
$_html_minutes = '';
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Minute]') : ($prefix . 'Minute');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($minute_extra) {
$_extra .= ' ' . $minute_extra;
}
$_html_minutes = '<select name="' . $_name . '"';
if ($minute_id !== null || $all_id !== null) {
$_html_minutes .= ' id="' . smarty_function_escape_special_chars($minute_id !== null ?
($minute_id ? $minute_id : $_name) :
($all_id ? ($all_id . $_name) :
$_name)) . '"';
}
if ($minute_size) {
$_html_minutes .= ' size="' . $minute_size . '"';
}
$_html_minutes .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($minute_empty) || isset($all_empty)) {
$_html_minutes .= '<option value="">' . (isset($minute_empty) ? $minute_empty : $all_empty) . '</option>' .
$option_separator;
}
$selected = $_minute !== null ? ($_minute - $_minute % $minute_interval) : null;
for ($i = 0; $i <= 59; $i += $minute_interval) {
$_val = sprintf('%02d', $i);
$_text = $minute_format === '%02d' ? $_val : sprintf($minute_format, $i);
$_value = $minute_value_format === '%02d' ? $_val : sprintf($minute_value_format, $i);
$_html_minutes .= '<option value="' . $_value . '"' . ($selected === $i ? ' selected="selected"' : '') .
'>' . $_text . '</option>' . $option_separator;
}
$_html_minutes .= '</select>';
}
// generate second <select>
if ($display_seconds) {
$_html_seconds = '';
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Second]') : ($prefix . 'Second');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($second_extra) {
$_extra .= ' ' . $second_extra;
}
$_html_seconds = '<select name="' . $_name . '"';
if ($second_id !== null || $all_id !== null) {
$_html_seconds .= ' id="' . smarty_function_escape_special_chars($second_id !== null ?
($second_id ? $second_id : $_name) :
($all_id ? ($all_id . $_name) :
$_name)) . '"';
}
if ($second_size) {
$_html_seconds .= ' size="' . $second_size . '"';
}
$_html_seconds .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($second_empty) || isset($all_empty)) {
$_html_seconds .= '<option value="">' . (isset($second_empty) ? $second_empty : $all_empty) . '</option>' .
$option_separator;
}
$selected = $_second !== null ? ($_second - $_second % $second_interval) : null;
for ($i = 0; $i <= 59; $i += $second_interval) {
$_val = sprintf('%02d', $i);
$_text = $second_format === '%02d' ? $_val : sprintf($second_format, $i);
$_value = $second_value_format === '%02d' ? $_val : sprintf($second_value_format, $i);
$_html_seconds .= '<option value="' . $_value . '"' . ($selected === $i ? ' selected="selected"' : '') .
'>' . $_text . '</option>' . $option_separator;
}
$_html_seconds .= '</select>';
}
// generate meridian <select>
if ($display_meridian && !$use_24_hours) {
$_html_meridian = '';
$_extra = '';
$_name = $field_array ? ($field_array . '[' . $prefix . 'Meridian]') : ($prefix . 'Meridian');
if ($all_extra) {
$_extra .= ' ' . $all_extra;
}
if ($meridian_extra) {
$_extra .= ' ' . $meridian_extra;
}
$_html_meridian = '<select name="' . $_name . '"';
if ($meridian_id !== null || $all_id !== null) {
$_html_meridian .= ' id="' . smarty_function_escape_special_chars($meridian_id !== null ?
($meridian_id ? $meridian_id :
$_name) :
($all_id ? ($all_id . $_name) :
$_name)) . '"';
}
if ($meridian_size) {
$_html_meridian .= ' size="' . $meridian_size . '"';
}
$_html_meridian .= $_extra . $extra_attrs . '>' . $option_separator;
if (isset($meridian_empty) || isset($all_empty)) {
$_html_meridian .= '<option value="">' . (isset($meridian_empty) ? $meridian_empty : $all_empty) .
'</option>' . $option_separator;
}
$_html_meridian .= '<option value="am"' . ($_hour > 0 && $_hour < 12 ? ' selected="selected"' : '') .
'>AM</option>' . $option_separator . '<option value="pm"' .
($_hour < 12 ? '' : ' selected="selected"') . '>PM</option>' . $option_separator .
'</select>';
}
$_html = '';
foreach (array('_html_hours',
'_html_minutes',
'_html_seconds',
'_html_meridian') as $k) {
if (isset($$k)) {
if ($_html) {
$_html .= $field_separator;
}
$_html .= $$k;
}
}
return $_html;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.count_paragraphs.php | Extend/Package/smarty/plugins/modifiercompiler.count_paragraphs.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty count_paragraphs modifier plugin
* Type: modifier
* Name: count_paragraphs
* Purpose: count the number of paragraphs in a text
*
* @link http://www.smarty.net/manual/en/language.modifier.count.paragraphs.php
* count_paragraphs (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_count_paragraphs($params)
{
// count \r or \n characters
return '(preg_match_all(\'#[\r\n]+#\', ' . $params[ 0 ] . ', $tmp)+1)';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.indent.php | Extend/Package/smarty/plugins/modifiercompiler.indent.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty indent modifier plugin
* Type: modifier
* Name: indent
* Purpose: indent lines of text
*
* @link http://www.smarty.net/manual/en/language.modifier.indent.php indent (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_indent($params)
{
if (!isset($params[ 1 ])) {
$params[ 1 ] = 4;
}
if (!isset($params[ 2 ])) {
$params[ 2 ] = "' '";
}
return 'preg_replace(\'!^!m\',str_repeat(' . $params[ 2 ] . ',' . $params[ 1 ] . '),' . $params[ 0 ] . ')';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.mailto.php | Extend/Package/smarty/plugins/function.mailto.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {mailto} function plugin
* Type: function
* Name: mailto
* Date: May 21, 2002
* Purpose: automate mailto address link creation, and optionally encode them.
* Params:
*
* - address - (required) - e-mail address
* - text - (optional) - text to display, default is address
* - encode - (optional) - can be one of:
* * none : no encoding (default)
* * javascript : encode with javascript
* * javascript_charcode : encode with javascript charcode
* * hex : encode with hexadecimal (no javascript)
* - cc - (optional) - address(es) to carbon copy
* - bcc - (optional) - address(es) to blind carbon copy
* - subject - (optional) - e-mail subject
* - newsgroups - (optional) - newsgroup(s) to post to
* - followupto - (optional) - address(es) to follow up to
* - extra - (optional) - extra tags for the href link
*
* Examples:
*
* {mailto address="me@domain.com"}
* {mailto address="me@domain.com" encode="javascript"}
* {mailto address="me@domain.com" encode="hex"}
* {mailto address="me@domain.com" subject="Hello to you!"}
* {mailto address="me@domain.com" cc="you@domain.com,they@domain.com"}
* {mailto address="me@domain.com" extra='class="mailto"'}
*
*
* @link http://www.smarty.net/manual/en/language.function.mailto.php {mailto}
* (Smarty online manual)
* @version 1.2
* @author Monte Ohrt <monte at ohrt dot com>
* @author credits to Jason Sweat (added cc, bcc and subject functionality)
*
* @param array $params parameters
*
* @return string
*/
function smarty_function_mailto($params)
{
static $_allowed_encoding =
array('javascript' => true, 'javascript_charcode' => true, 'hex' => true, 'none' => true);
$extra = '';
if (empty($params[ 'address' ])) {
trigger_error("mailto: missing 'address' parameter", E_USER_WARNING);
return;
} else {
$address = $params[ 'address' ];
}
$text = $address;
// netscape and mozilla do not decode %40 (@) in BCC field (bug?)
// so, don't encode it.
$search = array('%40', '%2C');
$replace = array('@', ',');
$mail_parms = array();
foreach ($params as $var => $value) {
switch ($var) {
case 'cc':
case 'bcc':
case 'followupto':
if (!empty($value)) {
$mail_parms[] = $var . '=' . str_replace($search, $replace, rawurlencode($value));
}
break;
case 'subject':
case 'newsgroups':
$mail_parms[] = $var . '=' . rawurlencode($value);
break;
case 'extra':
case 'text':
$$var = $value;
default:
}
}
if ($mail_parms) {
$address .= '?' . join('&', $mail_parms);
}
$encode = (empty($params[ 'encode' ])) ? 'none' : $params[ 'encode' ];
if (!isset($_allowed_encoding[ $encode ])) {
trigger_error("mailto: 'encode' parameter must be none, javascript, javascript_charcode or hex",
E_USER_WARNING);
return;
}
// FIXME: (rodneyrehm) document.write() excues me what? 1998 has passed!
if ($encode === 'javascript') {
$string = 'document.write(\'<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>\');';
$js_encode = '';
for ($x = 0, $_length = strlen($string); $x < $_length; $x ++) {
$js_encode .= '%' . bin2hex($string[ $x ]);
}
return '<script type="text/javascript">eval(unescape(\'' . $js_encode . '\'))</script>';
} elseif ($encode === 'javascript_charcode') {
$string = '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>';
for ($x = 0, $y = strlen($string); $x < $y; $x ++) {
$ord[] = ord($string[ $x ]);
}
$_ret = "<script type=\"text/javascript\" language=\"javascript\">\n" . "{document.write(String.fromCharCode(" .
implode(',', $ord) . "))" . "}\n" . "</script>\n";
return $_ret;
} elseif ($encode === 'hex') {
preg_match('!^(.*)(\?.*)$!', $address, $match);
if (!empty($match[ 2 ])) {
trigger_error("mailto: hex encoding does not work with extra attributes. Try javascript.", E_USER_WARNING);
return;
}
$address_encode = '';
for ($x = 0, $_length = strlen($address); $x < $_length; $x ++) {
if (preg_match('!\w!' . Smarty::$_UTF8_MODIFIER, $address[ $x ])) {
$address_encode .= '%' . bin2hex($address[ $x ]);
} else {
$address_encode .= $address[ $x ];
}
}
$text_encode = '';
for ($x = 0, $_length = strlen($text); $x < $_length; $x ++) {
$text_encode .= '&#x' . bin2hex($text[ $x ]) . ';';
}
$mailto = "mailto:";
return '<a href="' . $mailto . $address_encode . '" ' . $extra . '>' . $text_encode . '</a>';
} else {
// no encoding
return '<a href="mailto:' . $address . '" ' . $extra . '>' . $text . '</a>';
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.unescape.php | Extend/Package/smarty/plugins/modifiercompiler.unescape.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty unescape modifier plugin
* Type: modifier
* Name: unescape
* Purpose: unescape html entities
*
* @author Rodney Rehm
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_unescape($params)
{
if (!isset($params[ 1 ])) {
$params[ 1 ] = 'html';
}
if (!isset($params[ 2 ])) {
$params[ 2 ] = '\'' . addslashes(Smarty::$_CHARSET) . '\'';
} else {
$params[ 2 ] = "'{$params[ 2 ]}'";
}
switch (trim($params[ 1 ], '"\'')) {
case 'entity':
case 'htmlall':
if (Smarty::$_MBSTRING) {
return 'mb_convert_encoding(' . $params[ 0 ] . ', ' . $params[ 2 ] . ', \'HTML-ENTITIES\')';
}
return 'html_entity_decode(' . $params[ 0 ] . ', ENT_NOQUOTES, ' . $params[ 2 ] . ')';
case 'html':
return 'htmlspecialchars_decode(' . $params[ 0 ] . ', ENT_QUOTES)';
case 'url':
return 'rawurldecode(' . $params[ 0 ] . ')';
default:
return $params[ 0 ];
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/variablefilter.htmlspecialchars.php | Extend/Package/smarty/plugins/variablefilter.htmlspecialchars.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFilter
*/
/**
* Smarty htmlspecialchars variablefilter plugin
*
* @param string $source input string
* @param \Smarty_Internal_Template $template
*
* @return string filtered output
*/
function smarty_variablefilter_htmlspecialchars($source, Smarty_Internal_Template $template)
{
return htmlspecialchars($source, ENT_QUOTES, Smarty::$_CHARSET);
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.lower.php | Extend/Package/smarty/plugins/modifiercompiler.lower.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty lower modifier plugin
* Type: modifier
* Name: lower
* Purpose: convert string to lowercase
*
* @link http://www.smarty.net/manual/en/language.modifier.lower.php lower (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_lower($params)
{
if (Smarty::$_MBSTRING) {
return 'mb_strtolower(' . $params[ 0 ] . ', \'' . addslashes(Smarty::$_CHARSET) . '\')';
}
// no MBString fallback
return 'strtolower(' . $params[ 0 ] . ')';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.html_table.php | Extend/Package/smarty/plugins/function.html_table.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {html_table} function plugin
* Type: function
* Name: html_table
* Date: Feb 17, 2003
* Purpose: make an html table from an array of data
* Params:
*
* - loop - array to loop through
* - cols - number of columns, comma separated list of column names
* or array of column names
* - rows - number of rows
* - table_attr - table attributes
* - th_attr - table heading attributes (arrays are cycled)
* - tr_attr - table row attributes (arrays are cycled)
* - td_attr - table cell attributes (arrays are cycled)
* - trailpad - value to pad trailing cells with
* - caption - text for caption element
* - vdir - vertical direction (default: "down", means top-to-bottom)
* - hdir - horizontal direction (default: "right", means left-to-right)
* - inner - inner loop (default "cols": print $loop line by line,
* $loop will be printed column by column otherwise)
*
* Examples:
*
* {table loop=$data}
* {table loop=$data cols=4 tr_attr='"bgcolor=red"'}
* {table loop=$data cols="first,second,third" tr_attr=$colors}
*
*
* @author Monte Ohrt <monte at ohrt dot com>
* @author credit to Messju Mohr <messju at lammfellpuschen dot de>
* @author credit to boots <boots dot smarty at yahoo dot com>
* @version 1.1
* @link http://www.smarty.net/manual/en/language.function.html.table.php {html_table}
* (Smarty online manual)
*
* @param array $params parameters
*
* @return string
*/
function smarty_function_html_table($params)
{
$table_attr = 'border="1"';
$tr_attr = '';
$th_attr = '';
$td_attr = '';
$cols = $cols_count = 3;
$rows = 3;
$trailpad = ' ';
$vdir = 'down';
$hdir = 'right';
$inner = 'cols';
$caption = '';
$loop = null;
if (!isset($params[ 'loop' ])) {
trigger_error("html_table: missing 'loop' parameter", E_USER_WARNING);
return;
}
foreach ($params as $_key => $_value) {
switch ($_key) {
case 'loop':
$$_key = (array) $_value;
break;
case 'cols':
if (is_array($_value) && !empty($_value)) {
$cols = $_value;
$cols_count = count($_value);
} elseif (!is_numeric($_value) && is_string($_value) && !empty($_value)) {
$cols = explode(',', $_value);
$cols_count = count($cols);
} elseif (!empty($_value)) {
$cols_count = (int) $_value;
} else {
$cols_count = $cols;
}
break;
case 'rows':
$$_key = (int) $_value;
break;
case 'table_attr':
case 'trailpad':
case 'hdir':
case 'vdir':
case 'inner':
case 'caption':
$$_key = (string) $_value;
break;
case 'tr_attr':
case 'td_attr':
case 'th_attr':
$$_key = $_value;
break;
}
}
$loop_count = count($loop);
if (empty($params[ 'rows' ])) {
/* no rows specified */
$rows = ceil($loop_count / $cols_count);
} elseif (empty($params[ 'cols' ])) {
if (!empty($params[ 'rows' ])) {
/* no cols specified, but rows */
$cols_count = ceil($loop_count / $rows);
}
}
$output = "<table $table_attr>\n";
if (!empty($caption)) {
$output .= '<caption>' . $caption . "</caption>\n";
}
if (is_array($cols)) {
$cols = ($hdir === 'right') ? $cols : array_reverse($cols);
$output .= "<thead><tr>\n";
for ($r = 0; $r < $cols_count; $r ++) {
$output .= '<th' . smarty_function_html_table_cycle('th', $th_attr, $r) . '>';
$output .= $cols[ $r ];
$output .= "</th>\n";
}
$output .= "</tr></thead>\n";
}
$output .= "<tbody>\n";
for ($r = 0; $r < $rows; $r ++) {
$output .= "<tr" . smarty_function_html_table_cycle('tr', $tr_attr, $r) . ">\n";
$rx = ($vdir === 'down') ? $r * $cols_count : ($rows - 1 - $r) * $cols_count;
for ($c = 0; $c < $cols_count; $c ++) {
$x = ($hdir === 'right') ? $rx + $c : $rx + $cols_count - 1 - $c;
if ($inner !== 'cols') {
/* shuffle x to loop over rows*/
$x = floor($x / $cols_count) + ($x % $cols_count) * $rows;
}
if ($x < $loop_count) {
$output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">" . $loop[ $x ] . "</td>\n";
} else {
$output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">$trailpad</td>\n";
}
}
$output .= "</tr>\n";
}
$output .= "</tbody>\n";
$output .= "</table>\n";
return $output;
}
/**
* @param $name
* @param $var
* @param $no
*
* @return string
*/
function smarty_function_html_table_cycle($name, $var, $no)
{
if (!is_array($var)) {
$ret = $var;
} else {
$ret = $var[ $no % count($var) ];
}
return ($ret) ? ' ' . $ret : '';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifier.date_format.php | Extend/Package/smarty/plugins/modifier.date_format.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty date_format modifier plugin
* Type: modifier
* Name: date_format
* Purpose: format datestamps via strftime
* Input:
* - string: input date string
* - format: strftime format for output
* - default_date: default date if $string is empty
*
* @link http://www.smarty.net/manual/en/language.modifier.date.format.php date_format (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input date string
* @param string $format strftime format for output
* @param string $default_date default date if $string is empty
* @param string $formatter either 'strftime' or 'auto'
*
* @return string |void
* @uses smarty_make_timestamp()
*/
function smarty_modifier_date_format($string, $format = null, $default_date = '', $formatter = 'auto')
{
if ($format === null) {
$format = Smarty::$_DATE_FORMAT;
}
/**
* require_once the {@link shared.make_timestamp.php} plugin
*/
static $is_loaded = false;
if (!$is_loaded) {
if (!is_callable('smarty_make_timestamp')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.make_timestamp.php');
}
$is_loaded = true;
}
if ($string !== '' && $string !== '0000-00-00' && $string !== '0000-00-00 00:00:00') {
$timestamp = smarty_make_timestamp($string);
} elseif ($default_date !== '') {
$timestamp = smarty_make_timestamp($default_date);
} else {
return;
}
if ($formatter === 'strftime' || ($formatter === 'auto' && strpos($format, '%') !== false)) {
if (Smarty::$_IS_WINDOWS) {
$_win_from = array('%D',
'%h',
'%n',
'%r',
'%R',
'%t',
'%T');
$_win_to = array('%m/%d/%y',
'%b',
"\n",
'%I:%M:%S %p',
'%H:%M',
"\t",
'%H:%M:%S');
if (strpos($format, '%e') !== false) {
$_win_from[] = '%e';
$_win_to[] = sprintf('%\' 2d', date('j', $timestamp));
}
if (strpos($format, '%l') !== false) {
$_win_from[] = '%l';
$_win_to[] = sprintf('%\' 2d', date('h', $timestamp));
}
$format = str_replace($_win_from, $_win_to, $format);
}
return strftime($format, $timestamp);
} else {
return date($format, $timestamp);
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.strip.php | Extend/Package/smarty/plugins/modifiercompiler.strip.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty strip modifier plugin
* Type: modifier
* Name: strip
* Purpose: Replace all repeated spaces, newlines, tabs
* with a single space or supplied replacement string.
* Example: {$var|strip} {$var|strip:" "}
* Date: September 25th, 2002
*
* @link http://www.smarty.net/manual/en/language.modifier.strip.php strip (Smarty online manual)
* @author Uwe Tews
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_strip($params)
{
if (!isset($params[ 1 ])) {
$params[ 1 ] = "' '";
}
return "preg_replace('!\s+!" . Smarty::$_UTF8_MODIFIER . "', {$params[1]},{$params[0]})";
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.from_charset.php | Extend/Package/smarty/plugins/modifiercompiler.from_charset.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty from_charset modifier plugin
* Type: modifier
* Name: from_charset
* Purpose: convert character encoding from $charset to internal encoding
*
* @author Rodney Rehm
*
* @param array $params parameters
*
* @return string with compiled code
*/
function smarty_modifiercompiler_from_charset($params)
{
if (!Smarty::$_MBSTRING) {
// FIXME: (rodneyrehm) shouldn't this throw an error?
return $params[ 0 ];
}
if (!isset($params[ 1 ])) {
$params[ 1 ] = '"ISO-8859-1"';
}
return 'mb_convert_encoding(' . $params[ 0 ] . ', "' . addslashes(Smarty::$_CHARSET) . '", ' . $params[ 1 ] . ')';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/outputfilter.trimwhitespace.php | Extend/Package/smarty/plugins/outputfilter.trimwhitespace.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFilter
*/
/**
* Smarty trimwhitespace outputfilter plugin
* Trim unnecessary whitespace from HTML markup.
*
* @author Rodney Rehm
*
* @param string $source input string
*
* @return string filtered output
* @todo substr_replace() is not overloaded by mbstring.func_overload - so this function might fail!
*/
function smarty_outputfilter_trimwhitespace($source)
{
$store = array();
$_store = 0;
$_offset = 0;
// Unify Line-Breaks to \n
$source = preg_replace('/\015\012|\015|\012/', "\n", $source);
// capture Internet Explorer and KnockoutJS Conditional Comments
if (preg_match_all('#<!--((\[[^\]]+\]>.*?<!\[[^\]]+\])|(\s*/?ko\s+.+))-->#is', $source, $matches,
PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
foreach ($matches as $match) {
$store[] = $match[ 0 ][ 0 ];
$_length = strlen($match[ 0 ][ 0 ]);
$replace = '@!@SMARTY:' . $_store . ':SMARTY@!@';
$source = substr_replace($source, $replace, $match[ 0 ][ 1 ] - $_offset, $_length);
$_offset += $_length - strlen($replace);
$_store ++;
}
}
// Strip all HTML-Comments
// yes, even the ones in <script> - see http://stackoverflow.com/a/808850/515124
$source = preg_replace('#<!--.*?-->#ms', '', $source);
// capture html elements not to be messed with
$_offset = 0;
if (preg_match_all('#(<script[^>]*>.*?</script[^>]*>)|(<textarea[^>]*>.*?</textarea[^>]*>)|(<pre[^>]*>.*?</pre[^>]*>)#is',
$source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
foreach ($matches as $match) {
$store[] = $match[ 0 ][ 0 ];
$_length = strlen($match[ 0 ][ 0 ]);
$replace = '@!@SMARTY:' . $_store . ':SMARTY@!@';
$source = substr_replace($source, $replace, $match[ 0 ][ 1 ] - $_offset, $_length);
$_offset += $_length - strlen($replace);
$_store ++;
}
}
$expressions = array(// replace multiple spaces between tags by a single space
// can't remove them entirely, becaue that might break poorly implemented CSS display:inline-block elements
'#(:SMARTY@!@|>)\s+(?=@!@SMARTY:|<)#s' => '\1 \2',
// remove spaces between attributes (but not in attribute values!)
'#(([a-z0-9]\s*=\s*("[^"]*?")|(\'[^\']*?\'))|<[a-z0-9_]+)\s+([a-z/>])#is' => '\1 \5',
// note: for some very weird reason trim() seems to remove spaces inside attributes.
// maybe a \0 byte or something is interfering?
'#^\s+<#Ss' => '<', '#>\s+$#Ss' => '>',);
$source = preg_replace(array_keys($expressions), array_values($expressions), $source);
// note: for some very weird reason trim() seems to remove spaces inside attributes.
// maybe a \0 byte or something is interfering?
// $source = trim( $source );
$_offset = 0;
if (preg_match_all('#@!@SMARTY:([0-9]+):SMARTY@!@#is', $source, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
foreach ($matches as $match) {
$_length = strlen($match[ 0 ][ 0 ]);
$replace = $store[ $match[ 1 ][ 0 ] ];
$source = substr_replace($source, $replace, $match[ 0 ][ 1 ] + $_offset, $_length);
$_offset += strlen($replace) - $_length;
$_store ++;
}
}
return $source;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.escape.php | Extend/Package/smarty/plugins/modifiercompiler.escape.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty escape modifier plugin
* Type: modifier
* Name: escape
* Purpose: escape string for output
*
* @link http://www.smarty.net/docsv2/en/language.modifier.escape count_characters (Smarty online manual)
* @author Rodney Rehm
*
* @param array $params parameters
* @param $compiler
*
* @return string with compiled code
*/
function smarty_modifiercompiler_escape($params, $compiler)
{
static $_double_encode = null;
static $is_loaded = false;
if (!$is_loaded) {
if (!is_callable('smarty_literal_compiler_param')) {
require_once(SMARTY_PLUGINS_DIR . 'shared.literal_compiler_param.php');
}
$is_loaded = true;
}
if ($_double_encode === null) {
$_double_encode = version_compare(PHP_VERSION, '5.2.3', '>=');
}
try {
$esc_type = smarty_literal_compiler_param($params, 1, 'html');
$char_set = smarty_literal_compiler_param($params, 2, Smarty::$_CHARSET);
$double_encode = smarty_literal_compiler_param($params, 3, true);
if (!$char_set) {
$char_set = Smarty::$_CHARSET;
}
switch ($esc_type) {
case 'html':
if ($_double_encode) {
return 'htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ', ' .
var_export($double_encode, true) . ')';
} elseif ($double_encode) {
return 'htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ')';
} else {
// fall back to modifier.escape.php
}
case 'htmlall':
if (Smarty::$_MBSTRING) {
if ($_double_encode) {
// php >=5.2.3 - go native
return 'mb_convert_encoding(htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' .
var_export($char_set, true) . ', ' . var_export($double_encode, true) .
'), "HTML-ENTITIES", ' . var_export($char_set, true) . ')';
} elseif ($double_encode) {
// php <5.2.3 - only handle double encoding
return 'mb_convert_encoding(htmlspecialchars(' . $params[ 0 ] . ', ENT_QUOTES, ' .
var_export($char_set, true) . '), "HTML-ENTITIES", ' . var_export($char_set, true) . ')';
} else {
// fall back to modifier.escape.php
}
}
// no MBString fallback
if ($_double_encode) {
// php >=5.2.3 - go native
return 'htmlentities(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ', ' .
var_export($double_encode, true) . ')';
} elseif ($double_encode) {
// php <5.2.3 - only handle double encoding
return 'htmlentities(' . $params[ 0 ] . ', ENT_QUOTES, ' . var_export($char_set, true) . ')';
} else {
// fall back to modifier.escape.php
}
case 'url':
return 'rawurlencode(' . $params[ 0 ] . ')';
case 'urlpathinfo':
return 'str_replace("%2F", "/", rawurlencode(' . $params[ 0 ] . '))';
case 'quotes':
// escape unescaped single quotes
return 'preg_replace("%(?<!\\\\\\\\)\'%", "\\\'",' . $params[ 0 ] . ')';
case 'javascript':
// escape quotes and backslashes, newlines, etc.
return 'strtr(' . $params[ 0 ] .
', array("\\\\" => "\\\\\\\\", "\'" => "\\\\\'", "\"" => "\\\\\"", "\\r" => "\\\\r", "\\n" => "\\\n", "</" => "<\/" ))';
}
}
catch (SmartyException $e) {
// pass through to regular plugin fallback
}
// could not optimize |escape call, so fallback to regular plugin
if ($compiler->template->caching && ($compiler->tag_nocache | $compiler->nocache)) {
$compiler->parent_compiler->template->compiled->required_plugins[ 'nocache' ][ 'escape' ][ 'modifier' ][ 'file' ] =
SMARTY_PLUGINS_DIR . 'modifier.escape.php';
$compiler->parent_compiler->template->compiled->required_plugins[ 'nocache' ][ 'escape' ][ 'modifier' ][ 'function' ] =
'smarty_modifier_escape';
} else {
$compiler->parent_compiler->template->compiled->required_plugins[ 'compiled' ][ 'escape' ][ 'modifier' ][ 'file' ] =
SMARTY_PLUGINS_DIR . 'modifier.escape.php';
$compiler->parent_compiler->template->compiled->required_plugins[ 'compiled' ][ 'escape' ][ 'modifier' ][ 'function' ] =
'smarty_modifier_escape';
}
return 'smarty_modifier_escape(' . join(', ', $params) . ')';
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifier.spacify.php | Extend/Package/smarty/plugins/modifier.spacify.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty spacify modifier plugin
* Type: modifier
* Name: spacify
* Purpose: add spaces between characters in a string
*
* @link http://smarty.php.net/manual/en/language.modifier.spacify.php spacify (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param string $spacify_char string to insert between characters.
*
* @return string
*/
function smarty_modifier_spacify($string, $spacify_char = ' ')
{
// well… what about charsets besides latin and UTF-8?
return implode($spacify_char, preg_split('//' . Smarty::$_UTF8_MODIFIER, $string, - 1, PREG_SPLIT_NO_EMPTY));
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/shared.mb_str_replace.php | Extend/Package/smarty/plugins/shared.mb_str_replace.php | <?php
/**
* Smarty shared plugin
*
* @package Smarty
* @subpackage PluginsShared
*/
if (!function_exists('smarty_mb_str_replace')) {
/**
* Multibyte string replace
*
* @param string|string[] $search the string to be searched
* @param string|string[] $replace the replacement string
* @param string $subject the source string
* @param int &$count number of matches found
*
* @return string replaced string
* @author Rodney Rehm
*/
function smarty_mb_str_replace($search, $replace, $subject, &$count = 0)
{
if (!is_array($search) && is_array($replace)) {
return false;
}
if (is_array($subject)) {
// call mb_replace for each single string in $subject
foreach ($subject as &$string) {
$string = smarty_mb_str_replace($search, $replace, $string, $c);
$count += $c;
}
} else if (is_array($search)) {
if (!is_array($replace)) {
foreach ($search as &$string) {
$subject = smarty_mb_str_replace($string, $replace, $subject, $c);
$count += $c;
}
} else {
$n = max(count($search), count($replace));
while ($n--) {
$subject = smarty_mb_str_replace(current($search), current($replace), $subject, $c);
$count += $c;
next($search);
next($replace);
}
}
} else {
$parts = mb_split(preg_quote($search), $subject);
$count = count($parts) - 1;
$subject = implode($replace, $parts);
}
return $subject;
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifier.truncate.php | Extend/Package/smarty/plugins/modifier.truncate.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifier
*/
/**
* Smarty truncate modifier plugin
* Type: modifier
* Name: truncate
* Purpose: Truncate a string to a certain length if necessary,
* optionally splitting in the middle of a word, and
* appending the $etc string or inserting $etc into the middle.
*
* @link http://smarty.php.net/manual/en/language.modifier.truncate.php truncate (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param string $string input string
* @param integer $length length of truncated text
* @param string $etc end string
* @param boolean $break_words truncate at word boundary
* @param boolean $middle truncate in the middle of text
*
* @return string truncated string
*/
function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false)
{
if ($length === 0) {
return '';
}
if (Smarty::$_MBSTRING) {
if (mb_strlen($string, Smarty::$_CHARSET) > $length) {
$length -= min($length, mb_strlen($etc, Smarty::$_CHARSET));
if (!$break_words && !$middle) {
$string = preg_replace('/\s+?(\S+)?$/' . Smarty::$_UTF8_MODIFIER, '',
mb_substr($string, 0, $length + 1, Smarty::$_CHARSET));
}
if (!$middle) {
return mb_substr($string, 0, $length, Smarty::$_CHARSET) . $etc;
}
return mb_substr($string, 0, $length / 2, Smarty::$_CHARSET) . $etc .
mb_substr($string, - $length / 2, $length, Smarty::$_CHARSET);
}
return $string;
}
// no MBString fallback
if (isset($string[ $length ])) {
$length -= min($length, strlen($etc));
if (!$break_words && !$middle) {
$string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length + 1));
}
if (!$middle) {
return substr($string, 0, $length) . $etc;
}
return substr($string, 0, $length / 2) . $etc . substr($string, - $length / 2);
}
return $string;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifiercompiler.noprint.php | Extend/Package/smarty/plugins/modifiercompiler.noprint.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsModifierCompiler
*/
/**
* Smarty noprint modifier plugin
* Type: modifier
* Name: noprint
* Purpose: return an empty string
*
* @author Uwe Tews
* @return string with compiled code
*/
function smarty_modifiercompiler_noprint()
{
return "''";
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.fetch.php | Extend/Package/smarty/plugins/function.fetch.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {fetch} plugin
* Type: function
* Name: fetch
* Purpose: fetch file, web or ftp data and display results
*
* @link http://www.smarty.net/manual/en/language.function.fetch.php {fetch}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @throws SmartyException
* @return string|null if the assign parameter is passed, Smarty assigns the result to a template variable
*/
function smarty_function_fetch($params, $template)
{
if (empty($params[ 'file' ])) {
trigger_error('[plugin] fetch parameter \'file\' cannot be empty', E_USER_NOTICE);
return;
}
// strip file protocol
if (stripos($params[ 'file' ], 'file://') === 0) {
$params[ 'file' ] = substr($params[ 'file' ], 7);
}
$protocol = strpos($params[ 'file' ], '://');
if ($protocol !== false) {
$protocol = strtolower(substr($params[ 'file' ], 0, $protocol));
}
if (isset($template->smarty->security_policy)) {
if ($protocol) {
// remote resource (or php stream, …)
if (!$template->smarty->security_policy->isTrustedUri($params[ 'file' ])) {
return;
}
} else {
// local file
if (!$template->smarty->security_policy->isTrustedResourceDir($params[ 'file' ])) {
return;
}
}
}
$content = '';
if ($protocol === 'http') {
// http fetch
if ($uri_parts = parse_url($params[ 'file' ])) {
// set defaults
$host = $server_name = $uri_parts[ 'host' ];
$timeout = 30;
$accept = 'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*';
$agent = 'Smarty Template Engine ' . Smarty::SMARTY_VERSION;
$referer = '';
$uri = !empty($uri_parts[ 'path' ]) ? $uri_parts[ 'path' ] : '/';
$uri .= !empty($uri_parts[ 'query' ]) ? '?' . $uri_parts[ 'query' ] : '';
$_is_proxy = false;
if (empty($uri_parts[ 'port' ])) {
$port = 80;
} else {
$port = $uri_parts[ 'port' ];
}
if (!empty($uri_parts[ 'user' ])) {
$user = $uri_parts[ 'user' ];
}
if (!empty($uri_parts[ 'pass' ])) {
$pass = $uri_parts[ 'pass' ];
}
// loop through parameters, setup headers
foreach ($params as $param_key => $param_value) {
switch ($param_key) {
case 'file':
case 'assign':
case 'assign_headers':
break;
case 'user':
if (!empty($param_value)) {
$user = $param_value;
}
break;
case 'pass':
if (!empty($param_value)) {
$pass = $param_value;
}
break;
case 'accept':
if (!empty($param_value)) {
$accept = $param_value;
}
break;
case 'header':
if (!empty($param_value)) {
if (!preg_match('![\w\d-]+: .+!', $param_value)) {
trigger_error("[plugin] invalid header format '{$param_value}'", E_USER_NOTICE);
return;
} else {
$extra_headers[] = $param_value;
}
}
break;
case 'proxy_host':
if (!empty($param_value)) {
$proxy_host = $param_value;
}
break;
case 'proxy_port':
if (!preg_match('!\D!', $param_value)) {
$proxy_port = (int) $param_value;
} else {
trigger_error("[plugin] invalid value for attribute '{$param_key }'", E_USER_NOTICE);
return;
}
break;
case 'agent':
if (!empty($param_value)) {
$agent = $param_value;
}
break;
case 'referer':
if (!empty($param_value)) {
$referer = $param_value;
}
break;
case 'timeout':
if (!preg_match('!\D!', $param_value)) {
$timeout = (int) $param_value;
} else {
trigger_error("[plugin] invalid value for attribute '{$param_key}'", E_USER_NOTICE);
return;
}
break;
default:
trigger_error("[plugin] unrecognized attribute '{$param_key}'", E_USER_NOTICE);
return;
}
}
if (!empty($proxy_host) && !empty($proxy_port)) {
$_is_proxy = true;
$fp = fsockopen($proxy_host, $proxy_port, $errno, $errstr, $timeout);
} else {
$fp = fsockopen($server_name, $port, $errno, $errstr, $timeout);
}
if (!$fp) {
trigger_error("[plugin] unable to fetch: $errstr ($errno)", E_USER_NOTICE);
return;
} else {
if ($_is_proxy) {
fputs($fp, 'GET ' . $params[ 'file' ] . " HTTP/1.0\r\n");
} else {
fputs($fp, "GET $uri HTTP/1.0\r\n");
}
if (!empty($host)) {
fputs($fp, "Host: $host\r\n");
}
if (!empty($accept)) {
fputs($fp, "Accept: $accept\r\n");
}
if (!empty($agent)) {
fputs($fp, "User-Agent: $agent\r\n");
}
if (!empty($referer)) {
fputs($fp, "Referer: $referer\r\n");
}
if (isset($extra_headers) && is_array($extra_headers)) {
foreach ($extra_headers as $curr_header) {
fputs($fp, $curr_header . "\r\n");
}
}
if (!empty($user) && !empty($pass)) {
fputs($fp, 'Authorization: BASIC ' . base64_encode("$user:$pass") . "\r\n");
}
fputs($fp, "\r\n");
while (!feof($fp)) {
$content .= fgets($fp, 4096);
}
fclose($fp);
$csplit = preg_split("!\r\n\r\n!", $content, 2);
$content = $csplit[ 1 ];
if (!empty($params[ 'assign_headers' ])) {
$template->assign($params[ 'assign_headers' ], preg_split("!\r\n!", $csplit[ 0 ]));
}
}
} else {
trigger_error("[plugin fetch] unable to parse URL, check syntax", E_USER_NOTICE);
return;
}
} else {
$content = @file_get_contents($params[ 'file' ]);
if ($content === false) {
throw new SmartyException("{fetch} cannot read resource '" . $params[ 'file' ] . "'");
}
}
if (!empty($params[ 'assign' ])) {
$template->assign($params[ 'assign' ], $content);
} else {
return $content;
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/modifier.debug_print_var.php | Extend/Package/smarty/plugins/modifier.debug_print_var.php | <?php
/**
* Smarty plugin
*
* @package Smarty
* @subpackage Debug
*/
/**
* Smarty debug_print_var modifier plugin
* Type: modifier
* Name: debug_print_var
* Purpose: formats variable contents for display in the console
*
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param array|object $var variable to be formatted
* @param int $max maximum recursion depth if $var is an array or object
* @param int $length maximum string length if $var is a string
* @param int $depth actual recursion depth
* @param array $objects processed objects in actual depth to prevent recursive object processing
*
* @return string
*/
function smarty_modifier_debug_print_var($var, $max = 10, $length = 40, $depth = 0, $objects = array())
{
$_replace = array("\n" => '\n', "\r" => '\r', "\t" => '\t');
switch (gettype($var)) {
case 'array' :
$results = '<b>Array (' . count($var) . ')</b>';
if ($depth === $max) {
break;
}
foreach ($var as $curr_key => $curr_val) {
$results .= '<br>' . str_repeat(' ', $depth * 2) . '<b>' . strtr($curr_key, $_replace) .
'</b> => ' .
smarty_modifier_debug_print_var($curr_val, $max, $length, ++ $depth, $objects);
$depth --;
}
break;
case 'object' :
$object_vars = get_object_vars($var);
$results = '<b>' . get_class($var) . ' Object (' . count($object_vars) . ')</b>';
if (in_array($var, $objects)) {
$results .= ' called recursive';
break;
}
if ($depth === $max) {
break;
}
$objects[] = $var;
foreach ($object_vars as $curr_key => $curr_val) {
$results .= '<br>' . str_repeat(' ', $depth * 2) . '<b> ->' . strtr($curr_key, $_replace) .
'</b> = ' . smarty_modifier_debug_print_var($curr_val, $max, $length, ++ $depth, $objects);
$depth --;
}
break;
case 'boolean' :
case 'NULL' :
case 'resource' :
if (true === $var) {
$results = 'true';
} elseif (false === $var) {
$results = 'false';
} elseif (null === $var) {
$results = 'null';
} else {
$results = htmlspecialchars((string) $var);
}
$results = '<i>' . $results . '</i>';
break;
case 'integer' :
case 'float' :
$results = htmlspecialchars((string) $var);
break;
case 'string' :
$results = strtr($var, $_replace);
if (Smarty::$_MBSTRING) {
if (mb_strlen($var, Smarty::$_CHARSET) > $length) {
$results = mb_substr($var, 0, $length - 3, Smarty::$_CHARSET) . '...';
}
} else {
if (isset($var[ $length ])) {
$results = substr($var, 0, $length - 3) . '...';
}
}
$results = htmlspecialchars('"' . $results . '"', ENT_QUOTES, Smarty::$_CHARSET);
break;
case 'unknown type' :
default :
$results = strtr((string) $var, $_replace);
if (Smarty::$_MBSTRING) {
if (mb_strlen($results, Smarty::$_CHARSET) > $length) {
$results = mb_substr($results, 0, $length - 3, Smarty::$_CHARSET) . '...';
}
} else {
if (strlen($results) > $length) {
$results = substr($results, 0, $length - 3) . '...';
}
}
$results = htmlspecialchars($results, ENT_QUOTES, Smarty::$_CHARSET);
}
return $results;
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/plugins/function.math.php | Extend/Package/smarty/plugins/function.math.php | <?php
/**
* Smarty plugin
* This plugin is only for Smarty2 BC
*
* @package Smarty
* @subpackage PluginsFunction
*/
/**
* Smarty {math} function plugin
* Type: function
* Name: math
* Purpose: handle math computations in template
*
* @link http://www.smarty.net/manual/en/language.function.math.php {math}
* (Smarty online manual)
* @author Monte Ohrt <monte at ohrt dot com>
*
* @param array $params parameters
* @param Smarty_Internal_Template $template template object
*
* @return string|null
*/
function smarty_function_math($params, $template)
{
static $_allowed_funcs =
array('int' => true, 'abs' => true, 'ceil' => true, 'cos' => true, 'exp' => true, 'floor' => true,
'log' => true, 'log10' => true, 'max' => true, 'min' => true, 'pi' => true, 'pow' => true, 'rand' => true,
'round' => true, 'sin' => true, 'sqrt' => true, 'srand' => true, 'tan' => true);
// be sure equation parameter is present
if (empty($params[ 'equation' ])) {
trigger_error("math: missing equation parameter", E_USER_WARNING);
return;
}
$equation = $params[ 'equation' ];
// make sure parenthesis are balanced
if (substr_count($equation, '(') !== substr_count($equation, ')')) {
trigger_error("math: unbalanced parenthesis", E_USER_WARNING);
return;
}
// disallow backticks
if (strpos($equation, '`') !== false) {
trigger_error("math: backtick character not allowed in equation", E_USER_WARNING);
return;
}
// also disallow dollar signs
if (strpos($equation, '$') !== false) {
trigger_error("math: dollar signs not allowed in equation", E_USER_WARNING);
return;
}
foreach ($params as $key => $val) {
if ($key !== 'equation' && $key !== 'format' && $key !== 'assign') {
// make sure value is not empty
if (strlen($val) === 0) {
trigger_error("math: parameter '{$key}' is empty", E_USER_WARNING);
return;
}
if (!is_numeric($val)) {
trigger_error("math: parameter '{$key}' is not numeric", E_USER_WARNING);
return;
}
}
}
// match all vars in equation, make sure all are passed
preg_match_all('!(?:0x[a-fA-F0-9]+)|([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)!', $equation, $match);
foreach ($match[ 1 ] as $curr_var) {
if ($curr_var && !isset($params[ $curr_var ]) && !isset($_allowed_funcs[ $curr_var ])) {
trigger_error("math: function call '{$curr_var}' not allowed, or missing parameter '{$curr_var}'", E_USER_WARNING);
return;
}
}
foreach ($params as $key => $val) {
if ($key !== 'equation' && $key !== 'format' && $key !== 'assign') {
$equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation);
}
}
$smarty_math_result = null;
eval("\$smarty_math_result = " . $equation . ";");
if (empty($params[ 'format' ])) {
if (empty($params[ 'assign' ])) {
return $smarty_math_result;
} else {
$template->assign($params[ 'assign' ], $smarty_math_result);
}
} else {
if (empty($params[ 'assign' ])) {
printf($params[ 'format' ], $smarty_math_result);
} else {
$template->assign($params[ 'assign' ], sprintf($params[ 'format' ], $smarty_math_result));
}
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_getconfigvars.php | Extend/Package/smarty/sysplugins/smarty_internal_method_getconfigvars.php | <?php
/**
* Smarty Method GetConfigVars
*
* Smarty::getConfigVars() method
*
* @package Smarty
* @subpackage PluginsInternal
* @author Uwe Tews
*/
class Smarty_Internal_Method_GetConfigVars
{
/**
* Valid for all objects
*
* @var int
*/
public $objMap = 7;
/**
* Returns a single or all config variables
*
* @api Smarty::getConfigVars()
* @link http://www.smarty.net/docs/en/api.get.config.vars.tpl
*
* @param \Smarty_Internal_Data|\Smarty_Internal_Template|\Smarty $data
* @param string $varname variable name or null
* @param bool $search_parents include parent templates?
*
* @return mixed variable value or or array of variables
*/
public function getConfigVars(Smarty_Internal_Data $data, $varname = null, $search_parents = true)
{
$_ptr = $data;
$var_array = array();
while ($_ptr !== null) {
if (isset($varname)) {
if (isset($_ptr->config_vars[ $varname ])) {
return $_ptr->config_vars[ $varname ];
}
} else {
$var_array = array_merge($_ptr->config_vars, $var_array);
}
// not found, try at parent
if ($search_parents) {
$_ptr = $_ptr->parent;
} else {
$_ptr = null;
}
}
if (isset($varname)) {
return '';
} else {
return $var_array;
}
}
} | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_compile_private_object_block_function.php | Extend/Package/smarty/sysplugins/smarty_internal_compile_private_object_block_function.php | <?php
/**
* Smarty Internal Plugin Compile Object Block Function
* Compiles code for registered objects as block function
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Object Block Function Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Private_Object_Block_Function extends Smarty_Internal_Compile_Private_Block_Plugin
{
/**
* Setup callback and parameter array
*
* @param \Smarty_Internal_TemplateCompilerBase $compiler
* @param array $_attr attributes
* @param string $tag
* @param string $method
*
* @return array
*/
public function setup(Smarty_Internal_TemplateCompilerBase $compiler, $_attr, $tag, $method)
{
$_paramsArray = array();
foreach ($_attr as $_key => $_value) {
if (is_int($_key)) {
$_paramsArray[] = "$_key=>$_value";
} else {
$_paramsArray[] = "'$_key'=>$_value";
}
}
$callback = array("\$_smarty_tpl->smarty->registered_objects['{$tag}'][0]", "->{$method}");
return array($callback, $_paramsArray, "array(\$_block_plugin{$this->nesting}, '{$method}')");
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_compile_shared_inheritance.php | Extend/Package/smarty/sysplugins/smarty_internal_compile_shared_inheritance.php | <?php
/**
* Smarty Internal Plugin Compile Shared Inheritance
* Shared methods for {extends} and {block} tags
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Shared Inheritance Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Shared_Inheritance extends Smarty_Internal_CompileBase
{
/**
* Compile inheritance initialization code as prefix
*
* @param \Smarty_Internal_TemplateCompilerBase $compiler
* @param bool|false $initChildSequence if true force child template
*/
static function postCompile(Smarty_Internal_TemplateCompilerBase $compiler, $initChildSequence = false)
{
$compiler->prefixCompiledCode .= "<?php \$_smarty_tpl->_loadInheritance();\n\$_smarty_tpl->inheritance->init(\$_smarty_tpl, " .
var_export($initChildSequence, true) . ");\n?>\n";
}
/**
* Register post compile callback to compile inheritance initialization code
*
* @param \Smarty_Internal_TemplateCompilerBase $compiler
* @param bool|false $initChildSequence if true force child template
*/
public function registerInit(Smarty_Internal_TemplateCompilerBase $compiler, $initChildSequence = false)
{
if ($initChildSequence || !isset($compiler->_cache['inheritanceInit'])) {
$compiler->registerPostCompileCallback(array('Smarty_Internal_Compile_Shared_Inheritance', 'postCompile'),
array($initChildSequence),
'inheritanceInit',
$initChildSequence);
$compiler->_cache['inheritanceInit'] = true;
}
}
} | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_loadfilter.php | Extend/Package/smarty/sysplugins/smarty_internal_method_loadfilter.php | <?php
/**
* Smarty Method LoadFilter
*
* Smarty::loadFilter() method
*
* @package Smarty
* @subpackage PluginsInternal
* @author Uwe Tews
*/
class Smarty_Internal_Method_LoadFilter
{
/**
* Valid for Smarty and template object
*
* @var int
*/
public $objMap = 3;
/**
* Valid filter types
*
* @var array
*/
private $filterTypes = array('pre' => true, 'post' => true, 'output' => true, 'variable' => true);
/**
* load a filter of specified type and name
*
* @api Smarty::loadFilter()
*
* @link http://www.smarty.net/docs/en/api.load.filter.tpl
*
* @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj
* @param string $type filter type
* @param string $name filter name
*
* @return bool
* @throws SmartyException if filter could not be loaded
*/
public function loadFilter(Smarty_Internal_TemplateBase $obj, $type, $name)
{
$smarty = $obj->_getSmartyObj();
$this->_checkFilterType($type);
$_plugin = "smarty_{$type}filter_{$name}";
$_filter_name = $_plugin;
if (is_callable($_plugin)) {
$smarty->registered_filters[ $type ][ $_filter_name ] = $_plugin;
return true;
}
if ($smarty->loadPlugin($_plugin)) {
if (class_exists($_plugin, false)) {
$_plugin = array($_plugin, 'execute');
}
if (is_callable($_plugin)) {
$smarty->registered_filters[ $type ][ $_filter_name ] = $_plugin;
return true;
}
}
throw new SmartyException("{$type}filter '{$name}' not found or callable");
}
/**
* Check if filter type is valid
*
* @param string $type
*
* @throws \SmartyException
*/
public function _checkFilterType($type)
{
if (!isset($this->filterTypes[ $type ])) {
throw new SmartyException("Illegal filter type '{$type}'");
}
}
} | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_testinstall.php | Extend/Package/smarty/sysplugins/smarty_internal_testinstall.php | <?php
/**
* Smarty Internal TestInstall
* Test Smarty installation
*
* @package Smarty
* @subpackage Utilities
* @author Uwe Tews
*/
/**
* TestInstall class
*
* @package Smarty
* @subpackage Utilities
*/
class Smarty_Internal_TestInstall
{
/**
* diagnose Smarty setup
* If $errors is secified, the diagnostic report will be appended to the array, rather than being output.
*
* @param \Smarty $smarty
* @param array $errors array to push results into rather than outputting them
*
* @return bool status, true if everything is fine, false else
*/
public static function testInstall(Smarty $smarty, &$errors = null)
{
$status = true;
if ($errors === null) {
echo "<PRE>\n";
echo "Smarty Installation test...\n";
echo "Testing template directory...\n";
}
$_stream_resolve_include_path = function_exists('stream_resolve_include_path');
// test if all registered template_dir are accessible
foreach ($smarty->getTemplateDir() as $template_dir) {
$_template_dir = $template_dir;
$template_dir = realpath($template_dir);
// resolve include_path or fail existence
if (!$template_dir) {
if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_template_dir)) {
// try PHP include_path
if ($_stream_resolve_include_path) {
$template_dir = stream_resolve_include_path($_template_dir);
} else {
$template_dir = $smarty->ext->_getIncludePath->getIncludePath($_template_dir, null, $smarty);
}
if ($template_dir !== false) {
if ($errors === null) {
echo "$template_dir is OK.\n";
}
continue;
} else {
$status = false;
$message =
"FAILED: $_template_dir does not exist (and couldn't be found in include_path either)";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'template_dir' ] = $message;
}
continue;
}
} else {
$status = false;
$message = "FAILED: $_template_dir does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'template_dir' ] = $message;
}
continue;
}
}
if (!is_dir($template_dir)) {
$status = false;
$message = "FAILED: $template_dir is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'template_dir' ] = $message;
}
} else if (!is_readable($template_dir)) {
$status = false;
$message = "FAILED: $template_dir is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'template_dir' ] = $message;
}
} else {
if ($errors === null) {
echo "$template_dir is OK.\n";
}
}
}
if ($errors === null) {
echo "Testing compile directory...\n";
}
// test if registered compile_dir is accessible
$__compile_dir = $smarty->getCompileDir();
$_compile_dir = realpath($__compile_dir);
if (!$_compile_dir) {
$status = false;
$message = "FAILED: {$__compile_dir} does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'compile_dir' ] = $message;
}
} else if (!is_dir($_compile_dir)) {
$status = false;
$message = "FAILED: {$_compile_dir} is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'compile_dir' ] = $message;
}
} else if (!is_readable($_compile_dir)) {
$status = false;
$message = "FAILED: {$_compile_dir} is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'compile_dir' ] = $message;
}
} else if (!is_writable($_compile_dir)) {
$status = false;
$message = "FAILED: {$_compile_dir} is not writable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'compile_dir' ] = $message;
}
} else {
if ($errors === null) {
echo "{$_compile_dir} is OK.\n";
}
}
if ($errors === null) {
echo "Testing plugins directory...\n";
}
// test if all registered plugins_dir are accessible
// and if core plugins directory is still registered
$_core_plugins_dir = realpath(dirname(__FILE__) . '/../plugins');
$_core_plugins_available = false;
foreach ($smarty->getPluginsDir() as $plugin_dir) {
$_plugin_dir = $plugin_dir;
$plugin_dir = realpath($plugin_dir);
// resolve include_path or fail existence
if (!$plugin_dir) {
if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_plugin_dir)) {
// try PHP include_path
if ($_stream_resolve_include_path) {
$plugin_dir = stream_resolve_include_path($_plugin_dir);
} else {
$plugin_dir = $smarty->ext->_getIncludePath->getIncludePath($_plugin_dir, null, $smarty);
}
if ($plugin_dir !== false) {
if ($errors === null) {
echo "$plugin_dir is OK.\n";
}
continue;
} else {
$status = false;
$message = "FAILED: $_plugin_dir does not exist (and couldn't be found in include_path either)";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'plugins_dir' ] = $message;
}
continue;
}
} else {
$status = false;
$message = "FAILED: $_plugin_dir does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'plugins_dir' ] = $message;
}
continue;
}
}
if (!is_dir($plugin_dir)) {
$status = false;
$message = "FAILED: $plugin_dir is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'plugins_dir' ] = $message;
}
} else if (!is_readable($plugin_dir)) {
$status = false;
$message = "FAILED: $plugin_dir is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'plugins_dir' ] = $message;
}
} else if ($_core_plugins_dir && $_core_plugins_dir === realpath($plugin_dir)) {
$_core_plugins_available = true;
if ($errors === null) {
echo "$plugin_dir is OK.\n";
}
} else {
if ($errors === null) {
echo "$plugin_dir is OK.\n";
}
}
}
if (!$_core_plugins_available) {
$status = false;
$message = "WARNING: Smarty's own libs/plugins is not available";
if ($errors === null) {
echo $message . ".\n";
} else if (!isset($errors[ 'plugins_dir' ])) {
$errors[ 'plugins_dir' ] = $message;
}
}
if ($errors === null) {
echo "Testing cache directory...\n";
}
// test if all registered cache_dir is accessible
$__cache_dir = $smarty->getCacheDir();
$_cache_dir = realpath($__cache_dir);
if (!$_cache_dir) {
$status = false;
$message = "FAILED: {$__cache_dir} does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'cache_dir' ] = $message;
}
} else if (!is_dir($_cache_dir)) {
$status = false;
$message = "FAILED: {$_cache_dir} is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'cache_dir' ] = $message;
}
} else if (!is_readable($_cache_dir)) {
$status = false;
$message = "FAILED: {$_cache_dir} is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'cache_dir' ] = $message;
}
} else if (!is_writable($_cache_dir)) {
$status = false;
$message = "FAILED: {$_cache_dir} is not writable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'cache_dir' ] = $message;
}
} else {
if ($errors === null) {
echo "{$_cache_dir} is OK.\n";
}
}
if ($errors === null) {
echo "Testing configs directory...\n";
}
// test if all registered config_dir are accessible
foreach ($smarty->getConfigDir() as $config_dir) {
$_config_dir = $config_dir;
// resolve include_path or fail existence
if (!$config_dir) {
if ($smarty->use_include_path && !preg_match('/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/', $_config_dir)) {
// try PHP include_path
if ($_stream_resolve_include_path) {
$config_dir = stream_resolve_include_path($_config_dir);
} else {
$config_dir = $smarty->ext->_getIncludePath->getIncludePath($_config_dir, null, $smarty);
}
if ($config_dir !== false) {
if ($errors === null) {
echo "$config_dir is OK.\n";
}
continue;
} else {
$status = false;
$message = "FAILED: $_config_dir does not exist (and couldn't be found in include_path either)";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'config_dir' ] = $message;
}
continue;
}
} else {
$status = false;
$message = "FAILED: $_config_dir does not exist";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'config_dir' ] = $message;
}
continue;
}
}
if (!is_dir($config_dir)) {
$status = false;
$message = "FAILED: $config_dir is not a directory";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'config_dir' ] = $message;
}
} else if (!is_readable($config_dir)) {
$status = false;
$message = "FAILED: $config_dir is not readable";
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'config_dir' ] = $message;
}
} else {
if ($errors === null) {
echo "$config_dir is OK.\n";
}
}
}
if ($errors === null) {
echo "Testing sysplugin files...\n";
}
// test if sysplugins are available
$source = SMARTY_SYSPLUGINS_DIR;
if (is_dir($source)) {
$expectedSysplugins = array(
'smartycompilerexception.php' => true,
'smartyexception.php' => true,
'smarty_cacheresource.php' => true,
'smarty_cacheresource_custom.php' => true,
'smarty_cacheresource_keyvaluestore.php' => true,
'smarty_data.php' => true,
'smarty_internal_block.php' => true,
'smarty_internal_cacheresource_file.php' => true,
'smarty_internal_compilebase.php' => true,
'smarty_internal_compile_append.php' => true,
'smarty_internal_compile_assign.php' => true,
'smarty_internal_compile_block.php' => true,
'smarty_internal_compile_break.php' => true,
'smarty_internal_compile_call.php' => true,
'smarty_internal_compile_capture.php' => true,
'smarty_internal_compile_config_load.php' => true,
'smarty_internal_compile_continue.php' => true,
'smarty_internal_compile_debug.php' => true,
'smarty_internal_compile_eval.php' => true,
'smarty_internal_compile_extends.php' => true,
'smarty_internal_compile_for.php' => true,
'smarty_internal_compile_foreach.php' => true,
'smarty_internal_compile_function.php' => true,
'smarty_internal_compile_if.php' => true,
'smarty_internal_compile_include.php' => true,
'smarty_internal_compile_include_php.php' => true,
'smarty_internal_compile_insert.php' => true,
'smarty_internal_compile_ldelim.php' => true,
'smarty_internal_compile_make_nocache.php' => true,
'smarty_internal_compile_nocache.php' => true,
'smarty_internal_compile_private_block_plugin.php' => true,
'smarty_internal_compile_private_foreachsection.php' => true,
'smarty_internal_compile_private_function_plugin.php' => true,
'smarty_internal_compile_private_modifier.php' => true,
'smarty_internal_compile_private_object_block_function.php' => true,
'smarty_internal_compile_private_object_function.php' => true,
'smarty_internal_compile_private_php.php' => true,
'smarty_internal_compile_private_print_expression.php' => true,
'smarty_internal_compile_private_registered_block.php' => true,
'smarty_internal_compile_private_registered_function.php' => true,
'smarty_internal_compile_private_special_variable.php' => true,
'smarty_internal_compile_rdelim.php' => true,
'smarty_internal_compile_section.php' => true,
'smarty_internal_compile_setfilter.php' => true,
'smarty_internal_compile_shared_inheritance.php' => true,
'smarty_internal_compile_while.php' => true,
'smarty_internal_configfilelexer.php' => true,
'smarty_internal_configfileparser.php' => true,
'smarty_internal_config_file_compiler.php' => true,
'smarty_internal_data.php' => true,
'smarty_internal_debug.php' => true,
'smarty_internal_errorhandler.php' => true,
'smarty_internal_extension_handler.php' => true,
'smarty_internal_method_addautoloadfilters.php' => true,
'smarty_internal_method_adddefaultmodifiers.php' => true,
'smarty_internal_method_append.php' => true,
'smarty_internal_method_appendbyref.php' => true,
'smarty_internal_method_assignbyref.php' => true,
'smarty_internal_method_assignglobal.php' => true,
'smarty_internal_method_clearallassign.php' => true,
'smarty_internal_method_clearallcache.php' => true,
'smarty_internal_method_clearassign.php' => true,
'smarty_internal_method_clearcache.php' => true,
'smarty_internal_method_clearcompiledtemplate.php' => true,
'smarty_internal_method_clearconfig.php' => true,
'smarty_internal_method_compileallconfig.php' => true,
'smarty_internal_method_compilealltemplates.php' => true,
'smarty_internal_method_configload.php' => true,
'smarty_internal_method_createdata.php' => true,
'smarty_internal_method_getautoloadfilters.php' => true,
'smarty_internal_method_getconfigvariable.php' => true,
'smarty_internal_method_getconfigvars.php' => true,
'smarty_internal_method_getdebugtemplate.php' => true,
'smarty_internal_method_getdefaultmodifiers.php' => true,
'smarty_internal_method_getglobal.php' => true,
'smarty_internal_method_getregisteredobject.php' => true,
'smarty_internal_method_getstreamvariable.php' => true,
'smarty_internal_method_gettags.php' => true,
'smarty_internal_method_gettemplatevars.php' => true,
'smarty_internal_method_literals.php' => true,
'smarty_internal_method_loadfilter.php' => true,
'smarty_internal_method_loadplugin.php' => true,
'smarty_internal_method_mustcompile.php' => true,
'smarty_internal_method_registercacheresource.php' => true,
'smarty_internal_method_registerclass.php' => true,
'smarty_internal_method_registerdefaultconfighandler.php' => true,
'smarty_internal_method_registerdefaultpluginhandler.php' => true,
'smarty_internal_method_registerdefaulttemplatehandler.php' => true,
'smarty_internal_method_registerfilter.php' => true,
'smarty_internal_method_registerobject.php' => true,
'smarty_internal_method_registerplugin.php' => true,
'smarty_internal_method_registerresource.php' => true,
'smarty_internal_method_setautoloadfilters.php' => true,
'smarty_internal_method_setdebugtemplate.php' => true,
'smarty_internal_method_setdefaultmodifiers.php' => true,
'smarty_internal_method_unloadfilter.php' => true,
'smarty_internal_method_unregistercacheresource.php' => true,
'smarty_internal_method_unregisterfilter.php' => true,
'smarty_internal_method_unregisterobject.php' => true,
'smarty_internal_method_unregisterplugin.php' => true,
'smarty_internal_method_unregisterresource.php' => true,
'smarty_internal_nocache_insert.php' => true,
'smarty_internal_parsetree.php' => true,
'smarty_internal_parsetree_code.php' => true,
'smarty_internal_parsetree_dq.php' => true,
'smarty_internal_parsetree_dqcontent.php' => true,
'smarty_internal_parsetree_tag.php' => true,
'smarty_internal_parsetree_template.php' => true,
'smarty_internal_parsetree_text.php' => true,
'smarty_internal_resource_eval.php' => true,
'smarty_internal_resource_extends.php' => true,
'smarty_internal_resource_file.php' => true,
'smarty_internal_resource_php.php' => true,
'smarty_internal_resource_registered.php' => true,
'smarty_internal_resource_stream.php' => true,
'smarty_internal_resource_string.php' => true,
'smarty_internal_runtime_cachemodify.php' => true,
'smarty_internal_runtime_cacheresourcefile.php' => true,
'smarty_internal_runtime_capture.php' => true,
'smarty_internal_runtime_codeframe.php' => true,
'smarty_internal_runtime_filterhandler.php' => true,
'smarty_internal_runtime_foreach.php' => true,
'smarty_internal_runtime_getincludepath.php' => true,
'smarty_internal_runtime_inheritance.php' => true,
'smarty_internal_runtime_make_nocache.php' => true,
'smarty_internal_runtime_tplfunction.php' => true,
'smarty_internal_runtime_updatecache.php' => true,
'smarty_internal_runtime_updatescope.php' => true,
'smarty_internal_runtime_writefile.php' => true,
'smarty_internal_smartytemplatecompiler.php' => true,
'smarty_internal_template.php' => true,
'smarty_internal_templatebase.php' => true,
'smarty_internal_templatecompilerbase.php' => true,
'smarty_internal_templatelexer.php' => true,
'smarty_internal_templateparser.php' => true,
'smarty_internal_testinstall.php' => true,
'smarty_internal_undefined.php' => true,
'smarty_resource.php' => true,
'smarty_resource_custom.php' => true,
'smarty_resource_recompiled.php' => true,
'smarty_resource_uncompiled.php' => true,
'smarty_security.php' => true,
'smarty_template_cached.php' => true,
'smarty_template_compiled.php' => true,
'smarty_template_config.php' => true,
'smarty_template_resource_base.php' => true,
'smarty_template_source.php' => true,
'smarty_undefined_variable.php' => true,
'smarty_variable.php' => true,
);
$iterator = new DirectoryIterator($source);
foreach ($iterator as $file) {
if (!$file->isDot()) {
$filename = $file->getFilename();
if (isset($expectedSysplugins[ $filename ])) {
unset($expectedSysplugins[ $filename ]);
}
}
}
if ($expectedSysplugins) {
$status = false;
$message = "FAILED: files missing from libs/sysplugins: " . join(', ', array_keys($expectedSysplugins));
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'sysplugins' ] = $message;
}
} else if ($errors === null) {
echo "... OK\n";
}
} else {
$status = false;
$message = "FAILED: " . SMARTY_SYSPLUGINS_DIR . ' is not a directory';
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'sysplugins_dir_constant' ] = $message;
}
}
if ($errors === null) {
echo "Testing plugin files...\n";
}
// test if core plugins are available
$source = SMARTY_PLUGINS_DIR;
if (is_dir($source)) {
$expectedPlugins = array(
'block.textformat.php' => true,
'function.counter.php' => true,
'function.cycle.php' => true,
'function.fetch.php' => true,
'function.html_checkboxes.php' => true,
'function.html_image.php' => true,
'function.html_options.php' => true,
'function.html_radios.php' => true,
'function.html_select_date.php' => true,
'function.html_select_time.php' => true,
'function.html_table.php' => true,
'function.mailto.php' => true,
'function.math.php' => true,
'modifier.capitalize.php' => true,
'modifier.date_format.php' => true,
'modifier.debug_print_var.php' => true,
'modifier.escape.php' => true,
'modifier.mb_wordwrap.php' => true,
'modifier.regex_replace.php' => true,
'modifier.replace.php' => true,
'modifier.spacify.php' => true,
'modifier.truncate.php' => true,
'modifiercompiler.cat.php' => true,
'modifiercompiler.count_characters.php' => true,
'modifiercompiler.count_paragraphs.php' => true,
'modifiercompiler.count_sentences.php' => true,
'modifiercompiler.count_words.php' => true,
'modifiercompiler.default.php' => true,
'modifiercompiler.escape.php' => true,
'modifiercompiler.from_charset.php' => true,
'modifiercompiler.indent.php' => true,
'modifiercompiler.lower.php' => true,
'modifiercompiler.noprint.php' => true,
'modifiercompiler.string_format.php' => true,
'modifiercompiler.strip.php' => true,
'modifiercompiler.strip_tags.php' => true,
'modifiercompiler.to_charset.php' => true,
'modifiercompiler.unescape.php' => true,
'modifiercompiler.upper.php' => true,
'modifiercompiler.wordwrap.php' => true,
'outputfilter.trimwhitespace.php' => true,
'shared.escape_special_chars.php' => true,
'shared.literal_compiler_param.php' => true,
'shared.make_timestamp.php' => true,
'shared.mb_str_replace.php' => true,
'shared.mb_unicode.php' => true,
'variablefilter.htmlspecialchars.php' => true,
);
$iterator = new DirectoryIterator($source);
foreach ($iterator as $file) {
if (!$file->isDot()) {
$filename = $file->getFilename();
if (isset($expectedPlugins[ $filename ])) {
unset($expectedPlugins[ $filename ]);
}
}
}
if ($expectedPlugins) {
$status = false;
$message = "FAILED: files missing from libs/plugins: " . join(', ', array_keys($expectedPlugins));
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'plugins' ] = $message;
}
} else if ($errors === null) {
echo "... OK\n";
}
} else {
$status = false;
$message = "FAILED: " . SMARTY_PLUGINS_DIR . ' is not a directory';
if ($errors === null) {
echo $message . ".\n";
} else {
$errors[ 'plugins_dir_constant' ] = $message;
}
}
if ($errors === null) {
echo "Tests complete.\n";
echo "</PRE>\n";
}
return $status;
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_compile_include_php.php | Extend/Package/smarty/sysplugins/smarty_internal_compile_include_php.php | <?php
/**
* Smarty Internal Plugin Compile Include PHP
* Compiles the {include_php} tag
*
* @package Smarty
* @subpackage Compiler
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Compile Insert Class
*
* @package Smarty
* @subpackage Compiler
*/
class Smarty_Internal_Compile_Include_Php extends Smarty_Internal_CompileBase
{
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $required_attributes = array('file');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $shorttag_order = array('file');
/**
* Attribute definition: Overwrites base class.
*
* @var array
* @see Smarty_Internal_CompileBase
*/
public $optional_attributes = array('once', 'assign');
/**
* Compiles code for the {include_php} tag
*
* @param array $args array with attributes from parser
* @param \Smarty_Internal_TemplateCompilerBase $compiler compiler object
*
* @return string
* @throws \SmartyCompilerException
* @throws \SmartyException
*/
public function compile($args, Smarty_Internal_TemplateCompilerBase $compiler)
{
if (!($compiler->smarty instanceof SmartyBC)) {
throw new SmartyException("{include_php} is deprecated, use SmartyBC class to enable");
}
// check and get attributes
$_attr = $this->getAttributes($compiler, $args);
/** @var Smarty_Internal_Template $_smarty_tpl
* used in evaluated code
*/
$_smarty_tpl = $compiler->template;
$_filepath = false;
$_file = null;
eval('$_file = @' . $_attr[ 'file' ] . ';');
if (!isset($compiler->smarty->security_policy) && file_exists($_file)) {
$_filepath = $compiler->smarty->_realpath($_file, true);
} else {
if (isset($compiler->smarty->security_policy)) {
$_dir = $compiler->smarty->security_policy->trusted_dir;
} else {
$_dir = $compiler->smarty->trusted_dir;
}
if (!empty($_dir)) {
foreach ((array)$_dir as $_script_dir) {
$_path = $compiler->smarty->_realpath($_script_dir . DIRECTORY_SEPARATOR . $_file, true);
if (file_exists($_path)) {
$_filepath = $_path;
break;
}
}
}
}
if ($_filepath === false) {
$compiler->trigger_template_error("{include_php} file '{$_file}' is not readable", null, true);
}
if (isset($compiler->smarty->security_policy)) {
$compiler->smarty->security_policy->isTrustedPHPDir($_filepath);
}
if (isset($_attr[ 'assign' ])) {
// output will be stored in a smarty variable instead of being displayed
$_assign = $_attr[ 'assign' ];
}
$_once = '_once';
if (isset($_attr[ 'once' ])) {
if ($_attr[ 'once' ] === 'false') {
$_once = '';
}
}
if (isset($_assign)) {
return "<?php ob_start();\ninclude{$_once} ('{$_filepath}');\n\$_smarty_tpl->assign({$_assign},ob_get_clean());\n?>";
} else {
return "<?php include{$_once} ('{$_filepath}');?>\n";
}
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_template.php | Extend/Package/smarty/sysplugins/smarty_internal_template.php | <?php
/**
* Smarty Internal Plugin Template
* This file contains the Smarty template engine
*
* @package Smarty
* @subpackage Template
* @author Uwe Tews
*/
/**
* Main class with template data structures and methods
*
* @package Smarty
* @subpackage Template
*
* @property Smarty_Template_Compiled $compiled
* @property Smarty_Template_Cached $cached
* @property Smarty_Internal_TemplateCompilerBase $compiler
* @property mixed|\Smarty_Template_Cached registered_plugins
*
* The following methods will be dynamically loaded by the extension handler when they are called.
* They are located in a corresponding Smarty_Internal_Method_xxxx class
*
* @method bool mustCompile()
*/
class Smarty_Internal_Template extends Smarty_Internal_TemplateBase
{
/**
* This object type (Smarty = 1, template = 2, data = 4)
*
* @var int
*/
public $_objType = 2;
/**
* Global smarty instance
*
* @var Smarty
*/
public $smarty = null;
/**
* Source instance
*
* @var Smarty_Template_Source|Smarty_Template_Config
*/
public $source = null;
/**
* Inheritance runtime extension
*
* @var Smarty_Internal_Runtime_Inheritance
*/
public $inheritance = null;
/**
* Template resource
*
* @var string
*/
public $template_resource = null;
/**
* flag if compiled template is invalid and must be (re)compiled
*
* @var bool
*/
public $mustCompile = null;
/**
* Template Id
*
* @var null|string
*/
public $templateId = null;
/**
* Scope in which variables shall be assigned
*
* @var int
*/
public $scope = 0;
/**
* Flag which is set while rending a cache file
*
* @var bool
*/
public $isRenderingCache = false;
/**
* Callbacks called before rendering template
*
* @var callback[]
*/
public $startRenderCallbacks = array();
/**
* Callbacks called after rendering template
*
* @var callback[]
*/
public $endRenderCallbacks = array();
/**
* Template object cache
*
* @var Smarty_Internal_Template[]
*/
public static $tplObjCache = array();
/**
* Template object cache for Smarty::isCached() === true
*
* @var Smarty_Internal_Template[]
*/
public static $isCacheTplObj = array();
/**
* Sub template Info Cache
* - index name
* - value use count
*
* @var int[]
*/
public static $subTplInfo = array();
/**
* Create template data object
* Some of the global Smarty settings copied to template scope
* It load the required template resources and caching plugins
*
* @param string $template_resource template resource string
* @param Smarty $smarty Smarty instance
* @param null|\Smarty_Internal_Template|\Smarty|\Smarty_Internal_Data $_parent back pointer to parent object
* with variables or null
* @param mixed $_cache_id cache id or null
* @param mixed $_compile_id compile id or null
* @param bool|int|null $_caching use caching?
* @param int|null $_cache_lifetime cache life-time in seconds
* @param bool $_isConfig
*
* @throws \SmartyException
*/
public function __construct($template_resource, Smarty $smarty, Smarty_Internal_Data $_parent = null,
$_cache_id = null, $_compile_id = null, $_caching = null, $_cache_lifetime = null,
$_isConfig = false)
{
$this->smarty = $smarty;
// Smarty parameter
$this->cache_id = $_cache_id === null ? $this->smarty->cache_id : $_cache_id;
$this->compile_id = $_compile_id === null ? $this->smarty->compile_id : $_compile_id;
$this->caching = (int)($_caching === null ? $this->smarty->caching : $_caching);
$this->cache_lifetime = $_cache_lifetime === null ? $this->smarty->cache_lifetime : $_cache_lifetime;
$this->compile_check = (int)$smarty->compile_check;
$this->parent = $_parent;
// Template resource
$this->template_resource = $template_resource;
$this->source = $_isConfig ? Smarty_Template_Config::load($this) : Smarty_Template_Source::load($this);
parent::__construct();
if ($smarty->security_policy && method_exists($smarty->security_policy, 'registerCallBacks')) {
$smarty->security_policy->registerCallBacks($this);
}
}
/**
* render template
*
* @param bool $no_output_filter if true do not run output filter
* @param null|bool $display true: display, false: fetch null: sub-template
*
* @return string
* @throws \Exception
* @throws \SmartyException
*/
public function render($no_output_filter = true, $display = null)
{
if ($this->smarty->debugging) {
if (!isset($this->smarty->_debug)) {
$this->smarty->_debug = new Smarty_Internal_Debug();
}
$this->smarty->_debug->start_template($this, $display);
}
// checks if template exists
if (!$this->source->exists) {
throw new SmartyException("Unable to load template '{$this->source->type}:{$this->source->name}'" .
($this->_isSubTpl() ? " in '{$this->parent->template_resource}'" : ''));
}
// disable caching for evaluated code
if ($this->source->handler->recompiled) {
$this->caching = Smarty::CACHING_OFF;
}
// read from cache or render
if ($this->caching === Smarty::CACHING_LIFETIME_CURRENT || $this->caching === Smarty::CACHING_LIFETIME_SAVED) {
if (!isset($this->cached) || $this->cached->cache_id !== $this->cache_id ||
$this->cached->compile_id !== $this->compile_id
) {
$this->loadCached(true);
}
$this->cached->render($this, $no_output_filter);
} else {
if (!isset($this->compiled) || $this->compiled->compile_id !== $this->compile_id) {
$this->loadCompiled(true);
}
$this->compiled->render($this);
}
// display or fetch
if ($display) {
if ($this->caching && $this->smarty->cache_modified_check) {
$this->smarty->ext->_cacheModify->cacheModifiedCheck($this->cached, $this,
isset($content) ? $content : ob_get_clean());
} else {
if ((!$this->caching || $this->cached->has_nocache_code || $this->source->handler->recompiled) &&
!$no_output_filter && (isset($this->smarty->autoload_filters[ 'output' ]) ||
isset($this->smarty->registered_filters[ 'output' ]))
) {
echo $this->smarty->ext->_filterHandler->runFilter('output', ob_get_clean(), $this);
} else {
echo ob_get_clean();
}
}
if ($this->smarty->debugging) {
$this->smarty->_debug->end_template($this);
// debug output
$this->smarty->_debug->display_debug($this, true);
}
return '';
} else {
if ($this->smarty->debugging) {
$this->smarty->_debug->end_template($this);
if ($this->smarty->debugging === 2 && $display === false) {
$this->smarty->_debug->display_debug($this, true);
}
}
if ($this->_isSubTpl()) {
foreach ($this->compiled->required_plugins as $code => $tmp1) {
foreach ($tmp1 as $name => $tmp) {
foreach ($tmp as $type => $data) {
$this->parent->compiled->required_plugins[ $code ][ $name ][ $type ] = $data;
}
}
}
}
if (!$no_output_filter &&
(!$this->caching || $this->cached->has_nocache_code || $this->source->handler->recompiled) &&
(isset($this->smarty->autoload_filters[ 'output' ]) ||
isset($this->smarty->registered_filters[ 'output' ]))
) {
return $this->smarty->ext->_filterHandler->runFilter('output', ob_get_clean(), $this);
}
// return cache content
return null;
}
}
/**
* Runtime function to render sub-template
*
* @param string $template template name
* @param mixed $cache_id cache id
* @param mixed $compile_id compile id
* @param integer $caching cache mode
* @param integer $cache_lifetime life time of cache data
* @param array $data passed parameter template variables
* @param int $scope scope in which {include} should execute
* @param bool $forceTplCache cache template object
* @param string $uid file dependency uid
* @param string $content_func function name
*
* @throws \Exception
* @throws \SmartyException
*/
public function _subTemplateRender($template, $cache_id, $compile_id, $caching, $cache_lifetime, $data, $scope,
$forceTplCache, $uid = null, $content_func = null)
{
$tpl = clone $this;
$tpl->parent = $this;
$smarty = &$this->smarty;
$_templateId = $smarty->_getTemplateId($template, $cache_id, $compile_id, $caching, $tpl);
// recursive call ?
if (isset($tpl->templateId) ? $tpl->templateId : $tpl->_getTemplateId() !== $_templateId) {
// already in template cache?
if (isset(self::$tplObjCache[ $_templateId ])) {
// copy data from cached object
$cachedTpl = &self::$tplObjCache[ $_templateId ];
$tpl->templateId = $cachedTpl->templateId;
$tpl->template_resource = $cachedTpl->template_resource;
$tpl->cache_id = $cachedTpl->cache_id;
$tpl->compile_id = $cachedTpl->compile_id;
$tpl->source = $cachedTpl->source;
if (isset($cachedTpl->compiled)) {
$tpl->compiled = $cachedTpl->compiled;
} else {
unset($tpl->compiled);
}
if ($caching !== 9999 && isset($cachedTpl->cached)) {
$tpl->cached = $cachedTpl->cached;
} else {
unset($tpl->cached);
}
} else {
$tpl->templateId = $_templateId;
$tpl->template_resource = $template;
$tpl->cache_id = $cache_id;
$tpl->compile_id = $compile_id;
if (isset($uid)) {
// for inline templates we can get all resource information from file dependency
list($filepath, $timestamp, $type) = $tpl->compiled->file_dependency[ $uid ];
$tpl->source = new Smarty_Template_Source($smarty, $filepath, $type, $filepath);
$tpl->source->filepath = $filepath;
$tpl->source->timestamp = $timestamp;
$tpl->source->exists = true;
$tpl->source->uid = $uid;
} else {
$tpl->source = Smarty_Template_Source::load($tpl);
unset($tpl->compiled);
}
if ($caching !== 9999) {
unset($tpl->cached);
}
}
} else {
// on recursive calls force caching
$forceTplCache = true;
}
$tpl->caching = $caching;
$tpl->cache_lifetime = $cache_lifetime;
// set template scope
$tpl->scope = $scope;
if (!isset(self::$tplObjCache[ $tpl->templateId ]) && !$tpl->source->handler->recompiled) {
// check if template object should be cached
if ($forceTplCache || (isset(self::$subTplInfo[ $tpl->template_resource ]) &&
self::$subTplInfo[ $tpl->template_resource ] > 1) ||
($tpl->_isSubTpl() && isset(self::$tplObjCache[ $tpl->parent->templateId ]))
) {
self::$tplObjCache[ $tpl->templateId ] = $tpl;
}
}
if (!empty($data)) {
// set up variable values
foreach ($data as $_key => $_val) {
$tpl->tpl_vars[ $_key ] = new Smarty_Variable($_val, $this->isRenderingCache);
}
}
if ($tpl->caching === 9999) {
if (!isset($tpl->compiled)) {
$this->loadCompiled(true);
}
if ($tpl->compiled->has_nocache_code) {
$this->cached->hashes[ $tpl->compiled->nocache_hash ] = true;
}
}
$tpl->_cache = array();
if (isset($uid)) {
if ($smarty->debugging) {
if (!isset($smarty->_debug)) {
$smarty->_debug = new Smarty_Internal_Debug();
}
$smarty->_debug->start_template($tpl);
$smarty->_debug->start_render($tpl);
}
$tpl->compiled->getRenderedTemplateCode($tpl, $content_func);
if ($smarty->debugging) {
$smarty->_debug->end_template($tpl);
$smarty->_debug->end_render($tpl);
}
} else {
if (isset($tpl->compiled)) {
$tpl->compiled->render($tpl);
} else {
$tpl->render();
}
}
}
/**
* Get called sub-templates and save call count
*
*/
public function _subTemplateRegister()
{
foreach ($this->compiled->includes as $name => $count) {
if (isset(self::$subTplInfo[ $name ])) {
self::$subTplInfo[ $name ] += $count;
} else {
self::$subTplInfo[ $name ] = $count;
}
}
}
/**
* Check if this is a sub template
*
* @return bool true is sub template
*/
public function _isSubTpl()
{
return isset($this->parent) && $this->parent->_isTplObj();
}
/**
* Assign variable in scope
*
* @param string $varName variable name
* @param mixed $value value
* @param bool $nocache nocache flag
* @param int $scope scope into which variable shall be assigned
*
*/
public function _assignInScope($varName, $value, $nocache = false, $scope = 0)
{
if (isset($this->tpl_vars[ $varName ])) {
$this->tpl_vars[ $varName ] = clone $this->tpl_vars[ $varName ];
$this->tpl_vars[ $varName ]->value = $value;
if ($nocache || $this->isRenderingCache) {
$this->tpl_vars[ $varName ]->nocache = true;
}
} else {
$this->tpl_vars[ $varName ] = new Smarty_Variable($value, $nocache || $this->isRenderingCache);
}
if ($scope >= 0) {
if ($scope > 0 || $this->scope > 0) {
$this->smarty->ext->_updateScope->_updateScope($this, $varName, $scope);
}
}
}
/**
* This function is executed automatically when a compiled or cached template file is included
* - Decode saved properties from compiled template and cache files
* - Check if compiled or cache file is valid
*
* @param \Smarty_Internal_Template $tpl
* @param array $properties special template properties
* @param bool $cache flag if called from cache file
*
* @return bool flag if compiled or cache file is valid
* @throws \SmartyException
*/
public function _decodeProperties(Smarty_Internal_Template $tpl, $properties, $cache = false)
{
// on cache resources other than file check version stored in cache code
if (!isset($properties[ 'version' ]) || Smarty::SMARTY_VERSION !== $properties[ 'version' ]) {
if ($cache) {
$tpl->smarty->clearAllCache();
} else {
$tpl->smarty->clearCompiledTemplate();
}
return false;
}
$is_valid = true;
if (!empty($properties[ 'file_dependency' ]) &&
((!$cache && $tpl->compile_check) || $tpl->compile_check === Smarty::COMPILECHECK_ON)
) {
// check file dependencies at compiled code
foreach ($properties[ 'file_dependency' ] as $_file_to_check) {
if ($_file_to_check[ 2 ] === 'file' || $_file_to_check[ 2 ] === 'php') {
if ($tpl->source->filepath === $_file_to_check[ 0 ]) {
// do not recheck current template
continue;
//$mtime = $tpl->source->getTimeStamp();
} else {
// file and php types can be checked without loading the respective resource handlers
$mtime = is_file($_file_to_check[ 0 ]) ? filemtime($_file_to_check[ 0 ]) : false;
}
} else {
$handler = Smarty_Resource::load($tpl->smarty, $_file_to_check[ 2 ]);
if ($handler->checkTimestamps()) {
$source = Smarty_Template_Source::load($tpl, $tpl->smarty, $_file_to_check[ 0 ]);
$mtime = $source->getTimeStamp();
} else {
continue;
}
}
if ($mtime === false || $mtime > $_file_to_check[ 1 ]) {
$is_valid = false;
break;
}
}
}
if ($cache) {
// CACHING_LIFETIME_SAVED cache expiry has to be validated here since otherwise we'd define the unifunc
if ($tpl->caching === Smarty::CACHING_LIFETIME_SAVED && $properties[ 'cache_lifetime' ] >= 0 &&
(time() > ($tpl->cached->timestamp + $properties[ 'cache_lifetime' ]))
) {
$is_valid = false;
}
$tpl->cached->cache_lifetime = $properties[ 'cache_lifetime' ];
$tpl->cached->valid = $is_valid;
$resource = $tpl->cached;
} else {
$tpl->mustCompile = !$is_valid;
$resource = $tpl->compiled;
$resource->includes = isset($properties[ 'includes' ]) ? $properties[ 'includes' ] : array();
}
if ($is_valid) {
$resource->unifunc = $properties[ 'unifunc' ];
$resource->has_nocache_code = $properties[ 'has_nocache_code' ];
// $tpl->compiled->nocache_hash = $properties['nocache_hash'];
$resource->file_dependency = $properties[ 'file_dependency' ];
}
return $is_valid && !function_exists($properties[ 'unifunc' ]);
}
/**
* Compiles the template
* If the template is not evaluated the compiled template is saved on disk
*/
public function compileTemplateSource()
{
return $this->compiled->compileTemplateSource($this);
}
/**
* Writes the content to cache resource
*
* @param string $content
*
* @return bool
*/
public function writeCachedContent($content)
{
return $this->smarty->ext->_updateCache->writeCachedContent($this->cached, $this, $content);
}
/**
* Get unique template id
*
* @return string
* @throws \SmartyException
*/
public function _getTemplateId()
{
return isset($this->templateId) ? $this->templateId : $this->templateId =
$this->smarty->_getTemplateId($this->template_resource, $this->cache_id, $this->compile_id);
}
/**
* runtime error not matching capture tags
*/
public function capture_error()
{
throw new SmartyException("Not matching {capture} open/close in '{$this->template_resource}'");
}
/**
* Load compiled object
*
* @param bool $force force new compiled object
*/
public function loadCompiled($force = false)
{
if ($force || !isset($this->compiled)) {
$this->compiled = Smarty_Template_Compiled::load($this);
}
}
/**
* Load cached object
*
* @param bool $force force new cached object
*/
public function loadCached($force = false)
{
if ($force || !isset($this->cached)) {
$this->cached = Smarty_Template_Cached::load($this);
}
}
/**
* Load inheritance object
*
*/
public function _loadInheritance()
{
if (!isset($this->inheritance)) {
$this->inheritance = new Smarty_Internal_Runtime_Inheritance();
}
}
/**
* Unload inheritance object
*
*/
public function _cleanUp()
{
$this->startRenderCallbacks = array();
$this->endRenderCallbacks = array();
$this->inheritance = null;
}
/**
* Load compiler object
*
* @throws \SmartyException
*/
public function loadCompiler()
{
if (!class_exists($this->source->compiler_class,false)) {
$this->smarty->loadPlugin($this->source->compiler_class);
}
$this->compiler =
new $this->source->compiler_class($this->source->template_lexer_class, $this->source->template_parser_class,
$this->smarty);
}
/**
* Handle unknown class methods
*
* @param string $name unknown method-name
* @param array $args argument array
*
* @return mixed
* @throws SmartyException
*/
public function __call($name, $args)
{
// method of Smarty object?
if (method_exists($this->smarty, $name)) {
return call_user_func_array(array($this->smarty, $name), $args);
}
// parent
return parent::__call($name, $args);
}
/**
* set Smarty property in template context
*
* @param string $property_name property name
* @param mixed $value value
*
* @throws SmartyException
*/
public function __set($property_name, $value)
{
switch ($property_name) {
case 'compiled':
case 'cached':
case 'compiler':
$this->$property_name = $value;
return;
default:
// Smarty property ?
if (property_exists($this->smarty, $property_name)) {
$this->smarty->$property_name = $value;
return;
}
}
throw new SmartyException("invalid template property '$property_name'.");
}
/**
* get Smarty property in template context
*
* @param string $property_name property name
*
* @return mixed|Smarty_Template_Cached
* @throws SmartyException
*/
public function __get($property_name)
{
switch ($property_name) {
case 'compiled':
$this->loadCompiled();
return $this->compiled;
case 'cached':
$this->loadCached();
return $this->cached;
case 'compiler':
$this->loadCompiler();
return $this->compiler;
default:
// Smarty property ?
if (property_exists($this->smarty, $property_name)) {
return $this->smarty->$property_name;
}
}
throw new SmartyException("template property '$property_name' does not exist.");
}
/**
* Template data object destructor
*/
public function __destruct()
{
if ($this->smarty->cache_locking && isset($this->cached) && $this->cached->is_locked) {
$this->cached->handler->releaseLock($this->smarty, $this->cached);
}
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_loadplugin.php | Extend/Package/smarty/sysplugins/smarty_internal_method_loadplugin.php | <?php
/**
* Smarty Extension Loadplugin
*
* $smarty->loadPlugin() method
*
* @package Smarty
* @subpackage PluginsInternal
* @author Uwe Tews
*/
class Smarty_Internal_Method_LoadPlugin
{
/**
* Cache of searched plugin files
*
* @var array
*/
public $plugin_files = array();
/**
* Takes unknown classes and loads plugin files for them
* class name format: Smarty_PluginType_PluginName
* plugin filename format: plugintype.pluginname.php
*
* @param \Smarty $smarty
* @param string $plugin_name class plugin name to load
* @param bool $check check if already loaded
*
* @return bool|string
* @throws \SmartyException
*/
public function loadPlugin(Smarty $smarty, $plugin_name, $check)
{
// if function or class exists, exit silently (already loaded)
if ($check && (is_callable($plugin_name) || class_exists($plugin_name, false))) {
return true;
}
if (!preg_match('#^smarty_((internal)|([^_]+))_(.+)$#i', $plugin_name, $match)) {
throw new SmartyException("plugin {$plugin_name} is not a valid name format");
}
if (!empty($match[ 2 ])) {
$file = SMARTY_SYSPLUGINS_DIR . strtolower($plugin_name) . '.php';
if (isset($this->plugin_files[ $file ])) {
if ($this->plugin_files[ $file ] !== false) {
return $this->plugin_files[ $file ];
} else {
return false;
}
} else {
if (is_file($file)) {
$this->plugin_files[ $file ] = $file;
require_once($file);
return $file;
} else {
$this->plugin_files[ $file ] = false;
return false;
}
}
}
// plugin filename is expected to be: [type].[name].php
$_plugin_filename = "{$match[1]}.{$match[4]}.php";
$_lower_filename = strtolower($_plugin_filename);
if (isset($this->plugin_files)) {
if (isset($this->plugin_files[ 'plugins_dir' ][ $_lower_filename ])) {
if (!$smarty->use_include_path || $this->plugin_files[ 'plugins_dir' ][ $_lower_filename ] !== false) {
return $this->plugin_files[ 'plugins_dir' ][ $_lower_filename ];
}
}
if (!$smarty->use_include_path || $smarty->ext->_getIncludePath->isNewIncludePath($smarty)) {
unset($this->plugin_files[ 'include_path' ]);
} else {
if (isset($this->plugin_files[ 'include_path' ][ $_lower_filename ])) {
return $this->plugin_files[ 'include_path' ][ $_lower_filename ];
}
}
}
$_file_names = array($_plugin_filename);
if ($_lower_filename !== $_plugin_filename) {
$_file_names[] = $_lower_filename;
}
$_p_dirs = $smarty->getPluginsDir();
if (!isset($this->plugin_files[ 'plugins_dir' ][ $_lower_filename ])) {
// loop through plugin dirs and find the plugin
foreach ($_p_dirs as $_plugin_dir) {
foreach ($_file_names as $name) {
$file = $_plugin_dir . $name;
if (is_file($file)) {
$this->plugin_files[ 'plugins_dir' ][ $_lower_filename ] = $file;
require_once($file);
return $file;
}
$this->plugin_files[ 'plugins_dir' ][ $_lower_filename ] = false;
}
}
}
if ($smarty->use_include_path) {
foreach ($_file_names as $_file_name) {
// try PHP include_path
$file = $smarty->ext->_getIncludePath->getIncludePath($_p_dirs, $_file_name, $smarty);
$this->plugin_files[ 'include_path' ][ $_lower_filename ] = $file;
if ($file !== false) {
require_once($file);
return $file;
}
}
}
// no plugin loaded
return false;
}
} | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_unregisterplugin.php | Extend/Package/smarty/sysplugins/smarty_internal_method_unregisterplugin.php | <?php
/**
* Smarty Method UnregisterPlugin
*
* Smarty::unregisterPlugin() method
*
* @package Smarty
* @subpackage PluginsInternal
* @author Uwe Tews
*/
class Smarty_Internal_Method_UnregisterPlugin
{
/**
* Valid for Smarty and template object
*
* @var int
*/
public $objMap = 3;
/**
* Registers plugin to be used in templates
*
* @api Smarty::unregisterPlugin()
* @link http://www.smarty.net/docs/en/api.unregister.plugin.tpl
*
* @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj
* @param string $type plugin type
* @param string $name name of template tag
*
* @return \Smarty|\Smarty_Internal_Template
*/
public function unregisterPlugin(Smarty_Internal_TemplateBase $obj, $type, $name)
{
$smarty = $obj->_getSmartyObj();
if (isset($smarty->registered_plugins[ $type ][ $name ])) {
unset($smarty->registered_plugins[ $type ][ $name ]);
}
return $obj;
}
} | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_unloadfilter.php | Extend/Package/smarty/sysplugins/smarty_internal_method_unloadfilter.php | <?php
/**
* Smarty Method UnloadFilter
*
* Smarty::unloadFilter() method
*
* @package Smarty
* @subpackage PluginsInternal
* @author Uwe Tews
*/
class Smarty_Internal_Method_UnloadFilter extends Smarty_Internal_Method_LoadFilter
{
/**
* load a filter of specified type and name
*
* @api Smarty::unloadFilter()
*
* @link http://www.smarty.net/docs/en/api.unload.filter.tpl
*
* @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj
* @param string $type filter type
* @param string $name filter name
*
* @return Smarty_Internal_TemplateBase
* @throws \SmartyException
*/
public function unloadFilter(Smarty_Internal_TemplateBase $obj, $type, $name)
{
$smarty = $obj->_getSmartyObj();
$this->_checkFilterType($type);
if (isset($smarty->registered_filters[ $type ])) {
$_filter_name = "smarty_{$type}filter_{$name}";
if (isset($smarty->registered_filters[ $type ][ $_filter_name ])) {
unset ($smarty->registered_filters[ $type ][ $_filter_name ]);
if (empty($smarty->registered_filters[ $type ])) {
unset($smarty->registered_filters[ $type ]);
}
}
}
return $obj;
}
} | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_debug.php | Extend/Package/smarty/sysplugins/smarty_internal_debug.php | <?php
/**
* Smarty Internal Plugin Debug
* Class to collect data for the Smarty Debugging Console
*
* @package Smarty
* @subpackage Debug
* @author Uwe Tews
*/
/**
* Smarty Internal Plugin Debug Class
*
* @package Smarty
* @subpackage Debug
*/
class Smarty_Internal_Debug extends Smarty_Internal_Data
{
/**
* template data
*
* @var array
*/
public $template_data = array();
/**
* List of uid's which shall be ignored
*
* @var array
*/
public $ignore_uid = array();
/**
* Index of display() and fetch() calls
*
* @var int
*/
public $index = 0;
/**
* Counter for window offset
*
* @var int
*/
public $offset = 0;
/**
* Start logging template
*
* @param \Smarty_Internal_Template $template template
* @param null $mode true: display false: fetch null: subtemplate
*/
public function start_template(Smarty_Internal_Template $template, $mode = null)
{
if (isset($mode) && !$template->_isSubTpl()) {
$this->index ++;
$this->offset ++;
$this->template_data[ $this->index ] = null;
}
$key = $this->get_key($template);
$this->template_data[ $this->index ][ $key ][ 'start_template_time' ] = microtime(true);
}
/**
* End logging of cache time
*
* @param \Smarty_Internal_Template $template cached template
*/
public function end_template(Smarty_Internal_Template $template)
{
$key = $this->get_key($template);
$this->template_data[ $this->index ][ $key ][ 'total_time' ] +=
microtime(true) - $this->template_data[ $this->index ][ $key ][ 'start_template_time' ];
//$this->template_data[$this->index][$key]['properties'] = $template->properties;
}
/**
* Start logging of compile time
*
* @param \Smarty_Internal_Template $template
*/
public function start_compile(Smarty_Internal_Template $template)
{
static $_is_stringy = array('string' => true, 'eval' => true);
if (!empty($template->compiler->trace_uid)) {
$key = $template->compiler->trace_uid;
if (!isset($this->template_data[ $this->index ][ $key ])) {
if (isset($_is_stringy[ $template->source->type ])) {
$this->template_data[ $this->index ][ $key ][ 'name' ] =
'\'' . substr($template->source->name, 0, 25) . '...\'';
} else {
$this->template_data[ $this->index ][ $key ][ 'name' ] = $template->source->filepath;
}
$this->template_data[ $this->index ][ $key ][ 'compile_time' ] = 0;
$this->template_data[ $this->index ][ $key ][ 'render_time' ] = 0;
$this->template_data[ $this->index ][ $key ][ 'cache_time' ] = 0;
}
} else {
if (isset($this->ignore_uid[ $template->source->uid ])) {
return;
}
$key = $this->get_key($template);
}
$this->template_data[ $this->index ][ $key ][ 'start_time' ] = microtime(true);
}
/**
* End logging of compile time
*
* @param \Smarty_Internal_Template $template
*/
public function end_compile(Smarty_Internal_Template $template)
{
if (!empty($template->compiler->trace_uid)) {
$key = $template->compiler->trace_uid;
} else {
if (isset($this->ignore_uid[ $template->source->uid ])) {
return;
}
$key = $this->get_key($template);
}
$this->template_data[ $this->index ][ $key ][ 'compile_time' ] +=
microtime(true) - $this->template_data[ $this->index ][ $key ][ 'start_time' ];
}
/**
* Start logging of render time
*
* @param \Smarty_Internal_Template $template
*/
public function start_render(Smarty_Internal_Template $template)
{
$key = $this->get_key($template);
$this->template_data[ $this->index ][ $key ][ 'start_time' ] = microtime(true);
}
/**
* End logging of compile time
*
* @param \Smarty_Internal_Template $template
*/
public function end_render(Smarty_Internal_Template $template)
{
$key = $this->get_key($template);
$this->template_data[ $this->index ][ $key ][ 'render_time' ] +=
microtime(true) - $this->template_data[ $this->index ][ $key ][ 'start_time' ];
}
/**
* Start logging of cache time
*
* @param \Smarty_Internal_Template $template cached template
*/
public function start_cache(Smarty_Internal_Template $template)
{
$key = $this->get_key($template);
$this->template_data[ $this->index ][ $key ][ 'start_time' ] = microtime(true);
}
/**
* End logging of cache time
*
* @param \Smarty_Internal_Template $template cached template
*/
public function end_cache(Smarty_Internal_Template $template)
{
$key = $this->get_key($template);
$this->template_data[ $this->index ][ $key ][ 'cache_time' ] +=
microtime(true) - $this->template_data[ $this->index ][ $key ][ 'start_time' ];
}
/**
* Register template object
*
* @param \Smarty_Internal_Template $template cached template
*/
public function register_template(Smarty_Internal_Template $template)
{
}
/**
* Register data object
*
* @param \Smarty_Data $data data object
*/
public static function register_data(Smarty_Data $data)
{
}
/**
* Opens a window for the Smarty Debugging Console and display the data
*
* @param Smarty_Internal_Template|Smarty $obj object to debug
* @param bool $full
*
* @throws \Exception
* @throws \SmartyException
*/
public function display_debug($obj, $full = false)
{
if (!$full) {
$this->offset ++;
$savedIndex = $this->index;
$this->index = 9999;
}
$smarty = $obj->_getSmartyObj();
// create fresh instance of smarty for displaying the debug console
// to avoid problems if the application did overload the Smarty class
$debObj = new Smarty();
// copy the working dirs from application
$debObj->setCompileDir($smarty->getCompileDir());
// init properties by hand as user may have edited the original Smarty class
$debObj->setPluginsDir(is_dir(__DIR__ . '/../plugins') ? __DIR__ . '/../plugins' : $smarty->getPluginsDir());
$debObj->force_compile = false;
$debObj->compile_check = Smarty::COMPILECHECK_ON;
$debObj->left_delimiter = '{';
$debObj->right_delimiter = '}';
$debObj->security_policy = null;
$debObj->debugging = false;
$debObj->debugging_ctrl = 'NONE';
$debObj->error_reporting = E_ALL & ~E_NOTICE;
$debObj->debug_tpl = isset($smarty->debug_tpl) ? $smarty->debug_tpl : 'file:' . __DIR__ . '/../debug.tpl';
$debObj->registered_plugins = array();
$debObj->registered_resources = array();
$debObj->registered_filters = array();
$debObj->autoload_filters = array();
$debObj->default_modifiers = array();
$debObj->escape_html = true;
$debObj->caching = Smarty::CACHING_OFF;
$debObj->compile_id = null;
$debObj->cache_id = null;
// prepare information of assigned variables
$ptr = $this->get_debug_vars($obj);
$_assigned_vars = $ptr->tpl_vars;
ksort($_assigned_vars);
$_config_vars = $ptr->config_vars;
ksort($_config_vars);
$debugging = $smarty->debugging;
$_template = new Smarty_Internal_Template($debObj->debug_tpl, $debObj);
if ($obj->_isTplObj()) {
$_template->assign('template_name', $obj->source->type . ':' . $obj->source->name);
}
if ($obj->_objType === 1 || $full) {
$_template->assign('template_data', $this->template_data[ $this->index ]);
} else {
$_template->assign('template_data', null);
}
$_template->assign('assigned_vars', $_assigned_vars);
$_template->assign('config_vars', $_config_vars);
$_template->assign('execution_time', microtime(true) - $smarty->start_time);
$_template->assign('display_mode', $debugging === 2 || !$full);
$_template->assign('offset', $this->offset * 50);
echo $_template->fetch();
if (isset($full)) {
$this->index --;
}
if (!$full) {
$this->index = $savedIndex;
}
}
/**
* Recursively gets variables from all template/data scopes
*
* @param Smarty_Internal_Template|Smarty_Data $obj object to debug
*
* @return StdClass
*/
public function get_debug_vars($obj)
{
$config_vars = array();
foreach ($obj->config_vars as $key => $var) {
$config_vars[ $key ][ 'value' ] = $var;
if ($obj->_isTplObj()) {
$config_vars[ $key ][ 'scope' ] = $obj->source->type . ':' . $obj->source->name;
} elseif ($obj->_isDataObj()) {
$tpl_vars[ $key ][ 'scope' ] = $obj->dataObjectName;
} else {
$config_vars[ $key ][ 'scope' ] = 'Smarty object';
}
}
$tpl_vars = array();
foreach ($obj->tpl_vars as $key => $var) {
foreach ($var as $varkey => $varvalue) {
if ($varkey === 'value') {
$tpl_vars[ $key ][ $varkey ] = $varvalue;
} else {
if ($varkey === 'nocache') {
if ($varvalue === true) {
$tpl_vars[ $key ][ $varkey ] = $varvalue;
}
} else {
if ($varkey !== 'scope' || $varvalue !== 0) {
$tpl_vars[ $key ][ 'attributes' ][ $varkey ] = $varvalue;
}
}
}
}
if ($obj->_isTplObj()) {
$tpl_vars[ $key ][ 'scope' ] = $obj->source->type . ':' . $obj->source->name;
} elseif ($obj->_isDataObj()) {
$tpl_vars[ $key ][ 'scope' ] = $obj->dataObjectName;
} else {
$tpl_vars[ $key ][ 'scope' ] = 'Smarty object';
}
}
if (isset($obj->parent)) {
$parent = $this->get_debug_vars($obj->parent);
foreach ($parent->tpl_vars as $name => $pvar) {
if (isset($tpl_vars[ $name ]) && $tpl_vars[ $name ][ 'value' ] === $pvar[ 'value' ]) {
$tpl_vars[ $name ][ 'scope' ] = $pvar[ 'scope' ];
}
}
$tpl_vars = array_merge($parent->tpl_vars, $tpl_vars);
foreach ($parent->config_vars as $name => $pvar) {
if (isset($config_vars[ $name ]) && $config_vars[ $name ][ 'value' ] === $pvar[ 'value' ]) {
$config_vars[ $name ][ 'scope' ] = $pvar[ 'scope' ];
}
}
$config_vars = array_merge($parent->config_vars, $config_vars);
} else {
foreach (Smarty::$global_tpl_vars as $key => $var) {
if (!array_key_exists($key, $tpl_vars)) {
foreach ($var as $varkey => $varvalue) {
if ($varkey === 'value') {
$tpl_vars[ $key ][ $varkey ] = $varvalue;
} else {
if ($varkey === 'nocache') {
if ($varvalue === true) {
$tpl_vars[ $key ][ $varkey ] = $varvalue;
}
} else {
if ($varkey !== 'scope' || $varvalue !== 0) {
$tpl_vars[ $key ][ 'attributes' ][ $varkey ] = $varvalue;
}
}
}
}
$tpl_vars[ $key ][ 'scope' ] = 'Global';
}
}
}
return (object) array('tpl_vars' => $tpl_vars, 'config_vars' => $config_vars);
}
/**
* Return key into $template_data for template
*
* @param \Smarty_Internal_Template $template template object
*
* @return string key into $template_data
*/
private function get_key(Smarty_Internal_Template $template)
{
static $_is_stringy = array('string' => true, 'eval' => true);
// calculate Uid if not already done
if ($template->source->uid === '') {
$template->source->filepath;
}
$key = $template->source->uid;
if (isset($this->template_data[ $this->index ][ $key ])) {
return $key;
} else {
if (isset($_is_stringy[ $template->source->type ])) {
$this->template_data[ $this->index ][ $key ][ 'name' ] =
'\'' . substr($template->source->name, 0, 25) . '...\'';
} else {
$this->template_data[ $this->index ][ $key ][ 'name' ] = $template->source->filepath;
}
$this->template_data[ $this->index ][ $key ][ 'compile_time' ] = 0;
$this->template_data[ $this->index ][ $key ][ 'render_time' ] = 0;
$this->template_data[ $this->index ][ $key ][ 'cache_time' ] = 0;
$this->template_data[ $this->index ][ $key ][ 'total_time' ] = 0;
return $key;
}
}
/**
* Ignore template
*
* @param \Smarty_Internal_Template $template
*/
public function ignore(Smarty_Internal_Template $template)
{
// calculate Uid if not already done
if ($template->source->uid === '') {
$template->source->filepath;
}
$this->ignore_uid[ $template->source->uid ] = true;
}
/**
* handle 'URL' debugging mode
*
* @param Smarty $smarty
*/
public function debugUrl(Smarty $smarty)
{
if (isset($_SERVER[ 'QUERY_STRING' ])) {
$_query_string = $_SERVER[ 'QUERY_STRING' ];
} else {
$_query_string = '';
}
if (false !== strpos($_query_string, $smarty->smarty_debug_id)) {
if (false !== strpos($_query_string, $smarty->smarty_debug_id . '=on')) {
// enable debugging for this browser session
setcookie('SMARTY_DEBUG', true);
$smarty->debugging = true;
} elseif (false !== strpos($_query_string, $smarty->smarty_debug_id . '=off')) {
// disable debugging for this browser session
setcookie('SMARTY_DEBUG', false);
$smarty->debugging = false;
} else {
// enable debugging for this page
$smarty->debugging = true;
}
} else {
if (isset($_COOKIE[ 'SMARTY_DEBUG' ])) {
$smarty->debugging = true;
}
}
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_method_unregisterresource.php | Extend/Package/smarty/sysplugins/smarty_internal_method_unregisterresource.php | <?php
/**
* Smarty Method UnregisterResource
*
* Smarty::unregisterResource() method
*
* @package Smarty
* @subpackage PluginsInternal
* @author Uwe Tews
*/
class Smarty_Internal_Method_UnregisterResource
{
/**
* Valid for Smarty and template object
*
* @var int
*/
public $objMap = 3;
/**
* Registers a resource to fetch a template
*
* @api Smarty::unregisterResource()
* @link http://www.smarty.net/docs/en/api.unregister.resource.tpl
*
* @param \Smarty_Internal_TemplateBase|\Smarty_Internal_Template|\Smarty $obj
* @param string $type name of resource type
*
* @return \Smarty|\Smarty_Internal_Template
*/
public function unregisterResource(Smarty_Internal_TemplateBase $obj, $type)
{
$smarty = $obj->_getSmartyObj();
if (isset($smarty->registered_resources[ $type ])) {
unset($smarty->registered_resources[ $type ]);
}
return $obj;
}
} | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_runtime_capture.php | Extend/Package/smarty/sysplugins/smarty_internal_runtime_capture.php | <?php
/**
* Runtime Extension Capture
*
* @package Smarty
* @subpackage PluginsInternal
* @author Uwe Tews
*/
class Smarty_Internal_Runtime_Capture
{
/**
* Flag that this instance will not be cached
*
* @var bool
*/
public $isPrivateExtension = true;
/**
* Stack of capture parameter
*
* @var array
*/
private $captureStack = array();
/**
* Current open capture sections
*
* @var int
*/
private $captureCount = 0;
/**
* Count stack
*
* @var int[]
*/
private $countStack = array();
/**
* Named buffer
*
* @var string[]
*/
private $namedBuffer = array();
/**
* Flag if callbacks are registered
*
* @var bool
*/
private $isRegistered = false;
/**
* Open capture section
*
* @param \Smarty_Internal_Template $_template
* @param string $buffer capture name
* @param string $assign variable name
* @param string $append variable name
*/
public function open(Smarty_Internal_Template $_template, $buffer, $assign, $append)
{
if (!$this->isRegistered) {
$this->register($_template);
}
$this->captureStack[] = array($buffer,
$assign,
$append);
$this->captureCount ++;
ob_start();
}
/**
* Register callbacks in template class
*
* @param \Smarty_Internal_Template $_template
*/
private function register(Smarty_Internal_Template $_template)
{
$_template->startRenderCallbacks[] = array($this,
'startRender');
$_template->endRenderCallbacks[] = array($this,
'endRender');
$this->startRender($_template);
$this->isRegistered = true;
}
/**
* Start render callback
*
* @param \Smarty_Internal_Template $_template
*/
public function startRender(Smarty_Internal_Template $_template)
{
$this->countStack[] = $this->captureCount;
$this->captureCount = 0;
}
/**
* Close capture section
*
* @param \Smarty_Internal_Template $_template
*
* @throws \SmartyException
*/
public function close(Smarty_Internal_Template $_template)
{
if ($this->captureCount) {
list($buffer, $assign, $append) = array_pop($this->captureStack);
$this->captureCount --;
if (isset($assign)) {
$_template->assign($assign, ob_get_contents());
}
if (isset($append)) {
$_template->append($append, ob_get_contents());
}
$this->namedBuffer[ $buffer ] = ob_get_clean();
} else {
$this->error($_template);
}
}
/**
* Error exception on not matching {capture}{/capture}
*
* @param \Smarty_Internal_Template $_template
*
* @throws \SmartyException
*/
public function error(Smarty_Internal_Template $_template)
{
throw new SmartyException("Not matching {capture}{/capture} in '{$_template->template_resource}'");
}
/**
* Return content of named capture buffer by key or as array
*
* @param \Smarty_Internal_Template $_template
* @param string|null $name
*
* @return string|string[]|null
*/
public function getBuffer(Smarty_Internal_Template $_template, $name = null)
{
if (isset($name)) {
return isset($this->namedBuffer[ $name ]) ? $this->namedBuffer[ $name ] : null;
} else {
return $this->namedBuffer;
}
}
/**
* End render callback
*
* @param \Smarty_Internal_Template $_template
*
* @throws \SmartyException
*/
public function endRender(Smarty_Internal_Template $_template)
{
if ($this->captureCount) {
$this->error($_template);
} else {
$this->captureCount = array_pop($this->countStack);
}
}
} | php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
xcg340122/PHP300Framework2x | https://github.com/xcg340122/PHP300Framework2x/blob/2ba403cd277680a050c457d39db2aef652fb8e8f/Extend/Package/smarty/sysplugins/smarty_internal_parsetree_dqcontent.php | Extend/Package/smarty/sysplugins/smarty_internal_parsetree_dqcontent.php | <?php
/**
* Smarty Internal Plugin Templateparser Parse Tree
* These are classes to build parse tree in the template parser
*
* @package Smarty
* @subpackage Compiler
* @author Thue Kristensen
* @author Uwe Tews
*/
/**
* Raw chars as part of a double quoted string.
*
* @package Smarty
* @subpackage Compiler
* @ignore
*/
class Smarty_Internal_ParseTree_DqContent extends Smarty_Internal_ParseTree
{
/**
* Create parse tree buffer with string content
*
* @param string $data string section
*/
public function __construct($data)
{
$this->data = $data;
}
/**
* Return content as double quoted string
*
* @param \Smarty_Internal_Templateparser $parser
*
* @return string doubled quoted string
*/
public function to_smarty_php(Smarty_Internal_Templateparser $parser)
{
return '"' . $this->data . '"';
}
}
| php | Apache-2.0 | 2ba403cd277680a050c457d39db2aef652fb8e8f | 2026-01-05T04:52:44.635355Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.