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 |
|---|---|---|---|---|---|---|---|---|
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cookie/CookieStore.php | system/Cookie/CookieStore.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cookie;
use ArrayIterator;
use CodeIgniter\Cookie\Exceptions\CookieException;
use Countable;
use IteratorAggregate;
use Traversable;
/**
* The CookieStore object represents an immutable collection of `Cookie` value objects.
*
* @implements IteratorAggregate<string, Cookie>
* @see \CodeIgniter\Cookie\CookieStoreTest
*/
class CookieStore implements Countable, IteratorAggregate
{
/**
* The cookie collection.
*
* @var array<string, Cookie>
*/
protected $cookies = [];
/**
* Creates a CookieStore from an array of `Set-Cookie` headers.
*
* @param list<string> $headers
*
* @return static
*
* @throws CookieException
*/
public static function fromCookieHeaders(array $headers, bool $raw = false)
{
/**
* @var list<Cookie> $cookies
*/
$cookies = array_filter(array_map(static function (string $header) use ($raw) {
try {
return Cookie::fromHeaderString($header, $raw);
} catch (CookieException $e) {
log_message('error', (string) $e);
return false;
}
}, $headers));
return new static($cookies);
}
/**
* @param array<array-key, Cookie> $cookies
*
* @throws CookieException
*/
final public function __construct(array $cookies)
{
$this->validateCookies($cookies);
foreach ($cookies as $cookie) {
$this->cookies[$cookie->getId()] = $cookie;
}
}
/**
* Checks if a `Cookie` object identified by name and
* prefix is present in the collection.
*/
public function has(string $name, string $prefix = '', ?string $value = null): bool
{
$name = $prefix . $name;
foreach ($this->cookies as $cookie) {
if ($cookie->getPrefixedName() !== $name) {
continue;
}
if ($value === null) {
return true; // for BC
}
return $cookie->getValue() === $value;
}
return false;
}
/**
* Retrieves an instance of `Cookie` identified by a name and prefix.
* This throws an exception if not found.
*
* @throws CookieException
*/
public function get(string $name, string $prefix = ''): Cookie
{
$name = $prefix . $name;
foreach ($this->cookies as $cookie) {
if ($cookie->getPrefixedName() === $name) {
return $cookie;
}
}
throw CookieException::forUnknownCookieInstance([$name, $prefix]);
}
/**
* Store a new cookie and return a new collection. The original collection
* is left unchanged.
*
* @return static
*/
public function put(Cookie $cookie)
{
$store = clone $this;
$store->cookies[$cookie->getId()] = $cookie;
return $store;
}
/**
* Removes a cookie from a collection and returns an updated collection.
* The original collection is left unchanged.
*
* Removing a cookie from the store **DOES NOT** delete it from the browser.
* If you intend to delete a cookie *from the browser*, you must put an empty
* value cookie with the same name to the store.
*
* @return static
*/
public function remove(string $name, string $prefix = '')
{
$default = Cookie::setDefaults();
$id = implode(';', [$prefix . $name, $default['path'], $default['domain']]);
$store = clone $this;
foreach (array_keys($store->cookies) as $index) {
if ($index === $id) {
unset($store->cookies[$index]);
}
}
return $store;
}
/**
* Returns all cookie instances in store.
*
* @return array<string, Cookie>
*/
public function display(): array
{
return $this->cookies;
}
/**
* Clears the cookie collection.
*/
public function clear(): void
{
$this->cookies = [];
}
/**
* Gets the Cookie count in this collection.
*/
public function count(): int
{
return count($this->cookies);
}
/**
* Gets the iterator for the cookie collection.
*
* @return Traversable<string, Cookie>
*/
public function getIterator(): Traversable
{
return new ArrayIterator($this->cookies);
}
/**
* Validates all cookies passed to be instances of Cookie.
*
* @throws CookieException
*/
protected function validateCookies(array $cookies): void
{
foreach ($cookies as $index => $cookie) {
$type = get_debug_type($cookie);
if (! $cookie instanceof Cookie) {
throw CookieException::forInvalidCookieInstance([static::class, Cookie::class, $type, $index]);
}
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cookie/Cookie.php | system/Cookie/Cookie.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cookie;
use ArrayAccess;
use CodeIgniter\Cookie\Exceptions\CookieException;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Exceptions\LogicException;
use CodeIgniter\I18n\Time;
use Config\Cookie as CookieConfig;
use DateTimeInterface;
use ReturnTypeWillChange;
/**
* A `Cookie` class represents an immutable HTTP cookie value object.
*
* Being immutable, modifying one or more of its attributes will return
* a new `Cookie` instance, rather than modifying itself. Users should
* reassign this new instance to a new variable to capture it.
*
* ```php
* $cookie = new Cookie('test_cookie', 'test_value');
* $cookie->getName(); // test_cookie
*
* $cookie->withName('prod_cookie');
* $cookie->getName(); // test_cookie
*
* $cookie2 = $cookie->withName('prod_cookie');
* $cookie2->getName(); // prod_cookie
* ```
*
* @template-implements ArrayAccess<string, bool|int|string>
* @see \CodeIgniter\Cookie\CookieTest
*/
class Cookie implements ArrayAccess, CloneableCookieInterface
{
/**
* @var string
*/
protected $prefix = '';
/**
* @var string
*/
protected $name;
/**
* @var string
*/
protected $value;
/**
* @var int Unix timestamp
*/
protected $expires;
/**
* @var string
*/
protected $path = '/';
/**
* @var string
*/
protected $domain = '';
/**
* @var bool
*/
protected $secure = false;
/**
* @var bool
*/
protected $httponly = true;
/**
* @var string
*/
protected $samesite = self::SAMESITE_LAX;
/**
* @var bool
*/
protected $raw = false;
/**
* Default attributes for a Cookie object. The keys here are the
* lowercase attribute names. Do not camelCase!
*
* @var array{
* prefix: string,
* expires: int,
* path: string,
* domain: string,
* secure: bool,
* httponly: bool,
* samesite: string,
* raw: bool,
* }
*/
private static array $defaults = [
'prefix' => '',
'expires' => 0,
'path' => '/',
'domain' => '',
'secure' => false,
'httponly' => true,
'samesite' => self::SAMESITE_LAX,
'raw' => false,
];
/**
* A cookie name can be any US-ASCII characters, except control characters,
* spaces, tabs, or separator characters.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
* @see https://tools.ietf.org/html/rfc2616#section-2.2
*/
private static string $reservedCharsList = "=,; \t\r\n\v\f()<>@:\\\"/[]?{}";
/**
* Set the default attributes to a Cookie instance by injecting
* the values from the `CookieConfig` config or an array.
*
* This method is called from Response::__construct().
*
* @param array{
* prefix?: string,
* expires?: int,
* path?: string,
* domain?: string,
* secure?: bool,
* httponly?: bool,
* samesite?: string,
* raw?: bool,
* }|CookieConfig $config
*
* @return array{
* prefix: string,
* expires: int,
* path: string,
* domain: string,
* secure: bool,
* httponly: bool,
* samesite: string,
* raw: bool,
* } The old defaults array. Useful for resetting.
*/
public static function setDefaults($config = [])
{
$oldDefaults = self::$defaults;
$newDefaults = [];
if ($config instanceof CookieConfig) {
$newDefaults = [
'prefix' => $config->prefix,
'expires' => $config->expires,
'path' => $config->path,
'domain' => $config->domain,
'secure' => $config->secure,
'httponly' => $config->httponly,
'samesite' => $config->samesite,
'raw' => $config->raw,
];
} elseif (is_array($config)) {
$newDefaults = $config;
}
// This array union ensures that even if passed `$config` is not
// `CookieConfig` or `array`, no empty defaults will occur.
self::$defaults = $newDefaults + $oldDefaults;
return $oldDefaults;
}
// =========================================================================
// CONSTRUCTORS
// =========================================================================
/**
* Create a new Cookie instance from a `Set-Cookie` header.
*
* @return static
*
* @throws CookieException
*/
public static function fromHeaderString(string $cookie, bool $raw = false)
{
$data = self::$defaults;
$data['raw'] = $raw;
$parts = preg_split('/\;[\s]*/', $cookie);
$part = explode('=', array_shift($parts), 2);
$name = $raw ? $part[0] : urldecode($part[0]);
$value = isset($part[1]) ? ($raw ? $part[1] : urldecode($part[1])) : '';
unset($part);
foreach ($parts as $part) {
if (str_contains($part, '=')) {
[$attr, $val] = explode('=', $part);
} else {
$attr = $part;
$val = true;
}
$data[strtolower($attr)] = $val;
}
return new static($name, $value, $data);
}
/**
* Construct a new Cookie instance.
*
* @param string $name The cookie's name
* @param string $value The cookie's value
* @param array{prefix?: string, max-age?: int|numeric-string, expires?: DateTimeInterface|int|string, path?: string, domain?: string, secure?: bool, httponly?: bool, samesite?: string, raw?: bool} $options The cookie's options
*
* @throws CookieException
*/
final public function __construct(string $name, string $value = '', array $options = [])
{
$options += self::$defaults;
$options['expires'] = static::convertExpiresTimestamp($options['expires']);
// If both `Expires` and `Max-Age` are set, `Max-Age` has precedence.
if (isset($options['max-age']) && is_numeric($options['max-age'])) {
$options['expires'] = Time::now()->getTimestamp() + (int) $options['max-age'];
unset($options['max-age']);
}
// to preserve backward compatibility with array-based cookies in previous CI versions
$prefix = ($options['prefix'] === '') ? self::$defaults['prefix'] : $options['prefix'];
$path = $options['path'] ?: self::$defaults['path'];
$domain = $options['domain'] ?: self::$defaults['domain'];
// empty string SameSite should use the default for browsers
$samesite = $options['samesite'] ?: self::$defaults['samesite'];
$raw = $options['raw'];
$secure = $options['secure'];
$httponly = $options['httponly'];
$this->validateName($name, $raw);
$this->validatePrefix($prefix, $secure, $path, $domain);
$this->validateSameSite($samesite, $secure);
$this->prefix = $prefix;
$this->name = $name;
$this->value = $value;
$this->expires = static::convertExpiresTimestamp($options['expires']);
$this->path = $path;
$this->domain = $domain;
$this->secure = $secure;
$this->httponly = $httponly;
$this->samesite = ucfirst(strtolower($samesite));
$this->raw = $raw;
}
// =========================================================================
// GETTERS
// =========================================================================
/**
* {@inheritDoc}
*/
public function getId(): string
{
return implode(';', [$this->getPrefixedName(), $this->getPath(), $this->getDomain()]);
}
/**
* {@inheritDoc}
*/
public function getPrefix(): string
{
return $this->prefix;
}
/**
* {@inheritDoc}
*/
public function getName(): string
{
return $this->name;
}
/**
* {@inheritDoc}
*/
public function getPrefixedName(): string
{
$name = $this->getPrefix();
if ($this->isRaw()) {
$name .= $this->getName();
} else {
$search = str_split(self::$reservedCharsList);
$replace = array_map(rawurlencode(...), $search);
$name .= str_replace($search, $replace, $this->getName());
}
return $name;
}
/**
* {@inheritDoc}
*/
public function getValue(): string
{
return $this->value;
}
/**
* {@inheritDoc}
*/
public function getExpiresTimestamp(): int
{
return $this->expires;
}
/**
* {@inheritDoc}
*/
public function getExpiresString(): string
{
return gmdate(self::EXPIRES_FORMAT, $this->expires);
}
/**
* {@inheritDoc}
*/
public function isExpired(): bool
{
return $this->expires === 0 || $this->expires < Time::now()->getTimestamp();
}
/**
* {@inheritDoc}
*/
public function getMaxAge(): int
{
$maxAge = $this->expires - Time::now()->getTimestamp();
return $maxAge >= 0 ? $maxAge : 0;
}
/**
* {@inheritDoc}
*/
public function getPath(): string
{
return $this->path;
}
/**
* {@inheritDoc}
*/
public function getDomain(): string
{
return $this->domain;
}
/**
* {@inheritDoc}
*/
public function isSecure(): bool
{
return $this->secure;
}
/**
* {@inheritDoc}
*/
public function isHTTPOnly(): bool
{
return $this->httponly;
}
/**
* {@inheritDoc}
*/
public function getSameSite(): string
{
return $this->samesite;
}
/**
* {@inheritDoc}
*/
public function isRaw(): bool
{
return $this->raw;
}
/**
* {@inheritDoc}
*/
public function getOptions(): array
{
// This is the order of options in `setcookie`. DO NOT CHANGE.
return [
'expires' => $this->expires,
'path' => $this->path,
'domain' => $this->domain,
'secure' => $this->secure,
'httponly' => $this->httponly,
'samesite' => $this->samesite ?: ucfirst(self::SAMESITE_LAX),
];
}
// =========================================================================
// CLONING
// =========================================================================
/**
* {@inheritDoc}
*/
public function withPrefix(string $prefix = '')
{
$this->validatePrefix($prefix, $this->secure, $this->path, $this->domain);
$cookie = clone $this;
$cookie->prefix = $prefix;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withName(string $name)
{
$this->validateName($name, $this->raw);
$cookie = clone $this;
$cookie->name = $name;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withValue(string $value)
{
$cookie = clone $this;
$cookie->value = $value;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withExpires($expires)
{
$cookie = clone $this;
$cookie->expires = static::convertExpiresTimestamp($expires);
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withExpired()
{
$cookie = clone $this;
$cookie->expires = 0;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withPath(?string $path)
{
$path = $path !== null && $path !== '' && $path !== '0' ? $path : self::$defaults['path'];
$this->validatePrefix($this->prefix, $this->secure, $path, $this->domain);
$cookie = clone $this;
$cookie->path = $path;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withDomain(?string $domain)
{
$domain ??= self::$defaults['domain'];
$this->validatePrefix($this->prefix, $this->secure, $this->path, $domain);
$cookie = clone $this;
$cookie->domain = $domain;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withSecure(bool $secure = true)
{
$this->validatePrefix($this->prefix, $secure, $this->path, $this->domain);
$this->validateSameSite($this->samesite, $secure);
$cookie = clone $this;
$cookie->secure = $secure;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withHTTPOnly(bool $httponly = true)
{
$cookie = clone $this;
$cookie->httponly = $httponly;
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withSameSite(string $samesite)
{
$this->validateSameSite($samesite, $this->secure);
$cookie = clone $this;
$cookie->samesite = ucfirst(strtolower($samesite));
return $cookie;
}
/**
* {@inheritDoc}
*/
public function withRaw(bool $raw = true)
{
$this->validateName($this->name, $raw);
$cookie = clone $this;
$cookie->raw = $raw;
return $cookie;
}
// =========================================================================
// ARRAY ACCESS FOR BC
// =========================================================================
/**
* Whether an offset exists.
*
* @param string $offset
*/
public function offsetExists($offset): bool
{
return $offset === 'expire' ? true : property_exists($this, $offset);
}
/**
* Offset to retrieve.
*
* @param string $offset
*
* @return bool|int|string
*
* @throws InvalidArgumentException
*/
#[ReturnTypeWillChange]
public function offsetGet($offset)
{
if (! $this->offsetExists($offset)) {
throw new InvalidArgumentException(sprintf('Undefined offset "%s".', $offset));
}
return $offset === 'expire' ? $this->expires : $this->{$offset};
}
/**
* Offset to set.
*
* @param string $offset
* @param bool|int|string $value
*
* @throws LogicException
*/
public function offsetSet($offset, $value): void
{
throw new LogicException(sprintf('Cannot set values of properties of %s as it is immutable.', static::class));
}
/**
* Offset to unset.
*
* @param string $offset
*
* @throws LogicException
*/
public function offsetUnset($offset): void
{
throw new LogicException(sprintf('Cannot unset values of properties of %s as it is immutable.', static::class));
}
// =========================================================================
// CONVERTERS
// =========================================================================
/**
* {@inheritDoc}
*/
public function toHeaderString(): string
{
return $this->__toString();
}
/**
* {@inheritDoc}
*/
public function __toString(): string
{
$cookieHeader = [];
if ($this->getValue() === '') {
$cookieHeader[] = $this->getPrefixedName() . '=deleted';
$cookieHeader[] = 'Expires=' . gmdate(self::EXPIRES_FORMAT, 0);
$cookieHeader[] = 'Max-Age=0';
} else {
$value = $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());
$cookieHeader[] = sprintf('%s=%s', $this->getPrefixedName(), $value);
if ($this->getExpiresTimestamp() !== 0) {
$cookieHeader[] = 'Expires=' . $this->getExpiresString();
$cookieHeader[] = 'Max-Age=' . $this->getMaxAge();
}
}
if ($this->getPath() !== '') {
$cookieHeader[] = 'Path=' . $this->getPath();
}
if ($this->getDomain() !== '') {
$cookieHeader[] = 'Domain=' . $this->getDomain();
}
if ($this->isSecure()) {
$cookieHeader[] = 'Secure';
}
if ($this->isHTTPOnly()) {
$cookieHeader[] = 'HttpOnly';
}
$samesite = $this->getSameSite();
if ($samesite === '') {
// modern browsers warn in console logs that an empty SameSite attribute
// will be given the `Lax` value
$samesite = self::SAMESITE_LAX;
}
$cookieHeader[] = 'SameSite=' . ucfirst(strtolower($samesite));
return implode('; ', $cookieHeader);
}
/**
* {@inheritDoc}
*/
public function toArray(): array
{
return [
'name' => $this->name,
'value' => $this->value,
'prefix' => $this->prefix,
'raw' => $this->raw,
] + $this->getOptions();
}
/**
* Converts expires time to Unix format.
*
* @param DateTimeInterface|int|string $expires
*/
protected static function convertExpiresTimestamp($expires = 0): int
{
if ($expires instanceof DateTimeInterface) {
$expires = $expires->format('U');
}
if (! is_string($expires) && ! is_int($expires)) {
throw CookieException::forInvalidExpiresTime(gettype($expires));
}
if (! is_numeric($expires)) {
$expires = strtotime($expires);
if ($expires === false) {
throw CookieException::forInvalidExpiresValue();
}
}
return $expires > 0 ? (int) $expires : 0;
}
// =========================================================================
// VALIDATION
// =========================================================================
/**
* Validates the cookie name per RFC 2616.
*
* If `$raw` is true, names should not contain invalid characters
* as `setrawcookie()` will reject this.
*
* @throws CookieException
*/
protected function validateName(string $name, bool $raw): void
{
if ($raw && strpbrk($name, self::$reservedCharsList) !== false) {
throw CookieException::forInvalidCookieName($name);
}
if ($name === '') {
throw CookieException::forEmptyCookieName();
}
}
/**
* Validates the special prefixes if some attribute requirements are met.
*
* @throws CookieException
*/
protected function validatePrefix(string $prefix, bool $secure, string $path, string $domain): void
{
if (str_starts_with($prefix, '__Secure-') && ! $secure) {
throw CookieException::forInvalidSecurePrefix();
}
if (str_starts_with($prefix, '__Host-') && (! $secure || $domain !== '' || $path !== '/')) {
throw CookieException::forInvalidHostPrefix();
}
}
/**
* Validates the `SameSite` to be within the allowed types.
*
* @throws CookieException
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
*/
protected function validateSameSite(string $samesite, bool $secure): void
{
if ($samesite === '') {
$samesite = self::$defaults['samesite'];
}
if ($samesite === '') {
$samesite = self::SAMESITE_LAX;
}
if (! in_array(strtolower($samesite), self::ALLOWED_SAMESITE_VALUES, true)) {
throw CookieException::forInvalidSameSite($samesite);
}
if (strtolower($samesite) === self::SAMESITE_NONE && ! $secure) {
throw CookieException::forInvalidSameSiteNone();
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cookie/CookieInterface.php | system/Cookie/CookieInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cookie;
/**
* Interface for a value object representation of an HTTP cookie.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie
*/
interface CookieInterface
{
/**
* Cookies will be sent in all contexts, i.e in responses to both
* first-party and cross-origin requests. If `SameSite=None` is set,
* the cookie `Secure` attribute must also be set (or the cookie will be blocked).
*/
public const SAMESITE_NONE = 'none';
/**
* Cookies are not sent on normal cross-site subrequests (for example to
* load images or frames into a third party site), but are sent when a
* user is navigating to the origin site (i.e. when following a link).
*/
public const SAMESITE_LAX = 'lax';
/**
* Cookies will only be sent in a first-party context and not be sent
* along with requests initiated by third party websites.
*/
public const SAMESITE_STRICT = 'strict';
/**
* RFC 6265 allowed values for the "SameSite" attribute.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite
*/
public const ALLOWED_SAMESITE_VALUES = [
self::SAMESITE_NONE,
self::SAMESITE_LAX,
self::SAMESITE_STRICT,
];
/**
* Expires date format.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Date
* @see https://tools.ietf.org/html/rfc7231#section-7.1.1.2
*/
public const EXPIRES_FORMAT = 'D, d-M-Y H:i:s T';
/**
* Returns a unique identifier for the cookie consisting
* of its prefixed name, path, and domain.
*/
public function getId(): string;
/**
* Gets the cookie prefix.
*/
public function getPrefix(): string;
/**
* Gets the cookie name.
*/
public function getName(): string;
/**
* Gets the cookie name prepended with the prefix, if any.
*/
public function getPrefixedName(): string;
/**
* Gets the cookie value.
*/
public function getValue(): string;
/**
* Gets the time in Unix timestamp the cookie expires.
*/
public function getExpiresTimestamp(): int;
/**
* Gets the formatted expires time.
*/
public function getExpiresString(): string;
/**
* Checks if the cookie is expired.
*/
public function isExpired(): bool;
/**
* Gets the "Max-Age" cookie attribute.
*/
public function getMaxAge(): int;
/**
* Gets the "Path" cookie attribute.
*/
public function getPath(): string;
/**
* Gets the "Domain" cookie attribute.
*/
public function getDomain(): string;
/**
* Gets the "Secure" cookie attribute.
*
* Checks if the cookie is only sent to the server when a request is made
* with the `https:` scheme (except on `localhost`), and therefore is more
* resistent to man-in-the-middle attacks.
*/
public function isSecure(): bool;
/**
* Gets the "HttpOnly" cookie attribute.
*
* Checks if JavaScript is forbidden from accessing the cookie.
*/
public function isHTTPOnly(): bool;
/**
* Gets the "SameSite" cookie attribute.
*/
public function getSameSite(): string;
/**
* Checks if the cookie should be sent with no URL encoding.
*/
public function isRaw(): bool;
/**
* Gets the options that are passable to the `setcookie` variant
* available on PHP 7.3+
*
* @return array{
* expires: int,
* path: string,
* domain: string,
* secure: bool,
* httponly: bool,
* samesite: string,
* }
*/
public function getOptions(): array;
/**
* Returns the Cookie as a header value.
*/
public function toHeaderString(): string;
/**
* Returns the string representation of the Cookie object.
*
* @return string
*/
public function __toString();
/**
* Returns the array representation of the Cookie object.
*
* @return array{
* name: string,
* value: string,
* prefix: string,
* raw: bool,
* expires: int,
* path: string,
* domain: string,
* secure: bool,
* httponly: bool,
* samesite: string,
* }
*/
public function toArray(): array;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Cookie/Exceptions/CookieException.php | system/Cookie/Exceptions/CookieException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Cookie\Exceptions;
use CodeIgniter\Exceptions\FrameworkException;
/**
* CookieException is thrown for invalid cookies initialization and management.
*/
class CookieException extends FrameworkException
{
/**
* Thrown for invalid type given for the "Expires" attribute.
*
* @return static
*/
public static function forInvalidExpiresTime(string $type)
{
return new static(lang('Cookie.invalidExpiresTime', [$type]));
}
/**
* Thrown when the value provided for "Expires" is invalid.
*
* @return static
*/
public static function forInvalidExpiresValue()
{
return new static(lang('Cookie.invalidExpiresValue'));
}
/**
* Thrown when the cookie name contains invalid characters per RFC 2616.
*
* @return static
*/
public static function forInvalidCookieName(string $name)
{
return new static(lang('Cookie.invalidCookieName', [$name]));
}
/**
* Thrown when the cookie name is empty.
*
* @return static
*/
public static function forEmptyCookieName()
{
return new static(lang('Cookie.emptyCookieName'));
}
/**
* Thrown when using the `__Secure-` prefix but the `Secure` attribute
* is not set to true.
*
* @return static
*/
public static function forInvalidSecurePrefix()
{
return new static(lang('Cookie.invalidSecurePrefix'));
}
/**
* Thrown when using the `__Host-` prefix but the `Secure` flag is not
* set, the `Domain` is set, and the `Path` is not `/`.
*
* @return static
*/
public static function forInvalidHostPrefix()
{
return new static(lang('Cookie.invalidHostPrefix'));
}
/**
* Thrown when the `SameSite` attribute given is not of the valid types.
*
* @return static
*/
public static function forInvalidSameSite(string $sameSite)
{
return new static(lang('Cookie.invalidSameSite', [$sameSite]));
}
/**
* Thrown when the `SameSite` attribute is set to `None` but the `Secure`
* attribute is not set.
*
* @return static
*/
public static function forInvalidSameSiteNone()
{
return new static(lang('Cookie.invalidSameSiteNone'));
}
/**
* Thrown when the `CookieStore` class is filled with invalid Cookie objects.
*
* @param list<int|string> $data
*
* @return static
*/
public static function forInvalidCookieInstance(array $data)
{
return new static(lang('Cookie.invalidCookieInstance', $data));
}
/**
* Thrown when the queried Cookie object does not exist in the cookie collection.
*
* @param list<string> $data
*
* @return static
*/
public static function forUnknownCookieInstance(array $data)
{
return new static(lang('Cookie.unknownCookieInstance', $data));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Events/Events.php | system/Events/Events.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Events;
use Config\Modules;
/**
* Events
*
* @see \CodeIgniter\Events\EventsTest
*/
class Events
{
public const PRIORITY_LOW = 200;
public const PRIORITY_NORMAL = 100;
public const PRIORITY_HIGH = 10;
/**
* The list of listeners.
*
* @var array<string, array{0: bool, 1: list<int>, 2: list<callable(mixed): mixed>}>
*/
protected static $listeners = [];
/**
* Flag to let us know if we've read from the Config file(s)
* and have all of the defined events.
*
* @var bool
*/
protected static $initialized = false;
/**
* If true, events will not actually be fired.
* Useful during testing.
*
* @var bool
*/
protected static $simulate = false;
/**
* Stores information about the events
* for display in the debug toolbar.
*
* @var list<array{start: float, end: float, event: string}>
*/
protected static $performanceLog = [];
/**
* A list of found files.
*
* @var list<string>
*/
protected static $files = [];
/**
* Ensures that we have a events file ready.
*
* @return void
*/
public static function initialize()
{
// Don't overwrite anything....
if (static::$initialized) {
return;
}
$config = new Modules();
$events = APPPATH . 'Config' . DIRECTORY_SEPARATOR . 'Events.php';
$files = [];
if ($config->shouldDiscover('events')) {
$files = service('locator')->search('Config/Events.php');
}
$files = array_filter(array_map(
static fn (string $file): false|string => realpath($file),
$files,
));
static::$files = array_values(array_unique(array_merge($files, [$events])));
foreach (static::$files as $file) {
include $file;
}
static::$initialized = true;
}
/**
* Registers an action to happen on an event. The action can be any sort
* of callable:
*
* Events::on('create', 'myFunction'); // procedural function
* Events::on('create', ['myClass', 'myMethod']); // Class::method
* Events::on('create', [$myInstance, 'myMethod']); // Method on an existing instance
* Events::on('create', function() {}); // Closure
*
* @param string $eventName
* @param callable(mixed): mixed $callback
* @param int $priority
*
* @return void
*/
public static function on($eventName, $callback, $priority = self::PRIORITY_NORMAL)
{
if (! isset(static::$listeners[$eventName])) {
static::$listeners[$eventName] = [
true, // If there's only 1 item, it's sorted.
[$priority],
[$callback],
];
} else {
static::$listeners[$eventName][0] = false; // Not sorted
static::$listeners[$eventName][1][] = $priority;
static::$listeners[$eventName][2][] = $callback;
}
}
/**
* Runs through all subscribed methods running them one at a time,
* until either:
* a) All subscribers have finished or
* b) a method returns false, at which point execution of subscribers stops.
*
* @param string $eventName
* @param mixed ...$arguments
*/
public static function trigger($eventName, ...$arguments): bool
{
// Read in our Config/Events file so that we have them all!
if (! static::$initialized) {
static::initialize();
}
$listeners = static::listeners($eventName);
foreach ($listeners as $listener) {
$start = microtime(true);
$result = static::$simulate === false ? $listener(...$arguments) : true;
if (CI_DEBUG) {
static::$performanceLog[] = [
'start' => $start,
'end' => microtime(true),
'event' => $eventName,
];
}
if ($result === false) {
return false;
}
}
return true;
}
/**
* Returns an array of listeners for a single event. They are
* sorted by priority.
*
* @param string $eventName
*
* @return list<callable(mixed): mixed>
*/
public static function listeners($eventName): array
{
if (! isset(static::$listeners[$eventName])) {
return [];
}
// The list is not sorted
if (! static::$listeners[$eventName][0]) {
// Sort it!
array_multisort(static::$listeners[$eventName][1], SORT_NUMERIC, static::$listeners[$eventName][2]);
// Mark it as sorted already!
static::$listeners[$eventName][0] = true;
}
return static::$listeners[$eventName][2];
}
/**
* Removes a single listener from an event.
*
* If the listener couldn't be found, returns FALSE, else TRUE if
* it was removed.
*
* @param string $eventName
* @param callable(mixed): mixed $listener
*/
public static function removeListener($eventName, callable $listener): bool
{
if (! isset(static::$listeners[$eventName])) {
return false;
}
foreach (static::$listeners[$eventName][2] as $index => $check) {
if ($check === $listener) {
unset(
static::$listeners[$eventName][1][$index],
static::$listeners[$eventName][2][$index],
);
return true;
}
}
return false;
}
/**
* Removes all listeners.
*
* If the event_name is specified, only listeners for that event will be
* removed, otherwise all listeners for all events are removed.
*
* @param string|null $eventName
*
* @return void
*/
public static function removeAllListeners($eventName = null)
{
if ($eventName !== null) {
unset(static::$listeners[$eventName]);
} else {
static::$listeners = [];
}
}
/**
* Sets the path to the file that routes are read from.
*
* @param list<string> $files
*
* @return void
*/
public static function setFiles(array $files)
{
static::$files = $files;
}
/**
* Returns the files that were found/loaded during this request.
*
* @return list<string>
*/
public static function getFiles()
{
return static::$files;
}
/**
* Turns simulation on or off. When on, events will not be triggered,
* simply logged. Useful during testing when you don't actually want
* the tests to run.
*
* @return void
*/
public static function simulate(bool $choice = true)
{
static::$simulate = $choice;
}
/**
* Getter for the performance log records.
*
* @return list<array{start: float, end: float, event: string}>
*/
public static function getPerformanceLogs()
{
return static::$performanceLog;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/API/ResponseTrait.php | system/API/ResponseTrait.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\API;
use CodeIgniter\Format\Format;
use CodeIgniter\Format\FormatterInterface;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Provides common, more readable, methods to provide
* consistent HTTP responses under a variety of common
* situations when working as an API.
*
* @property RequestInterface $request
* @property ResponseInterface $response
* @property bool $stringAsHtml Whether to treat string data as HTML in JSON response.
* Setting `true` is only for backward compatibility.
*/
trait ResponseTrait
{
/**
* Allows child classes to override the
* status code that is used in their API.
*
* @var array<string, int>
*/
protected $codes = [
'created' => 201,
'deleted' => 200,
'updated' => 200,
'no_content' => 204,
'invalid_request' => 400,
'unsupported_response_type' => 400,
'invalid_scope' => 400,
'temporarily_unavailable' => 400,
'invalid_grant' => 400,
'invalid_credentials' => 400,
'invalid_refresh' => 400,
'no_data' => 400,
'invalid_data' => 400,
'access_denied' => 401,
'unauthorized' => 401,
'invalid_client' => 401,
'forbidden' => 403,
'resource_not_found' => 404,
'not_acceptable' => 406,
'resource_exists' => 409,
'conflict' => 409,
'resource_gone' => 410,
'payload_too_large' => 413,
'unsupported_media_type' => 415,
'too_many_requests' => 429,
'server_error' => 500,
'unsupported_grant_type' => 501,
'not_implemented' => 501,
];
/**
* How to format the response data.
* Either 'json' or 'xml'. If null is set, it will be determined through
* content negotiation.
*
* @var 'html'|'json'|'xml'|null
*/
protected $format = 'json';
/**
* Current Formatter instance. This is usually set by ResponseTrait::format
*
* @var FormatterInterface|null
*/
protected $formatter;
/**
* Provides a single, simple method to return an API response, formatted
* to match the requested format, with proper content-type and status code.
*
* @param array<string, mixed>|string|null $data
*
* @return ResponseInterface
*/
protected function respond($data = null, ?int $status = null, string $message = '')
{
if ($data === null && $status === null) {
$status = 404;
$output = null;
$this->format($data);
} elseif ($data === null && is_numeric($status)) {
$output = null;
$this->format($data);
} else {
$status ??= 200;
$output = $this->format($data);
}
if ($output !== null) {
if ($this->format === 'json') {
return $this->response->setJSON($output)->setStatusCode($status, $message);
}
if ($this->format === 'xml') {
return $this->response->setXML($output)->setStatusCode($status, $message);
}
}
return $this->response->setBody($output)->setStatusCode($status, $message);
}
/**
* Used for generic failures that no custom methods exist for.
*
* @param list<string>|string $messages
* @param int $status HTTP status code
* @param string|null $code Custom, API-specific, error code
*
* @return ResponseInterface
*/
protected function fail($messages, int $status = 400, ?string $code = null, string $customMessage = '')
{
if (! is_array($messages)) {
$messages = ['error' => $messages];
}
$response = [
'status' => $status,
'error' => $code ?? $status,
'messages' => $messages,
];
return $this->respond($response, $status, $customMessage);
}
// --------------------------------------------------------------------
// Response Helpers
// --------------------------------------------------------------------
/**
* Used after successfully creating a new resource.
*
* @param array<string, mixed>|string|null $data
*
* @return ResponseInterface
*/
protected function respondCreated($data = null, string $message = '')
{
return $this->respond($data, $this->codes['created'], $message);
}
/**
* Used after a resource has been successfully deleted.
*
* @param array<string, mixed>|string|null $data
*
* @return ResponseInterface
*/
protected function respondDeleted($data = null, string $message = '')
{
return $this->respond($data, $this->codes['deleted'], $message);
}
/**
* Used after a resource has been successfully updated.
*
* @param array<string, mixed>|string|null $data
*
* @return ResponseInterface
*/
protected function respondUpdated($data = null, string $message = '')
{
return $this->respond($data, $this->codes['updated'], $message);
}
/**
* Used after a command has been successfully executed but there is no
* meaningful reply to send back to the client.
*
* @return ResponseInterface
*/
protected function respondNoContent(string $message = 'No Content')
{
return $this->respond(null, $this->codes['no_content'], $message);
}
/**
* Used when the client is either didn't send authorization information,
* or had bad authorization credentials. User is encouraged to try again
* with the proper information.
*
* @return ResponseInterface
*/
protected function failUnauthorized(string $description = 'Unauthorized', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['unauthorized'], $code, $message);
}
/**
* Used when access is always denied to this resource and no amount
* of trying again will help.
*
* @return ResponseInterface
*/
protected function failForbidden(string $description = 'Forbidden', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['forbidden'], $code, $message);
}
/**
* Used when a specified resource cannot be found.
*
* @return ResponseInterface
*/
protected function failNotFound(string $description = 'Not Found', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['resource_not_found'], $code, $message);
}
/**
* Used when the data provided by the client cannot be validated on one or more fields.
*
* @param list<string>|string $errors
*
* @return ResponseInterface
*/
protected function failValidationErrors($errors, ?string $code = null, string $message = '')
{
return $this->fail($errors, $this->codes['invalid_data'], $code, $message);
}
/**
* Use when trying to create a new resource and it already exists.
*
* @return ResponseInterface
*/
protected function failResourceExists(string $description = 'Conflict', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['resource_exists'], $code, $message);
}
/**
* Use when a resource was previously deleted. This is different than
* Not Found, because here we know the data previously existed, but is now gone,
* where Not Found means we simply cannot find any information about it.
*
* @return ResponseInterface
*/
protected function failResourceGone(string $description = 'Gone', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['resource_gone'], $code, $message);
}
/**
* Used when the user has made too many requests for the resource recently.
*
* @return ResponseInterface
*/
protected function failTooManyRequests(string $description = 'Too Many Requests', ?string $code = null, string $message = '')
{
return $this->fail($description, $this->codes['too_many_requests'], $code, $message);
}
/**
* Used when there is a server error.
*
* @param string $description The error message to show the user.
* @param string|null $code A custom, API-specific, error code.
* @param string $message A custom "reason" message to return.
*/
protected function failServerError(string $description = 'Internal Server Error', ?string $code = null, string $message = ''): ResponseInterface
{
return $this->fail($description, $this->codes['server_error'], $code, $message);
}
// --------------------------------------------------------------------
// Utility Methods
// --------------------------------------------------------------------
/**
* Handles formatting a response. Currently, makes some heavy assumptions
* and needs updating! :)
*
* @param array<string, mixed>|string|null $data
*
* @return string|null
*/
protected function format($data = null)
{
/** @var Format $format */
$format = service('format');
$mime = $this->format === null
? $format->getConfig()->supportedResponseFormats[0]
: "application/{$this->format}";
// Determine correct response type through content negotiation if not explicitly declared
if (
! in_array($this->format, ['json', 'xml'], true)
&& $this->request instanceof IncomingRequest
) {
$mime = $this->request->negotiate(
'media',
$format->getConfig()->supportedResponseFormats,
false,
);
}
$this->response->setContentType($mime);
// if we don't have a formatter, make one
$this->formatter ??= $format->getFormatter($mime);
$asHtml = $this->stringAsHtml ?? false;
if (
($mime === 'application/json' && $asHtml && is_string($data))
|| ($mime !== 'application/json' && is_string($data))
) {
// The content type should be text/... and not application/...
$contentType = $this->response->getHeaderLine('Content-Type');
$contentType = str_replace('application/json', 'text/html', $contentType);
$contentType = str_replace('application/', 'text/', $contentType);
$this->response->setContentType($contentType);
$this->format = 'html';
return $data;
}
if ($mime !== 'application/json') {
// Recursively convert objects into associative arrays
// Conversion not required for JSONFormatter
/** @var array<string, mixed>|string|null $data */
$data = json_decode(json_encode($data), true);
}
return $this->formatter->format($data);
}
/**
* Sets the format the response should be in.
*
* @param 'json'|'xml' $format Response format
*
* @return $this
*/
protected function setResponseFormat(?string $format = null)
{
$this->format = $format === null ? null : strtolower($format);
return $this;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Security/Security.php | system/Security/Security.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Security;
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\Exceptions\InvalidArgumentException;
use CodeIgniter\Exceptions\LogicException;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\Method;
use CodeIgniter\HTTP\Request;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\I18n\Time;
use CodeIgniter\Security\Exceptions\SecurityException;
use CodeIgniter\Session\Session;
use Config\Cookie as CookieConfig;
use Config\Security as SecurityConfig;
use ErrorException;
/**
* Class Security
*
* Provides methods that help protect your site against
* Cross-Site Request Forgery attacks.
*
* @see \CodeIgniter\Security\SecurityTest
*/
class Security implements SecurityInterface
{
public const CSRF_PROTECTION_COOKIE = 'cookie';
public const CSRF_PROTECTION_SESSION = 'session';
protected const CSRF_HASH_BYTES = 16;
/**
* CSRF Protection Method
*
* Protection Method for Cross Site Request Forgery protection.
*
* @var string 'cookie' or 'session'
*
* @deprecated 4.4.0 Use $this->config->csrfProtection.
*/
protected $csrfProtection = self::CSRF_PROTECTION_COOKIE;
/**
* CSRF Token Randomization
*
* @var bool
*
* @deprecated 4.4.0 Use $this->config->tokenRandomize.
*/
protected $tokenRandomize = false;
/**
* CSRF Hash (without randomization)
*
* Random hash for Cross Site Request Forgery protection.
*
* @var string|null
*/
protected $hash;
/**
* CSRF Token Name
*
* Token name for Cross Site Request Forgery protection.
*
* @var string
*
* @deprecated 4.4.0 Use $this->config->tokenName.
*/
protected $tokenName = 'csrf_token_name';
/**
* CSRF Header Name
*
* Header name for Cross Site Request Forgery protection.
*
* @var string
*
* @deprecated 4.4.0 Use $this->config->headerName.
*/
protected $headerName = 'X-CSRF-TOKEN';
/**
* The CSRF Cookie instance.
*
* @var Cookie
*/
protected $cookie;
/**
* CSRF Cookie Name (with Prefix)
*
* Cookie name for Cross Site Request Forgery protection.
*
* @var string
*/
protected $cookieName = 'csrf_cookie_name';
/**
* CSRF Expires
*
* Expiration time for Cross Site Request Forgery protection cookie.
*
* Defaults to two hours (in seconds).
*
* @var int
*
* @deprecated 4.4.0 Use $this->config->expires.
*/
protected $expires = 7200;
/**
* CSRF Regenerate
*
* Regenerate CSRF Token on every request.
*
* @var bool
*
* @deprecated 4.4.0 Use $this->config->regenerate.
*/
protected $regenerate = true;
/**
* CSRF Redirect
*
* Redirect to previous page with error on failure.
*
* @var bool
*
* @deprecated 4.4.0 Use $this->config->redirect.
*/
protected $redirect = false;
/**
* CSRF SameSite
*
* Setting for CSRF SameSite cookie token.
*
* Allowed values are: None - Lax - Strict - ''.
*
* Defaults to `Lax` as recommended in this link:
*
* @see https://portswigger.net/web-security/csrf/samesite-cookies
*
* @var string
*
* @deprecated `Config\Cookie` $samesite property is used.
*/
protected $samesite = Cookie::SAMESITE_LAX;
private readonly IncomingRequest $request;
/**
* CSRF Cookie Name without Prefix
*/
private ?string $rawCookieName = null;
/**
* Session instance.
*/
private ?Session $session = null;
/**
* CSRF Hash in Request Cookie
*
* The cookie value is always CSRF hash (without randomization) even if
* $tokenRandomize is true.
*/
private ?string $hashInCookie = null;
/**
* Security Config
*/
protected SecurityConfig $config;
/**
* Constructor.
*
* Stores our configuration and fires off the init() method to setup
* initial state.
*/
public function __construct(SecurityConfig $config)
{
$this->config = $config;
$this->rawCookieName = $config->cookieName;
if ($this->isCSRFCookie()) {
$cookie = config(CookieConfig::class);
$this->configureCookie($cookie);
} else {
// Session based CSRF protection
$this->configureSession();
}
$this->request = service('request');
$this->hashInCookie = $this->request->getCookie($this->cookieName);
$this->restoreHash();
if ($this->hash === null) {
$this->generateHash();
}
}
private function isCSRFCookie(): bool
{
return $this->config->csrfProtection === self::CSRF_PROTECTION_COOKIE;
}
private function configureSession(): void
{
$this->session = service('session');
}
private function configureCookie(CookieConfig $cookie): void
{
$cookiePrefix = $cookie->prefix;
$this->cookieName = $cookiePrefix . $this->rawCookieName;
Cookie::setDefaults($cookie);
}
/**
* CSRF verification.
*
* @return $this
*
* @throws SecurityException
*/
public function verify(RequestInterface $request)
{
// Protects POST, PUT, DELETE, PATCH
$method = $request->getMethod();
$methodsToProtect = [Method::POST, Method::PUT, Method::DELETE, Method::PATCH];
if (! in_array($method, $methodsToProtect, true)) {
return $this;
}
$postedToken = $this->getPostedToken($request);
try {
$token = ($postedToken !== null && $this->config->tokenRandomize)
? $this->derandomize($postedToken) : $postedToken;
} catch (InvalidArgumentException) {
$token = null;
}
// Do the tokens match?
if (! isset($token, $this->hash) || ! hash_equals($this->hash, $token)) {
throw SecurityException::forDisallowedAction();
}
$this->removeTokenInRequest($request);
if ($this->config->regenerate) {
$this->generateHash();
}
log_message('info', 'CSRF token verified.');
return $this;
}
/**
* Remove token in POST or JSON request data
*/
private function removeTokenInRequest(RequestInterface $request): void
{
assert($request instanceof Request);
if (isset($_POST[$this->config->tokenName])) {
// We kill this since we're done and we don't want to pollute the POST array.
unset($_POST[$this->config->tokenName]);
$request->setGlobal('post', $_POST);
} else {
$body = $request->getBody() ?? '';
$json = json_decode($body);
if ($json !== null && json_last_error() === JSON_ERROR_NONE) {
// We kill this since we're done and we don't want to pollute the JSON data.
unset($json->{$this->config->tokenName});
$request->setBody(json_encode($json));
} else {
parse_str($body, $parsed);
// We kill this since we're done and we don't want to pollute the BODY data.
unset($parsed[$this->config->tokenName]);
$request->setBody(http_build_query($parsed));
}
}
}
private function getPostedToken(RequestInterface $request): ?string
{
assert($request instanceof IncomingRequest);
// Does the token exist in POST, HEADER or optionally php:://input - json data or PUT, DELETE, PATCH - raw data.
if ($tokenValue = $request->getPost($this->config->tokenName)) {
return is_string($tokenValue) ? $tokenValue : null;
}
if ($request->hasHeader($this->config->headerName)) {
$tokenValue = $request->header($this->config->headerName)->getValue();
return (is_string($tokenValue) && $tokenValue !== '') ? $tokenValue : null;
}
$body = (string) $request->getBody();
if ($body !== '') {
$json = json_decode($body);
if ($json !== null && json_last_error() === JSON_ERROR_NONE) {
$tokenValue = $json->{$this->config->tokenName} ?? null;
return is_string($tokenValue) ? $tokenValue : null;
}
parse_str($body, $parsed);
$tokenValue = $parsed[$this->config->tokenName] ?? null;
return is_string($tokenValue) ? $tokenValue : null;
}
return null;
}
/**
* Returns the CSRF Token.
*/
public function getHash(): ?string
{
return $this->config->tokenRandomize ? $this->randomize($this->hash) : $this->hash;
}
/**
* Randomize hash to avoid BREACH attacks.
*
* @params string $hash CSRF hash
*
* @return string CSRF token
*/
protected function randomize(string $hash): string
{
$keyBinary = random_bytes(static::CSRF_HASH_BYTES);
$hashBinary = hex2bin($hash);
if ($hashBinary === false) {
throw new LogicException('$hash is invalid: ' . $hash);
}
return bin2hex(($hashBinary ^ $keyBinary) . $keyBinary);
}
/**
* Derandomize the token.
*
* @params string $token CSRF token
*
* @return string CSRF hash
*
* @throws InvalidArgumentException "hex2bin(): Hexadecimal input string must have an even length"
*/
protected function derandomize(string $token): string
{
$key = substr($token, -static::CSRF_HASH_BYTES * 2);
$value = substr($token, 0, static::CSRF_HASH_BYTES * 2);
try {
return bin2hex(hex2bin($value) ^ hex2bin($key));
} catch (ErrorException $e) {
// "hex2bin(): Hexadecimal input string must have an even length"
throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);
}
}
/**
* Returns the CSRF Token Name.
*/
public function getTokenName(): string
{
return $this->config->tokenName;
}
/**
* Returns the CSRF Header Name.
*/
public function getHeaderName(): string
{
return $this->config->headerName;
}
/**
* Returns the CSRF Cookie Name.
*/
public function getCookieName(): string
{
return $this->config->cookieName;
}
/**
* Check if request should be redirect on failure.
*/
public function shouldRedirect(): bool
{
return $this->config->redirect;
}
/**
* Sanitize Filename
*
* Tries to sanitize filenames in order to prevent directory traversal attempts
* and other security threats, which is particularly useful for files that
* were supplied via user input.
*
* If it is acceptable for the user input to include relative paths,
* e.g. file/in/some/approved/folder.txt, you can set the second optional
* parameter, $relativePath to TRUE.
*
* @deprecated 4.6.2 Use `sanitize_filename()` instead
*
* @param string $str Input file name
* @param bool $relativePath Whether to preserve paths
*/
public function sanitizeFilename(string $str, bool $relativePath = false): string
{
helper('security');
return sanitize_filename($str, $relativePath);
}
/**
* Restore hash from Session or Cookie
*/
private function restoreHash(): void
{
if ($this->isCSRFCookie()) {
if ($this->isHashInCookie()) {
$this->hash = $this->hashInCookie;
}
} elseif ($this->session->has($this->config->tokenName)) {
// Session based CSRF protection
$this->hash = $this->session->get($this->config->tokenName);
}
}
/**
* Generates (Regenerates) the CSRF Hash.
*/
public function generateHash(): string
{
$this->hash = bin2hex(random_bytes(static::CSRF_HASH_BYTES));
if ($this->isCSRFCookie()) {
$this->saveHashInCookie();
} else {
// Session based CSRF protection
$this->saveHashInSession();
}
return $this->hash;
}
private function isHashInCookie(): bool
{
if ($this->hashInCookie === null) {
return false;
}
$length = static::CSRF_HASH_BYTES * 2;
$pattern = '#^[0-9a-f]{' . $length . '}$#iS';
return preg_match($pattern, $this->hashInCookie) === 1;
}
private function saveHashInCookie(): void
{
$this->cookie = new Cookie(
$this->rawCookieName,
$this->hash,
[
'expires' => $this->config->expires === 0 ? 0 : Time::now()->getTimestamp() + $this->config->expires,
],
);
$response = service('response');
$response->setCookie($this->cookie);
}
private function saveHashInSession(): void
{
$this->session->set($this->config->tokenName, $this->hash);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Security/CheckPhpIni.php | system/Security/CheckPhpIni.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Security;
use CodeIgniter\CLI\CLI;
use CodeIgniter\View\Table;
/**
* Checks php.ini settings
*
* @used-by \CodeIgniter\Commands\Utilities\PhpIniCheck
* @see \CodeIgniter\Security\CheckPhpIniTest
*/
class CheckPhpIni
{
/**
* @param bool $isCli Set false if you run via Web
*
* @return string|null HTML string or void in CLI
*/
public static function run(bool $isCli = true, ?string $argument = null)
{
$output = static::checkIni($argument);
$thead = ['Directive', 'Global', 'Current', 'Recommended', 'Remark'];
$tbody = [];
// CLI
if ($isCli) {
self::outputForCli($output, $thead, $tbody);
return null;
}
// Web
return self::outputForWeb($output, $thead, $tbody);
}
private static function outputForCli(array $output, array $thead, array $tbody): void
{
foreach ($output as $directive => $values) {
$current = $values['current'] ?? '';
$notRecommended = false;
if ($values['recommended'] !== '') {
if ($values['recommended'] !== $current) {
$notRecommended = true;
}
$current = $notRecommended
? CLI::color($current === '' ? 'n/a' : $current, 'red')
: $current;
}
$directive = $notRecommended ? CLI::color($directive, 'red') : $directive;
$tbody[] = [
$directive, $values['global'], $current, $values['recommended'], $values['remark'],
];
}
CLI::table($tbody, $thead);
}
private static function outputForWeb(array $output, array $thead, array $tbody): string
{
foreach ($output as $directive => $values) {
$current = $values['current'];
$notRecommended = false;
if ($values['recommended'] !== '') {
if ($values['recommended'] !== $values['current']) {
$notRecommended = true;
}
if ($values['current'] === '') {
$current = 'n/a';
}
$current = $notRecommended
? '<span style="color: red">' . $current . '</span>'
: $current;
}
$directive = $notRecommended
? '<span style="color: red">' . $directive . '</span>'
: $directive;
$tbody[] = [
$directive, $values['global'], $current, $values['recommended'], $values['remark'],
];
}
$table = new Table();
$template = [
'table_open' => '<table border="1" cellpadding="4" cellspacing="0">',
];
$table->setTemplate($template);
$table->setHeading($thead);
return '<pre>' . $table->generate($tbody) . '</pre>';
}
/**
* @internal Used for testing purposes only.
* @testTag
*/
public static function checkIni(?string $argument = null): array
{
// Default items
$items = [
'error_reporting' => ['recommended' => '5111'],
'display_errors' => ['recommended' => '0'],
'display_startup_errors' => ['recommended' => '0'],
'log_errors' => [],
'error_log' => [],
'default_charset' => ['recommended' => 'UTF-8'],
'max_execution_time' => ['remark' => 'The default is 30.'],
'memory_limit' => ['remark' => '> post_max_size'],
'post_max_size' => ['remark' => '> upload_max_filesize'],
'upload_max_filesize' => ['remark' => '< post_max_size'],
'max_input_vars' => ['remark' => 'The default is 1000.'],
'request_order' => ['recommended' => 'GP'],
'variables_order' => ['recommended' => 'GPCS'],
'date.timezone' => ['recommended' => 'UTC'],
'mbstring.language' => ['recommended' => 'neutral'],
'opcache.enable' => ['recommended' => '1'],
'opcache.enable_cli' => ['recommended' => '0', 'remark' => 'Enable when you are using queues or running repetitive CLI tasks'],
'opcache.jit' => ['recommended' => 'tracing'],
'opcache.jit_buffer_size' => ['recommended' => '128', 'remark' => 'Adjust with your free space of memory'],
'zend.assertions' => ['recommended' => '-1'],
];
if ($argument === 'opcache') {
$items = [
'opcache.enable' => ['recommended' => '1'],
'opcache.enable_cli' => ['recommended' => '0', 'remark' => 'Enable when you are using queues or running repetitive CLI tasks'],
'opcache.jit' => ['recommended' => 'tracing', 'remark' => 'Disable when you used third-party extensions'],
'opcache.jit_buffer_size' => ['recommended' => '128', 'remark' => 'Adjust with your free space of memory'],
'opcache.memory_consumption' => ['recommended' => '128', 'remark' => 'Adjust with your free space of memory'],
'opcache.interned_strings_buffer' => ['recommended' => '16'],
'opcache.max_accelerated_files' => ['remark' => 'Adjust based on the number of PHP files in your project (e.g.: find your_project/ -iname \'*.php\'|wc -l)'],
'opcache.max_wasted_percentage' => ['recommended' => '10'],
'opcache.validate_timestamps' => ['recommended' => '0', 'remark' => 'When you disabled, opcache hold your code into shared memory. Restart webserver needed'],
'opcache.revalidate_freq' => [],
'opcache.file_cache' => ['remark' => 'Location file caching, It should improve performance when SHM memory is full'],
'opcache.file_cache_only' => ['remark' => 'Opcode caching in shared memory, Disabled when you using Windows'],
'opcache.file_cache_fallback' => ['remark' => 'Set enable when you using Windows'],
'opcache.save_comments' => ['recommended' => '0', 'remark' => 'Enable when you using package require docblock annotation'],
];
}
$output = [];
$ini = ini_get_all();
foreach ($items as $key => $values) {
$hasKeyInIni = array_key_exists($key, $ini);
$output[$key] = [
'global' => $hasKeyInIni ? $ini[$key]['global_value'] : 'disabled',
'current' => $hasKeyInIni ? $ini[$key]['local_value'] : 'disabled',
'recommended' => $values['recommended'] ?? '',
'remark' => $values['remark'] ?? '',
];
}
// [directive => [current_value, recommended_value]]
return $output;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Security/SecurityInterface.php | system/Security/SecurityInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Security;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\Security\Exceptions\SecurityException;
/**
* Expected behavior of a Security.
*/
interface SecurityInterface
{
/**
* CSRF Verify
*
* @return $this|false
*
* @throws SecurityException
*/
public function verify(RequestInterface $request);
/**
* Returns the CSRF Hash.
*/
public function getHash(): ?string;
/**
* Returns the CSRF Token Name.
*/
public function getTokenName(): string;
/**
* Returns the CSRF Header Name.
*/
public function getHeaderName(): string;
/**
* Returns the CSRF Cookie Name.
*/
public function getCookieName(): string;
/**
* Check if request should be redirect on failure.
*/
public function shouldRedirect(): bool;
/**
* Sanitize Filename
*
* Tries to sanitize filenames in order to prevent directory traversal attempts
* and other security threats, which is particularly useful for files that
* were supplied via user input.
*
* If it is acceptable for the user input to include relative paths,
* e.g. file/in/some/approved/folder.txt, you can set the second optional
* parameter, $relativePath to TRUE.
*
* @deprecated 4.6.2 Use `sanitize_filename()` instead
*
* @param string $str Input file name
* @param bool $relativePath Whether to preserve paths
*/
public function sanitizeFilename(string $str, bool $relativePath = false): string;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Security/Exceptions/SecurityException.php | system/Security/Exceptions/SecurityException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Security\Exceptions;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\Exceptions\HTTPExceptionInterface;
class SecurityException extends FrameworkException implements HTTPExceptionInterface
{
/**
* Throws when some specific action is not allowed.
* This is used for CSRF protection.
*
* @return static
*/
public static function forDisallowedAction()
{
return new static(lang('Security.disallowedAction'), 403);
}
/**
* Throws if a secure cookie is dispatched when the current connection is not
* secure.
*/
public static function forInsecureCookie(): static
{
return new static(lang('Security.insecureCookie'));
}
/**
* Throws when the source string contains invalid UTF-8 characters.
*
* @param string $source The source string
* @param string $string The invalid string
*
* @return static
*/
public static function forInvalidUTF8Chars(string $source, string $string)
{
return new static(
'Invalid UTF-8 characters in ' . $source . ': ' . $string,
400,
);
}
/**
* Throws when the source string contains invalid control characters.
*
* @param string $source The source string
* @param string $string The invalid string
*
* @return static
*/
public static function forInvalidControlChars(string $source, string $string)
{
return new static(
'Invalid Control characters in ' . $source . ': ' . $string,
400,
);
}
/**
* @deprecated Use `CookieException::forInvalidSameSite()` instead.
*
* @codeCoverageIgnore
*
* @return static
*/
public static function forInvalidSameSite(string $samesite)
{
return new static(lang('Security.invalidSameSite', [$samesite]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Session/SessionInterface.php | system/Session/SessionInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session;
/**
* Expected behavior of a session container used with CodeIgniter.
*/
interface SessionInterface
{
/**
* Regenerates the session ID.
*
* @param bool $destroy Should old session data be destroyed?
*
* @return void
*/
public function regenerate(bool $destroy = false);
/**
* Destroys the current session.
*
* @return void
*/
public function destroy();
/**
* Sets user data into the session.
*
* If $data is a string, then it is interpreted as a session property
* key, and $value is expected to be non-null.
*
* If $data is an array, it is expected to be an array of key/value pairs
* to be set as session properties.
*
* @param array<string, mixed>|list<string>|string $data Property name or associative array of properties
* @param mixed $value Property value if single key provided
*
* @return void
*/
public function set($data, $value = null);
/**
* Get user data that has been set in the session.
*
* If the property exists as "normal", returns it.
* Otherwise, returns an array of any temp or flash data values with the
* property key.
*
* Replaces the legacy method $session->userdata();
*
* @param string|null $key Identifier of the session property to retrieve
*
* @return ($key is string ? mixed : array<string, mixed>)
*/
public function get(?string $key = null);
/**
* Returns whether an index exists in the session array.
*
* @param string $key Identifier of the session property we are interested in.
*/
public function has(string $key): bool;
/**
* Remove one or more session properties.
*
* If $key is an array, it is interpreted as an array of string property
* identifiers to remove. Otherwise, it is interpreted as the identifier
* of a specific session property to remove.
*
* @param list<string>|string $key Identifier of the session property or properties to remove.
*
* @return void
*/
public function remove($key);
/**
* Sets data into the session that will only last for a single request.
* Perfect for use with single-use status update messages.
*
* If $data is an array, it is interpreted as an associative array of
* key/value pairs for flashdata properties.
* Otherwise, it is interpreted as the identifier of a specific
* flashdata property, with $value containing the property value.
*
* @param array<string, mixed>|string $data Property identifier or associative array of properties
* @param mixed $value Property value if $data is a scalar
*
* @return void
*/
public function setFlashdata($data, $value = null);
/**
* Retrieve one or more items of flash data from the session.
*
* If the item key is null, return all flashdata.
*
* @param string|null $key Property identifier
*
* @return ($key is string ? mixed : array<string, mixed>)
*/
public function getFlashdata(?string $key = null);
/**
* Keeps a single piece of flash data alive for one more request.
*
* @param list<string>|string $key Property identifier or array of them
*
* @return void
*/
public function keepFlashdata($key);
/**
* Mark a session property or properties as flashdata. This returns
* `false` if any of the properties were not already set.
*
* @param list<string>|string $key Property identifier or array of them
*
* @return bool
*/
public function markAsFlashdata($key);
/**
* Unmark data in the session as flashdata.
*
* @param list<string>|string $key Property identifier or array of them
*
* @return void
*/
public function unmarkFlashdata($key);
/**
* Retrieve all of the keys for session data marked as flashdata.
*
* @return list<string>
*/
public function getFlashKeys(): array;
/**
* Sets new data into the session, and marks it as temporary data
* with a set lifespan.
*
* @param array<string, mixed>|list<string>|string $data Session data key or associative array of items
* @param mixed $value Value to store
* @param int $ttl Time-to-live in seconds
*
* @return void
*/
public function setTempdata($data, $value = null, int $ttl = 300);
/**
* Returns either a single piece of tempdata, or all temp data currently
* in the session.
*
* @param string|null $key Session data key
*
* @return ($key is string ? mixed : array<string, mixed>)
*/
public function getTempdata(?string $key = null);
/**
* Removes a single piece of temporary data from the session.
*
* @param string $key Session data key
*
* @return void
*/
public function removeTempdata(string $key);
/**
* Mark one of more pieces of data as being temporary, meaning that
* it has a set lifespan within the session.
*
* Returns `false` if any of the properties were not set.
*
* @param array<string, mixed>|list<string>|string $key Property identifier or array of them
* @param int $ttl Time to live, in seconds
*
* @return bool
*/
public function markAsTempdata($key, int $ttl = 300);
/**
* Unmarks temporary data in the session, effectively removing its
* lifespan and allowing it to live as long as the session does.
*
* @param list<string>|string $key Property identifier or array of them
*
* @return void
*/
public function unmarkTempdata($key);
/**
* Retrieve the keys of all session data that have been marked as temporary data.
*
* @return list<string>
*/
public function getTempKeys(): array;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Session/Session.php | system/Session/Session.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session;
use CodeIgniter\Cookie\Cookie;
use CodeIgniter\I18n\Time;
use Config\Cookie as CookieConfig;
use Config\Session as SessionConfig;
use Psr\Log\LoggerAwareTrait;
use SessionHandlerInterface;
/**
* Implementation of CodeIgniter session container.
*
* Session configuration is done through session variables and cookie related
* variables in app/config/App.php
*
* @property string $session_id
* @see \CodeIgniter\Session\SessionTest
*/
class Session implements SessionInterface
{
use LoggerAwareTrait;
/**
* Instance of the driver to use.
*
* @var SessionHandlerInterface
*/
protected $driver;
/**
* The storage driver to use: files, database, redis, memcached
*
* @var string
*
* @deprecated Use $this->config->driver.
*/
protected $sessionDriverName;
/**
* The session cookie name, must contain only [0-9a-z_-] characters.
*
* @var string
*
* @deprecated Use $this->config->cookieName.
*/
protected $sessionCookieName = 'ci_session';
/**
* The number of SECONDS you want the session to last.
* Setting it to 0 (zero) means expire when the browser is closed.
*
* @var int
*
* @deprecated Use $this->config->expiration.
*/
protected $sessionExpiration = 7200;
/**
* The location to save sessions to, driver dependent.
*
* For the 'files' driver, it's a path to a writable directory.
* WARNING: Only absolute paths are supported!
*
* For the 'database' driver, it's a table name.
*
* @todo address memcache & redis needs
*
* IMPORTANT: You are REQUIRED to set a valid save path!
*
* @var string
*
* @deprecated Use $this->config->savePath.
*/
protected $sessionSavePath;
/**
* Whether to match the user's IP address when reading the session data.
*
* WARNING: If you're using the database driver, don't forget to update
* your session table's PRIMARY KEY when changing this setting.
*
* @var bool
*
* @deprecated Use $this->config->matchIP.
*/
protected $sessionMatchIP = false;
/**
* How many seconds between CI regenerating the session ID.
*
* @var int
*
* @deprecated Use $this->config->timeToUpdate.
*/
protected $sessionTimeToUpdate = 300;
/**
* Whether to destroy session data associated with the old session ID
* when auto-regenerating the session ID. When set to FALSE, the data
* will be later deleted by the garbage collector.
*
* @var bool
*
* @deprecated Use $this->config->regenerateDestroy.
*/
protected $sessionRegenerateDestroy = false;
/**
* The session cookie instance.
*
* @var Cookie
*/
protected $cookie;
/**
* The domain name to use for cookies.
* Set to .your-domain.com for site-wide cookies.
*
* @var string
*
* @deprecated No longer used.
*/
protected $cookieDomain = '';
/**
* Path used for storing cookies.
* Typically will be a forward slash.
*
* @var string
*
* @deprecated No longer used.
*/
protected $cookiePath = '/';
/**
* Cookie will only be set if a secure HTTPS connection exists.
*
* @var bool
*
* @deprecated No longer used.
*/
protected $cookieSecure = false;
/**
* Cookie SameSite setting as described in RFC6265
* Must be 'None', 'Lax' or 'Strict'.
*
* @var string
*
* @deprecated No longer used.
*/
protected $cookieSameSite = Cookie::SAMESITE_LAX;
/**
* sid regex expression
*
* @var string
*/
protected $sidRegexp;
/**
* Session Config
*/
protected SessionConfig $config;
/**
* Constructor.
*
* Extract configuration settings and save them here.
*/
public function __construct(SessionHandlerInterface $driver, SessionConfig $config)
{
$this->driver = $driver;
$this->config = $config;
$cookie = config(CookieConfig::class);
$this->cookie = (new Cookie($this->config->cookieName, '', [
'expires' => $this->config->expiration === 0 ? 0 : Time::now()->getTimestamp() + $this->config->expiration,
'path' => $cookie->path,
'domain' => $cookie->domain,
'secure' => $cookie->secure,
'httponly' => true, // for security
'samesite' => $cookie->samesite ?? Cookie::SAMESITE_LAX,
'raw' => $cookie->raw ?? false,
]))->withPrefix(''); // Cookie prefix should be ignored.
helper('array');
}
/**
* Initialize the session container and starts up the session.
*
* @return $this|null
*/
public function start()
{
if (is_cli() && ENVIRONMENT !== 'testing') {
// @codeCoverageIgnoreStart
$this->logger->debug('Session: Initialization under CLI aborted.');
return null;
// @codeCoverageIgnoreEnd
}
if ((bool) ini_get('session.auto_start')) {
$this->logger->error('Session: session.auto_start is enabled in php.ini. Aborting.');
return null;
}
if (session_status() === PHP_SESSION_ACTIVE) {
$this->logger->warning('Session: Sessions is enabled, and one exists. Please don\'t $session->start();');
return null;
}
$this->configure();
$this->setSaveHandler();
// Sanitize the cookie, because apparently PHP doesn't do that for userspace handlers
if (
isset($_COOKIE[$this->config->cookieName])
&& (! is_string($_COOKIE[$this->config->cookieName]) || preg_match('#\A' . $this->sidRegexp . '\z#', $_COOKIE[$this->config->cookieName]) !== 1)
) {
unset($_COOKIE[$this->config->cookieName]);
}
$this->startSession();
// Is session ID auto-regeneration configured? (ignoring ajax requests)
if ((! isset($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !== 'xmlhttprequest')
&& ($regenerateTime = $this->config->timeToUpdate) > 0
) {
if (! isset($_SESSION['__ci_last_regenerate'])) {
$_SESSION['__ci_last_regenerate'] = Time::now()->getTimestamp();
} elseif ($_SESSION['__ci_last_regenerate'] < (Time::now()->getTimestamp() - $regenerateTime)) {
$this->regenerate($this->config->regenerateDestroy);
}
}
// Another work-around ... PHP doesn't seem to send the session cookie
// unless it is being currently created or regenerated
elseif (isset($_COOKIE[$this->config->cookieName]) && $_COOKIE[$this->config->cookieName] === session_id()) {
$this->setCookie();
}
$this->initVars();
$this->logger->debug("Session: Class initialized using '" . $this->config->driver . "' driver.");
return $this;
}
/**
* Destroys the current session.
*
* @deprecated Use destroy() instead.
*
* @return void
*/
public function stop()
{
$this->destroy();
}
/**
* Configuration.
*
* Handle input binds and configuration defaults.
*
* @return void
*/
protected function configure()
{
ini_set('session.name', $this->config->cookieName);
$sameSite = $this->cookie->getSameSite() ?: ucfirst(Cookie::SAMESITE_LAX);
$params = [
'lifetime' => $this->config->expiration,
'path' => $this->cookie->getPath(),
'domain' => $this->cookie->getDomain(),
'secure' => $this->cookie->isSecure(),
'httponly' => true, // HTTP only; Yes, this is intentional and not configurable for security reasons.
'samesite' => $sameSite,
];
ini_set('session.cookie_samesite', $sameSite);
session_set_cookie_params($params);
if ($this->config->expiration > 0) {
ini_set('session.gc_maxlifetime', (string) $this->config->expiration);
}
if ($this->config->savePath !== '') {
ini_set('session.save_path', $this->config->savePath);
}
// Security is king
ini_set('session.use_trans_sid', '0');
ini_set('session.use_strict_mode', '1');
ini_set('session.use_cookies', '1');
ini_set('session.use_only_cookies', '1');
$this->configureSidLength();
}
/**
* Configure session ID length
*
* To make life easier, we force the PHP defaults. Because PHP9 forces them.
* See https://wiki.php.net/rfc/deprecations_php_8_4#sessionsid_length_and_sessionsid_bits_per_character
*
* @return void
*/
protected function configureSidLength()
{
$bitsPerCharacter = (int) ini_get('session.sid_bits_per_character');
$sidLength = (int) ini_get('session.sid_length');
// We force the PHP defaults.
if (PHP_VERSION_ID < 90000) {
if ($bitsPerCharacter !== 4) {
ini_set('session.sid_bits_per_character', '4');
}
if ($sidLength !== 32) {
ini_set('session.sid_length', '32');
}
}
$this->sidRegexp = '[0-9a-f]{32}';
}
/**
* Handle temporary variables
*
* Clears old "flash" data, marks the new one for deletion and handles
* "temp" data deletion.
*
* @return void
*/
protected function initVars()
{
if (! isset($_SESSION['__ci_vars'])) {
return;
}
$currentTime = Time::now()->getTimestamp();
foreach ($_SESSION['__ci_vars'] as $key => &$value) {
if ($value === 'new') {
$_SESSION['__ci_vars'][$key] = 'old';
}
// DO NOT move this above the 'new' check!
elseif ($value === 'old' || $value < $currentTime) {
unset($_SESSION[$key], $_SESSION['__ci_vars'][$key]);
}
}
if ($_SESSION['__ci_vars'] === []) {
unset($_SESSION['__ci_vars']);
}
}
/**
* Regenerates the session ID.
*
* @param bool $destroy Should old session data be destroyed?
*
* @return void
*/
public function regenerate(bool $destroy = false)
{
$_SESSION['__ci_last_regenerate'] = Time::now()->getTimestamp();
session_regenerate_id($destroy);
$this->removeOldSessionCookie();
}
private function removeOldSessionCookie(): void
{
$response = service('response');
$cookieStoreInResponse = $response->getCookieStore();
if (! $cookieStoreInResponse->has($this->config->cookieName)) {
return;
}
// CookieStore is immutable.
$newCookieStore = $cookieStoreInResponse->remove($this->config->cookieName);
// But clear() method clears cookies in the object (not immutable).
$cookieStoreInResponse->clear();
foreach ($newCookieStore as $cookie) {
$response->setCookie($cookie);
}
}
/**
* Destroys the current session.
*
* @return void
*/
public function destroy()
{
if (ENVIRONMENT === 'testing') {
return;
}
session_destroy();
}
/**
* Writes session data and close the current session.
*
* @return void
*/
public function close()
{
if (ENVIRONMENT === 'testing') {
return;
}
session_write_close();
}
/**
* Sets user data into the session.
*
* If $data is a string, then it is interpreted as a session property
* key, and $value is expected to be non-null.
*
* If $data is an array, it is expected to be an array of key/value pairs
* to be set as session properties.
*
* @param array<string, mixed>|list<string>|string $data Property name or associative array of properties
* @param mixed $value Property value if single key provided
*
* @return void
*/
public function set($data, $value = null)
{
$data = is_array($data) ? $data : [$data => $value];
if (array_is_list($data)) {
$data = array_fill_keys($data, null);
}
foreach ($data as $sessionKey => $sessionValue) {
$_SESSION[$sessionKey] = $sessionValue;
}
}
/**
* Get user data that has been set in the session.
*
* If the property exists as "normal", returns it.
* Otherwise, returns an array of any temp or flash data values with the
* property key.
*
* Replaces the legacy method $session->userdata();
*
* @param string|null $key Identifier of the session property to retrieve
*
* @return ($key is string ? mixed : array<string, mixed>)
*/
public function get(?string $key = null)
{
if (! isset($_SESSION) || $_SESSION === []) {
return $key === null ? [] : null;
}
$key ??= '';
if ($key !== '') {
return $_SESSION[$key] ?? dot_array_search($key, $_SESSION);
}
$userdata = [];
$exclude = array_merge(['__ci_vars'], $this->getFlashKeys(), $this->getTempKeys());
foreach (array_keys($_SESSION) as $key) {
if (! in_array($key, $exclude, true)) {
$userdata[$key] = $_SESSION[$key];
}
}
return $userdata;
}
/**
* Returns whether an index exists in the session array.
*
* @param string $key Identifier of the session property we are interested in.
*/
public function has(string $key): bool
{
return isset($_SESSION[$key]);
}
/**
* Push new value onto session value that is array.
*
* @param string $key Identifier of the session property we are interested in.
* @param array<string, mixed> $data value to be pushed to existing session key.
*
* @return void
*/
public function push(string $key, array $data)
{
if ($this->has($key) && is_array($value = $this->get($key))) {
$this->set($key, array_merge($value, $data));
}
}
/**
* Remove one or more session properties.
*
* If $key is an array, it is interpreted as an array of string property
* identifiers to remove. Otherwise, it is interpreted as the identifier
* of a specific session property to remove.
*
* @param list<string>|string $key Identifier of the session property or properties to remove.
*
* @return void
*/
public function remove($key)
{
$key = is_array($key) ? $key : [$key];
foreach ($key as $k) {
unset($_SESSION[$k]);
}
}
/**
* Magic method to set variables in the session by simply calling
* $session->foo = bar;
*
* @param string $key Identifier of the session property to set.
* @param mixed $value
*
* @return void
*/
public function __set(string $key, $value)
{
$_SESSION[$key] = $value;
}
/**
* Magic method to get session variables by simply calling
* $foo = $session->foo;
*
* @param string $key Identifier of the session property to remove.
*
* @return mixed
*/
public function __get(string $key)
{
// Note: Keep this order the same, just in case somebody wants to
// use 'session_id' as a session data key, for whatever reason
if (isset($_SESSION[$key])) {
return $_SESSION[$key];
}
if ($key === 'session_id') {
return session_id();
}
return null;
}
/**
* Magic method to check for session variables.
*
* Different from `has()` in that it will validate 'session_id' as well.
* Mostly used by internal PHP functions, users should stick to `has()`.
*
* @param string $key Identifier of the session property to remove.
*/
public function __isset(string $key): bool
{
return isset($_SESSION[$key]) || $key === 'session_id';
}
/**
* Sets data into the session that will only last for a single request.
* Perfect for use with single-use status update messages.
*
* If $data is an array, it is interpreted as an associative array of
* key/value pairs for flashdata properties.
* Otherwise, it is interpreted as the identifier of a specific
* flashdata property, with $value containing the property value.
*
* @param array<string, mixed>|string $data Property identifier or associative array of properties
* @param mixed $value Property value if $data is a scalar
*
* @return void
*/
public function setFlashdata($data, $value = null)
{
$this->set($data, $value);
$this->markAsFlashdata(is_array($data) ? array_keys($data) : $data);
}
/**
* Retrieve one or more items of flash data from the session.
*
* If the item key is null, return all flashdata.
*
* @param string|null $key Property identifier
*
* @return ($key is string ? mixed : array<string, mixed>)
*/
public function getFlashdata(?string $key = null)
{
$_SESSION['__ci_vars'] ??= [];
if (isset($key)) {
if (! isset($_SESSION['__ci_vars'][$key]) || is_int($_SESSION['__ci_vars'][$key])) {
return null;
}
return $_SESSION[$key] ?? null;
}
$flashdata = [];
foreach ($_SESSION['__ci_vars'] as $key => $value) {
if (! is_int($value)) {
$flashdata[$key] = $_SESSION[$key];
}
}
return $flashdata;
}
/**
* Keeps a single piece of flash data alive for one more request.
*
* @param list<string>|string $key Property identifier or array of them
*
* @return void
*/
public function keepFlashdata($key)
{
$this->markAsFlashdata($key);
}
/**
* Mark a session property or properties as flashdata. This returns
* `false` if any of the properties were not already set.
*
* @param list<string>|string $key Property identifier or array of them
*/
public function markAsFlashdata($key): bool
{
$keys = is_array($key) ? $key : [$key];
foreach ($keys as $sessionKey) {
if (! isset($_SESSION[$sessionKey])) {
return false;
}
}
$_SESSION['__ci_vars'] ??= [];
$_SESSION['__ci_vars'] = [...$_SESSION['__ci_vars'], ...array_fill_keys($keys, 'new')];
return true;
}
/**
* Unmark data in the session as flashdata.
*
* @param list<string>|string $key Property identifier or array of them
*
* @return void
*/
public function unmarkFlashdata($key)
{
if (! isset($_SESSION['__ci_vars'])) {
return;
}
if (! is_array($key)) {
$key = [$key];
}
foreach ($key as $k) {
if (isset($_SESSION['__ci_vars'][$k]) && ! is_int($_SESSION['__ci_vars'][$k])) {
unset($_SESSION['__ci_vars'][$k]);
}
}
if ($_SESSION['__ci_vars'] === []) {
unset($_SESSION['__ci_vars']);
}
}
/**
* Retrieve all of the keys for session data marked as flashdata.
*
* @return list<string>
*/
public function getFlashKeys(): array
{
if (! isset($_SESSION['__ci_vars'])) {
return [];
}
$keys = [];
foreach (array_keys($_SESSION['__ci_vars']) as $key) {
if (! is_int($_SESSION['__ci_vars'][$key])) {
$keys[] = $key;
}
}
return $keys;
}
/**
* Sets new data into the session, and marks it as temporary data
* with a set lifespan.
*
* @param array<string, mixed>|list<string>|string $data Session data key or associative array of items
* @param mixed $value Value to store
* @param int $ttl Time-to-live in seconds
*
* @return void
*/
public function setTempdata($data, $value = null, int $ttl = 300)
{
$this->set($data, $value);
$this->markAsTempdata($data, $ttl);
}
/**
* Returns either a single piece of tempdata, or all temp data currently
* in the session.
*
* @param string|null $key Session data key
*
* @return ($key is string ? mixed : array<string, mixed>)
*/
public function getTempdata(?string $key = null)
{
$_SESSION['__ci_vars'] ??= [];
if (isset($key)) {
if (! isset($_SESSION['__ci_vars'][$key]) || ! is_int($_SESSION['__ci_vars'][$key])) {
return null;
}
return $_SESSION[$key] ?? null;
}
$tempdata = [];
foreach ($_SESSION['__ci_vars'] as $key => $value) {
if (is_int($value)) {
$tempdata[$key] = $_SESSION[$key];
}
}
return $tempdata;
}
/**
* Removes a single piece of temporary data from the session.
*
* @param string $key Session data key
*
* @return void
*/
public function removeTempdata(string $key)
{
$this->unmarkTempdata($key);
unset($_SESSION[$key]);
}
/**
* Mark one of more pieces of data as being temporary, meaning that
* it has a set lifespan within the session.
*
* Returns `false` if any of the properties were not set.
*
* @param array<string, mixed>|list<string>|string $key Property identifier or array of them
* @param int $ttl Time to live, in seconds
*/
public function markAsTempdata($key, int $ttl = 300): bool
{
$time = Time::now()->getTimestamp();
$keys = is_array($key) ? $key : [$key];
if (array_is_list($keys)) {
$keys = array_fill_keys($keys, $ttl);
}
$tempdata = [];
foreach ($keys as $sessionKey => $timeToLive) {
if (! array_key_exists($sessionKey, $_SESSION)) {
return false;
}
if (is_int($timeToLive)) {
$timeToLive += $time;
} else {
$timeToLive = $time + $ttl;
}
$tempdata[$sessionKey] = $timeToLive;
}
$_SESSION['__ci_vars'] ??= [];
$_SESSION['__ci_vars'] = [...$_SESSION['__ci_vars'], ...$tempdata];
return true;
}
/**
* Unmarks temporary data in the session, effectively removing its
* lifespan and allowing it to live as long as the session does.
*
* @param list<string>|string $key Property identifier or array of them
*
* @return void
*/
public function unmarkTempdata($key)
{
if (! isset($_SESSION['__ci_vars'])) {
return;
}
if (! is_array($key)) {
$key = [$key];
}
foreach ($key as $k) {
if (isset($_SESSION['__ci_vars'][$k]) && is_int($_SESSION['__ci_vars'][$k])) {
unset($_SESSION['__ci_vars'][$k]);
}
}
if ($_SESSION['__ci_vars'] === []) {
unset($_SESSION['__ci_vars']);
}
}
/**
* Retrieve the keys of all session data that have been marked as temporary data.
*
* @return list<string>
*/
public function getTempKeys(): array
{
if (! isset($_SESSION['__ci_vars'])) {
return [];
}
$keys = [];
foreach (array_keys($_SESSION['__ci_vars']) as $key) {
if (is_int($_SESSION['__ci_vars'][$key])) {
$keys[] = $key;
}
}
return $keys;
}
/**
* Sets the driver as the session handler in PHP.
* Extracted for easier testing.
*
* @return void
*/
protected function setSaveHandler()
{
session_set_save_handler($this->driver, true);
}
/**
* Starts the session.
* Extracted for testing reasons.
*
* @return void
*/
protected function startSession()
{
if (ENVIRONMENT === 'testing') {
$_SESSION = [];
return;
}
session_start(); // @codeCoverageIgnore
}
/**
* Takes care of setting the cookie on the client side.
*
* @codeCoverageIgnore
*
* @return void
*/
protected function setCookie()
{
$expiration = $this->config->expiration === 0 ? 0 : Time::now()->getTimestamp() + $this->config->expiration;
$this->cookie = $this->cookie->withValue(session_id())->withExpires($expiration);
$response = service('response');
$response->setCookie($this->cookie);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Session/Exceptions/SessionException.php | system/Session/Exceptions/SessionException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Exceptions;
use CodeIgniter\Exceptions\FrameworkException;
class SessionException extends FrameworkException
{
/**
* @return static
*/
public static function forMissingDatabaseTable()
{
return new static(lang('Session.missingDatabaseTable'));
}
/**
* @return static
*/
public static function forInvalidSavePath(?string $path = null)
{
return new static(lang('Session.invalidSavePath', [$path]));
}
/**
* @return static
*/
public static function forWriteProtectedSavePath(?string $path = null)
{
return new static(lang('Session.writeProtectedSavePath', [$path]));
}
/**
* @return static
*/
public static function forEmptySavepath()
{
return new static(lang('Session.emptySavePath'));
}
/**
* @return static
*/
public static function forInvalidSavePathFormat(string $path)
{
return new static(lang('Session.invalidSavePathFormat', [$path]));
}
/**
* @deprecated
*
* @return static
*
* @codeCoverageIgnore
*/
public static function forInvalidSameSiteSetting(string $samesite)
{
return new static(lang('Session.invalidSameSiteSetting', [$samesite]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Session/Handlers/DatabaseHandler.php | system/Session/Handlers/DatabaseHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Database\BaseConnection;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\Database;
use Config\Session as SessionConfig;
use ReturnTypeWillChange;
/**
* Base database session handler
*
* Do not use this class. Use database specific handler class.
*/
class DatabaseHandler extends BaseHandler
{
/**
* The database group to use for storage.
*
* @var string
*/
protected $DBGroup;
/**
* The name of the table to store session info.
*
* @var string
*/
protected $table;
/**
* The DB Connection instance.
*
* @var BaseConnection
*/
protected $db;
/**
* The database type
*
* @var string
*/
protected $platform;
/**
* Row exists flag
*
* @var bool
*/
protected $rowExists = false;
/**
* ID prefix for multiple session cookies
*/
protected string $idPrefix;
/**
* @throws SessionException
*/
public function __construct(SessionConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
// Store Session configurations
$this->DBGroup = $config->DBGroup ?? config(Database::class)->defaultGroup;
// Add sessionCookieName for multiple session cookies.
$this->idPrefix = $config->cookieName . ':';
$this->table = $this->savePath;
if (empty($this->table)) {
throw SessionException::forMissingDatabaseTable();
}
$this->db = Database::connect($this->DBGroup);
$this->platform = $this->db->getPlatform();
}
/**
* Re-initialize existing session, or creates a new one.
*
* @param string $path The path where to store/retrieve the session
* @param string $name The session name
*/
public function open($path, $name): bool
{
if (empty($this->db->connID)) {
$this->db->initialize();
}
return true;
}
/**
* Reads the session data from the session storage, and returns the results.
*
* @param string $id The session ID
*
* @return false|string Returns an encoded string of the read data.
* If nothing was read, it must return false.
*/
#[ReturnTypeWillChange]
public function read($id)
{
if ($this->lockSession($id) === false) {
$this->fingerprint = md5('');
return '';
}
if (! isset($this->sessionID)) {
$this->sessionID = $id;
}
$builder = $this->db->table($this->table)->where('id', $this->idPrefix . $id);
if ($this->matchIP) {
$builder = $builder->where('ip_address', $this->ipAddress);
}
$this->setSelect($builder);
$result = $builder->get()->getRow();
if ($result === null) {
// PHP7 will reuse the same SessionHandler object after
// ID regeneration, so we need to explicitly set this to
// FALSE instead of relying on the default ...
$this->rowExists = false;
$this->fingerprint = md5('');
return '';
}
$result = is_bool($result) ? '' : $this->decodeData($result->data);
$this->fingerprint = md5($result);
$this->rowExists = true;
return $result;
}
/**
* Sets SELECT clause
*
* @return void
*/
protected function setSelect(BaseBuilder $builder)
{
$builder->select('data');
}
/**
* Decodes column data
*
* @param string $data
*
* @return false|string
*/
protected function decodeData($data)
{
return $data;
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*/
public function write($id, $data): bool
{
if ($this->lock === false) {
return $this->fail();
}
if ($this->sessionID !== $id) {
$this->rowExists = false;
$this->sessionID = $id;
}
if ($this->rowExists === false) {
$insertData = [
'id' => $this->idPrefix . $id,
'ip_address' => $this->ipAddress,
'data' => $this->prepareData($data),
];
if (! $this->db->table($this->table)->set('timestamp', 'now()', false)->insert($insertData)) {
return $this->fail();
}
$this->fingerprint = md5($data);
$this->rowExists = true;
return true;
}
$builder = $this->db->table($this->table)->where('id', $this->idPrefix . $id);
if ($this->matchIP) {
$builder = $builder->where('ip_address', $this->ipAddress);
}
$updateData = [];
if ($this->fingerprint !== md5($data)) {
$updateData['data'] = $this->prepareData($data);
}
if (! $builder->set('timestamp', 'now()', false)->update($updateData)) {
return $this->fail();
}
$this->fingerprint = md5($data);
return true;
}
/**
* Prepare data to insert/update
*/
protected function prepareData(string $data): string
{
return $data;
}
/**
* Closes the current session.
*/
public function close(): bool
{
return ($this->lock && ! $this->releaseLock()) ? $this->fail() : true;
}
/**
* Destroys a session
*
* @param string $id The session ID being destroyed
*/
public function destroy($id): bool
{
if ($this->lock) {
$builder = $this->db->table($this->table)->where('id', $this->idPrefix . $id);
if ($this->matchIP) {
$builder = $builder->where('ip_address', $this->ipAddress);
}
if (! $builder->delete()) {
return $this->fail();
}
}
if ($this->close()) {
$this->destroyCookie();
return true;
}
return $this->fail();
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
return $this->db->table($this->table)->where(
'timestamp <',
"now() - INTERVAL {$max_lifetime} second",
false,
)->delete() ? 1 : $this->fail();
}
/**
* Releases the lock, if any.
*/
protected function releaseLock(): bool
{
if (! $this->lock) {
return true;
}
// Unsupported DB? Let the parent handle the simple version.
return parent::releaseLock();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Session/Handlers/ArrayHandler.php | system/Session/Handlers/ArrayHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use ReturnTypeWillChange;
/**
* Session handler using static array for storage.
* Intended only for use during testing.
*/
class ArrayHandler extends BaseHandler
{
protected static $cache = [];
/**
* Re-initialize existing session, or creates a new one.
*
* @param string $path The path where to store/retrieve the session
* @param string $name The session name
*/
public function open($path, $name): bool
{
return true;
}
/**
* Reads the session data from the session storage, and returns the results.
*
* @param string $id The session ID
*
* @return false|string Returns an encoded string of the read data.
* If nothing was read, it must return false.
*/
#[ReturnTypeWillChange]
public function read($id)
{
return '';
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*/
public function write($id, $data): bool
{
return true;
}
/**
* Closes the current session.
*/
public function close(): bool
{
return true;
}
/**
* Destroys a session
*
* @param string $id The session ID being destroyed
*/
public function destroy($id): bool
{
return true;
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
return 1;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Session/Handlers/RedisHandler.php | system/Session/Handlers/RedisHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use CodeIgniter\I18n\Time;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\Session as SessionConfig;
use Redis;
use RedisException;
use ReturnTypeWillChange;
/**
* Session handler using Redis for persistence
*/
class RedisHandler extends BaseHandler
{
private const DEFAULT_PORT = 6379;
private const DEFAULT_PROTOCOL = 'tcp';
/**
* phpRedis instance
*
* @var Redis|null
*/
protected $redis;
/**
* Key prefix
*
* @var string
*/
protected $keyPrefix = 'ci_session:';
/**
* Lock key
*
* @var string|null
*/
protected $lockKey;
/**
* Key exists flag
*
* @var bool
*/
protected $keyExists = false;
/**
* Number of seconds until the session ends.
*
* @var int
*/
protected $sessionExpiration = 7200;
/**
* Time (microseconds) to wait if lock cannot be acquired.
*/
private int $lockRetryInterval = 100_000;
/**
* Maximum number of lock acquisition attempts.
*/
private int $lockMaxRetries = 300;
/**
* @param string $ipAddress User's IP address
*
* @throws SessionException
*/
public function __construct(SessionConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
// Store Session configurations
$this->sessionExpiration = ($config->expiration === 0)
? (int) ini_get('session.gc_maxlifetime')
: $config->expiration;
// Add sessionCookieName for multiple session cookies.
$this->keyPrefix .= $config->cookieName . ':';
$this->setSavePath();
if ($this->matchIP === true) {
$this->keyPrefix .= $this->ipAddress . ':';
}
$this->lockRetryInterval = $config->lockWait ?? $this->lockRetryInterval;
$this->lockMaxRetries = $config->lockAttempts ?? $this->lockMaxRetries;
}
protected function setSavePath(): void
{
if (empty($this->savePath)) {
throw SessionException::forEmptySavepath();
}
$url = parse_url($this->savePath);
$query = [];
if ($url === false) {
// Unix domain socket like `unix:///var/run/redis/redis.sock?persistent=1`.
if (preg_match('#unix://(/[^:?]+)(\?.+)?#', $this->savePath, $matches)) {
$host = $matches[1];
$port = 0;
if (isset($matches[2])) {
parse_str(ltrim($matches[2], '?'), $query);
}
} else {
throw SessionException::forInvalidSavePathFormat($this->savePath);
}
} else {
// Also accepts `/var/run/redis.sock` for backward compatibility.
if (isset($url['path']) && $url['path'][0] === '/') {
$host = $url['path'];
$port = 0;
} else {
// TCP connection.
if (! isset($url['host'])) {
throw SessionException::forInvalidSavePathFormat($this->savePath);
}
$protocol = $url['scheme'] ?? self::DEFAULT_PROTOCOL;
$host = $protocol . '://' . $url['host'];
$port = $url['port'] ?? self::DEFAULT_PORT;
}
if (isset($url['query'])) {
parse_str($url['query'], $query);
}
}
$password = $query['auth'] ?? null;
$database = isset($query['database']) ? (int) $query['database'] : 0;
$timeout = isset($query['timeout']) ? (float) $query['timeout'] : 0.0;
$prefix = $query['prefix'] ?? null;
$this->savePath = [
'host' => $host,
'port' => $port,
'password' => $password,
'database' => $database,
'timeout' => $timeout,
];
if ($prefix !== null) {
$this->keyPrefix = $prefix;
}
}
/**
* Re-initialize existing session, or creates a new one.
*
* @param string $path The path where to store/retrieve the session
* @param string $name The session name
*
* @throws RedisException
*/
public function open($path, $name): bool
{
if (empty($this->savePath)) {
return false;
}
$redis = new Redis();
if (
! $redis->connect(
$this->savePath['host'],
$this->savePath['port'],
$this->savePath['timeout'],
)
) {
$this->logger->error('Session: Unable to connect to Redis with the configured settings.');
} elseif (isset($this->savePath['password']) && ! $redis->auth($this->savePath['password'])) {
$this->logger->error('Session: Unable to authenticate to Redis instance.');
} elseif (isset($this->savePath['database']) && ! $redis->select($this->savePath['database'])) {
$this->logger->error(
'Session: Unable to select Redis database with index ' . $this->savePath['database'],
);
} else {
$this->redis = $redis;
return true;
}
return false;
}
/**
* Reads the session data from the session storage, and returns the results.
*
* @param string $id The session ID
*
* @return false|string Returns an encoded string of the read data.
* If nothing was read, it must return false.
*
* @throws RedisException
*/
#[ReturnTypeWillChange]
public function read($id)
{
if (isset($this->redis) && $this->lockSession($id)) {
if (! isset($this->sessionID)) {
$this->sessionID = $id;
}
$data = $this->redis->get($this->keyPrefix . $id);
if (is_string($data)) {
$this->keyExists = true;
} else {
$data = '';
}
$this->fingerprint = md5($data);
return $data;
}
return false;
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*
* @throws RedisException
*/
public function write($id, $data): bool
{
if (! isset($this->redis)) {
return false;
}
if ($this->sessionID !== $id) {
if (! $this->releaseLock() || ! $this->lockSession($id)) {
return false;
}
$this->keyExists = false;
$this->sessionID = $id;
}
if (isset($this->lockKey)) {
$this->redis->expire($this->lockKey, 300);
if ($this->fingerprint !== ($fingerprint = md5($data)) || $this->keyExists === false) {
if ($this->redis->set($this->keyPrefix . $id, $data, $this->sessionExpiration)) {
$this->fingerprint = $fingerprint;
$this->keyExists = true;
return true;
}
return false;
}
return $this->redis->expire($this->keyPrefix . $id, $this->sessionExpiration);
}
return false;
}
/**
* Closes the current session.
*/
public function close(): bool
{
if (isset($this->redis)) {
try {
$pingReply = $this->redis->ping();
if (($pingReply === true) || ($pingReply === '+PONG')) {
if (isset($this->lockKey) && ! $this->releaseLock()) {
return false;
}
if (! $this->redis->close()) {
return false;
}
}
} catch (RedisException $e) {
$this->logger->error('Session: Got RedisException on close(): ' . $e->getMessage());
}
$this->redis = null;
return true;
}
return true;
}
/**
* Destroys a session
*
* @param string $id The session ID being destroyed
*
* @throws RedisException
*/
public function destroy($id): bool
{
if (isset($this->redis, $this->lockKey)) {
if (($result = $this->redis->del($this->keyPrefix . $id)) !== 1) {
$this->logger->debug(
'Session: Redis::del() expected to return 1, got ' . var_export($result, true) . ' instead.',
);
}
return $this->destroyCookie();
}
return false;
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
return 1;
}
/**
* Acquires an emulated lock.
*
* @param string $sessionID Session ID
*
* @throws RedisException
*/
protected function lockSession(string $sessionID): bool
{
$lockKey = $this->keyPrefix . $sessionID . ':lock';
// PHP 7 reuses the SessionHandler object on regeneration,
// so we need to check here if the lock key is for the
// correct session ID.
if ($this->lockKey === $lockKey) {
// If there is the lock, make the ttl longer.
return $this->redis->expire($this->lockKey, 300);
}
$attempt = 0;
do {
$result = $this->redis->set(
$lockKey,
(string) Time::now()->getTimestamp(),
// NX -- Only set the key if it does not already exist.
// EX seconds -- Set the specified expire time, in seconds.
['nx', 'ex' => 300],
);
if (! $result) {
usleep($this->lockRetryInterval);
continue;
}
$this->lockKey = $lockKey;
break;
} while (++$attempt < $this->lockMaxRetries);
if ($attempt === 300) {
$this->logger->error(
'Session: Unable to obtain lock for ' . $this->keyPrefix . $sessionID
. ' after 300 attempts, aborting.',
);
return false;
}
$this->lock = true;
return true;
}
/**
* Releases a previously acquired lock
*
* @throws RedisException
*/
protected function releaseLock(): bool
{
if (isset($this->redis, $this->lockKey) && $this->lock) {
if (! $this->redis->del($this->lockKey)) {
$this->logger->error('Session: Error while trying to free lock for ' . $this->lockKey);
return false;
}
$this->lockKey = null;
$this->lock = false;
}
return true;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Session/Handlers/FileHandler.php | system/Session/Handlers/FileHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use CodeIgniter\I18n\Time;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\Session as SessionConfig;
use ReturnTypeWillChange;
/**
* Session handler using file system for storage
*/
class FileHandler extends BaseHandler
{
/**
* Where to save the session files to.
*
* @var string
*/
protected $savePath;
/**
* The file handle
*
* @var resource|null
*/
protected $fileHandle;
/**
* File Name
*
* @var string
*/
protected $filePath;
/**
* Whether this is a new file.
*
* @var bool
*/
protected $fileNew;
/**
* Whether IP addresses should be matched.
*
* @var bool
*/
protected $matchIP = false;
/**
* Regex of session ID
*
* @var string
*/
protected $sessionIDRegex = '';
public function __construct(SessionConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
if (! empty($this->savePath)) {
$this->savePath = rtrim($this->savePath, '/\\');
ini_set('session.save_path', $this->savePath);
} else {
$sessionPath = rtrim(ini_get('session.save_path'), '/\\');
if ($sessionPath === '') {
$sessionPath = WRITEPATH . 'session';
}
$this->savePath = $sessionPath;
}
$this->configureSessionIDRegex();
}
/**
* Re-initialize existing session, or creates a new one.
*
* @param string $path The path where to store/retrieve the session
* @param string $name The session name
*
* @throws SessionException
*/
public function open($path, $name): bool
{
if (! is_dir($path) && ! mkdir($path, 0700, true)) {
throw SessionException::forInvalidSavePath($this->savePath);
}
if (! is_writable($path)) {
throw SessionException::forWriteProtectedSavePath($this->savePath);
}
$this->savePath = $path;
// we'll use the session name as prefix to avoid collisions
$this->filePath = $this->savePath . '/' . $name . ($this->matchIP ? md5($this->ipAddress) : '');
return true;
}
/**
* Reads the session data from the session storage, and returns the results.
*
* @param string $id The session ID
*
* @return false|string Returns an encoded string of the read data.
* If nothing was read, it must return false.
*/
#[ReturnTypeWillChange]
public function read($id)
{
// This might seem weird, but PHP 5.6 introduced session_reset(),
// which re-reads session data
if ($this->fileHandle === null) {
$this->fileNew = ! is_file($this->filePath . $id);
if (($this->fileHandle = fopen($this->filePath . $id, 'c+b')) === false) {
$this->logger->error("Session: Unable to open file '" . $this->filePath . $id . "'.");
return false;
}
if (flock($this->fileHandle, LOCK_EX) === false) {
$this->logger->error("Session: Unable to obtain lock for file '" . $this->filePath . $id . "'.");
fclose($this->fileHandle);
$this->fileHandle = null;
return false;
}
if (! isset($this->sessionID)) {
$this->sessionID = $id;
}
if ($this->fileNew) {
chmod($this->filePath . $id, 0600);
$this->fingerprint = md5('');
return '';
}
} else {
rewind($this->fileHandle);
}
$data = '';
$buffer = 0;
clearstatcache(); // Address https://github.com/codeigniter4/CodeIgniter4/issues/2056
for ($read = 0, $length = filesize($this->filePath . $id); $read < $length; $read += strlen($buffer)) {
if (($buffer = fread($this->fileHandle, $length - $read)) === false) {
break;
}
$data .= $buffer;
}
$this->fingerprint = md5($data);
return $data;
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*/
public function write($id, $data): bool
{
// If the two IDs don't match, we have a session_regenerate_id() call
if ($id !== $this->sessionID) {
$this->sessionID = $id;
}
if (! is_resource($this->fileHandle)) {
return false;
}
if ($this->fingerprint === md5($data)) {
return ($this->fileNew) ? true : touch($this->filePath . $id);
}
if (! $this->fileNew) {
ftruncate($this->fileHandle, 0);
rewind($this->fileHandle);
}
if (($length = strlen($data)) > 0) {
$result = null;
$written = 0;
for (; $written < $length; $written += $result) {
if (($result = fwrite($this->fileHandle, substr($data, $written))) === false) {
break;
}
}
if (! is_int($result)) {
$this->fingerprint = md5(substr($data, 0, $written));
$this->logger->error('Session: Unable to write data.');
return false;
}
}
$this->fingerprint = md5($data);
return true;
}
/**
* Closes the current session.
*/
public function close(): bool
{
if (is_resource($this->fileHandle)) {
flock($this->fileHandle, LOCK_UN);
fclose($this->fileHandle);
$this->fileHandle = null;
$this->fileNew = false;
}
return true;
}
/**
* Destroys a session
*
* @param string $id The session ID being destroyed
*/
public function destroy($id): bool
{
if ($this->close()) {
return is_file($this->filePath . $id)
? (unlink($this->filePath . $id) && $this->destroyCookie())
: true;
}
if ($this->filePath !== null) {
clearstatcache();
return is_file($this->filePath . $id)
? (unlink($this->filePath . $id) && $this->destroyCookie())
: true;
}
return false;
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
if (! is_dir($this->savePath) || ($directory = opendir($this->savePath)) === false) {
$this->logger->debug("Session: Garbage collector couldn't list files under directory '" . $this->savePath . "'.");
return false;
}
$ts = Time::now()->getTimestamp() - $max_lifetime;
$pattern = $this->matchIP === true ? '[0-9a-f]{32}' : '';
$pattern = sprintf(
'#\A%s' . $pattern . $this->sessionIDRegex . '\z#',
preg_quote($this->cookieName, '#'),
);
$collected = 0;
while (($file = readdir($directory)) !== false) {
// If the filename doesn't match this pattern, it's either not a session file or is not ours
if (preg_match($pattern, $file) !== 1
|| ! is_file($this->savePath . DIRECTORY_SEPARATOR . $file)
|| ($mtime = filemtime($this->savePath . DIRECTORY_SEPARATOR . $file)) === false
|| $mtime > $ts
) {
continue;
}
unlink($this->savePath . DIRECTORY_SEPARATOR . $file);
$collected++;
}
closedir($directory);
return $collected;
}
/**
* Configure Session ID regular expression
*
* To make life easier, we force the PHP defaults. Because PHP9 forces them.
*
* @see https://wiki.php.net/rfc/deprecations_php_8_4#sessionsid_length_and_sessionsid_bits_per_character
*
* @return void
*/
protected function configureSessionIDRegex()
{
$bitsPerCharacter = (int) ini_get('session.sid_bits_per_character');
$sidLength = (int) ini_get('session.sid_length');
// We force the PHP defaults.
if (PHP_VERSION_ID < 90000) {
if ($bitsPerCharacter !== 4) {
ini_set('session.sid_bits_per_character', '4');
}
if ($sidLength !== 32) {
ini_set('session.sid_length', '32');
}
}
$this->sessionIDRegex = '[0-9a-f]{32}';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Session/Handlers/BaseHandler.php | system/Session/Handlers/BaseHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use Config\Cookie as CookieConfig;
use Config\Session as SessionConfig;
use Psr\Log\LoggerAwareTrait;
use SessionHandlerInterface;
/**
* Base class for session handling
*/
abstract class BaseHandler implements SessionHandlerInterface
{
use LoggerAwareTrait;
/**
* The Data fingerprint.
*
* @var string
*/
protected $fingerprint;
/**
* Lock placeholder.
*
* @var bool|string
*/
protected $lock = false;
/**
* Cookie prefix
*
* The Config\Cookie::$prefix setting is completely ignored.
* See https://codeigniter.com/user_guide/libraries/sessions.html#session-preferences
*
* @var string
*/
protected $cookiePrefix = '';
/**
* Cookie domain
*
* @var string
*/
protected $cookieDomain = '';
/**
* Cookie path
*
* @var string
*/
protected $cookiePath = '/';
/**
* Cookie secure?
*
* @var bool
*/
protected $cookieSecure = false;
/**
* Cookie name to use
*
* @var string
*/
protected $cookieName;
/**
* Match IP addresses for cookies?
*
* @var bool
*/
protected $matchIP = false;
/**
* Current session ID
*
* @var string|null
*/
protected $sessionID;
/**
* The 'save path' for the session
* varies between
*
* @var array|string
*/
protected $savePath;
/**
* User's IP address.
*
* @var string
*/
protected $ipAddress;
public function __construct(SessionConfig $config, string $ipAddress)
{
// Store Session configurations
$this->cookieName = $config->cookieName;
$this->matchIP = $config->matchIP;
$this->savePath = $config->savePath;
$cookie = config(CookieConfig::class);
// Session cookies have no prefix.
$this->cookieDomain = $cookie->domain;
$this->cookiePath = $cookie->path;
$this->cookieSecure = $cookie->secure;
$this->ipAddress = $ipAddress;
}
/**
* Internal method to force removal of a cookie by the client
* when session_destroy() is called.
*/
protected function destroyCookie(): bool
{
return setcookie(
$this->cookieName,
'',
['expires' => 1, 'path' => $this->cookiePath, 'domain' => $this->cookieDomain, 'secure' => $this->cookieSecure, 'httponly' => true],
);
}
/**
* A dummy method allowing drivers with no locking functionality
* (databases other than PostgreSQL and MySQL) to act as if they
* do acquire a lock.
*/
protected function lockSession(string $sessionID): bool
{
$this->lock = true;
return true;
}
/**
* Releases the lock, if any.
*/
protected function releaseLock(): bool
{
$this->lock = false;
return true;
}
/**
* Drivers other than the 'files' one don't (need to) use the
* session.save_path INI setting, but that leads to confusing
* error messages emitted by PHP when open() or write() fail,
* as the message contains session.save_path ...
*
* To work around the problem, the drivers will call this method
* so that the INI is set just in time for the error message to
* be properly generated.
*/
protected function fail(): bool
{
ini_set('session.save_path', $this->savePath);
return false;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Session/Handlers/MemcachedHandler.php | system/Session/Handlers/MemcachedHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers;
use CodeIgniter\I18n\Time;
use CodeIgniter\Session\Exceptions\SessionException;
use Config\Session as SessionConfig;
use Memcached;
use ReturnTypeWillChange;
/**
* Session handler using Memcache for persistence
*/
class MemcachedHandler extends BaseHandler
{
/**
* Memcached instance
*
* @var Memcached|null
*/
protected $memcached;
/**
* Key prefix
*
* @var string
*/
protected $keyPrefix = 'ci_session:';
/**
* Lock key
*
* @var string|null
*/
protected $lockKey;
/**
* Number of seconds until the session ends.
*
* @var int
*/
protected $sessionExpiration = 7200;
/**
* @throws SessionException
*/
public function __construct(SessionConfig $config, string $ipAddress)
{
parent::__construct($config, $ipAddress);
$this->sessionExpiration = $config->expiration;
if (empty($this->savePath)) {
throw SessionException::forEmptySavepath();
}
// Add sessionCookieName for multiple session cookies.
$this->keyPrefix .= $config->cookieName . ':';
if ($this->matchIP === true) {
$this->keyPrefix .= $this->ipAddress . ':';
}
ini_set('memcached.sess_prefix', $this->keyPrefix);
}
/**
* Re-initialize existing session, or creates a new one.
*
* @param string $path The path where to store/retrieve the session
* @param string $name The session name
*/
public function open($path, $name): bool
{
$this->memcached = new Memcached();
$this->memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true); // required for touch() usage
$serverList = [];
foreach ($this->memcached->getServerList() as $server) {
$serverList[] = $server['host'] . ':' . $server['port'];
}
if (
preg_match_all(
'#,?([^,:]+)\:(\d{1,5})(?:\:(\d+))?#',
$this->savePath,
$matches,
PREG_SET_ORDER,
) < 1
) {
$this->memcached = null;
$this->logger->error('Session: Invalid Memcached save path format: ' . $this->savePath);
return false;
}
foreach ($matches as $match) {
// If Memcached already has this server (or if the port is invalid), skip it
if (in_array($match[1] . ':' . $match[2], $serverList, true)) {
$this->logger->debug(
'Session: Memcached server pool already has ' . $match[1] . ':' . $match[2],
);
continue;
}
if (! $this->memcached->addServer($match[1], (int) $match[2], $match[3] ?? 0)) {
$this->logger->error(
'Could not add ' . $match[1] . ':' . $match[2] . ' to Memcached server pool.',
);
} else {
$serverList[] = $match[1] . ':' . $match[2];
}
}
if ($serverList === []) {
$this->logger->error('Session: Memcached server pool is empty.');
return false;
}
return true;
}
/**
* Reads the session data from the session storage, and returns the results.
*
* @param string $id The session ID
*
* @return false|string Returns an encoded string of the read data.
* If nothing was read, it must return false.
*/
#[ReturnTypeWillChange]
public function read($id)
{
if (isset($this->memcached) && $this->lockSession($id)) {
if (! isset($this->sessionID)) {
$this->sessionID = $id;
}
$data = (string) $this->memcached->get($this->keyPrefix . $id);
$this->fingerprint = md5($data);
return $data;
}
return '';
}
/**
* Writes the session data to the session storage.
*
* @param string $id The session ID
* @param string $data The encoded session data
*/
public function write($id, $data): bool
{
if (! isset($this->memcached)) {
return false;
}
if ($this->sessionID !== $id) {
if (! $this->releaseLock() || ! $this->lockSession($id)) {
return false;
}
$this->fingerprint = md5('');
$this->sessionID = $id;
}
if (isset($this->lockKey)) {
$this->memcached->replace($this->lockKey, Time::now()->getTimestamp(), 300);
if ($this->fingerprint !== ($fingerprint = md5($data))) {
if ($this->memcached->set($this->keyPrefix . $id, $data, $this->sessionExpiration)) {
$this->fingerprint = $fingerprint;
return true;
}
return false;
}
return $this->memcached->touch($this->keyPrefix . $id, $this->sessionExpiration);
}
return false;
}
/**
* Closes the current session.
*/
public function close(): bool
{
if (isset($this->memcached)) {
if (isset($this->lockKey)) {
$this->memcached->delete($this->lockKey);
}
if (! $this->memcached->quit()) {
return false;
}
$this->memcached = null;
return true;
}
return false;
}
/**
* Destroys a session
*
* @param string $id The session ID being destroyed
*/
public function destroy($id): bool
{
if (isset($this->memcached, $this->lockKey)) {
$this->memcached->delete($this->keyPrefix . $id);
return $this->destroyCookie();
}
return false;
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
return 1;
}
/**
* Acquires an emulated lock.
*
* @param string $sessionID Session ID
*/
protected function lockSession(string $sessionID): bool
{
if (isset($this->lockKey)) {
return $this->memcached->replace($this->lockKey, Time::now()->getTimestamp(), 300);
}
$lockKey = $this->keyPrefix . $sessionID . ':lock';
$attempt = 0;
do {
if ($this->memcached->get($lockKey) !== false) {
sleep(1);
continue;
}
if (! $this->memcached->set($lockKey, Time::now()->getTimestamp(), 300)) {
$this->logger->error(
'Session: Error while trying to obtain lock for ' . $this->keyPrefix . $sessionID,
);
return false;
}
$this->lockKey = $lockKey;
break;
} while (++$attempt < 30);
if ($attempt === 30) {
$this->logger->error(
'Session: Unable to obtain lock for ' . $this->keyPrefix . $sessionID . ' after 30 attempts, aborting.',
);
return false;
}
$this->lock = true;
return true;
}
/**
* Releases a previously acquired lock
*/
protected function releaseLock(): bool
{
if (isset($this->memcached, $this->lockKey) && $this->lock) {
if (
! $this->memcached->delete($this->lockKey)
&& $this->memcached->getResultCode() !== Memcached::RES_NOTFOUND
) {
$this->logger->error(
'Session: Error while trying to free lock for ' . $this->lockKey,
);
return false;
}
$this->lockKey = null;
$this->lock = false;
}
return true;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Session/Handlers/Database/PostgreHandler.php | system/Session/Handlers/Database/PostgreHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers\Database;
use CodeIgniter\Database\BaseBuilder;
use CodeIgniter\Session\Handlers\DatabaseHandler;
use ReturnTypeWillChange;
/**
* Session handler for Postgre
*
* @see \CodeIgniter\Session\Handlers\Database\PostgreHandlerTest
*/
class PostgreHandler extends DatabaseHandler
{
/**
* Sets SELECT clause
*
* @return void
*/
protected function setSelect(BaseBuilder $builder)
{
$builder->select("encode(data, 'base64') AS data");
}
/**
* Decodes column data
*
* @param string $data
*
* @return false|string
*/
protected function decodeData($data)
{
return base64_decode(rtrim($data), true);
}
/**
* Prepare data to insert/update
*/
protected function prepareData(string $data): string
{
return '\x' . bin2hex($data);
}
/**
* Cleans up expired sessions.
*
* @param int $max_lifetime Sessions that have not updated
* for the last max_lifetime seconds will be removed.
*
* @return false|int Returns the number of deleted sessions on success, or false on failure.
*/
#[ReturnTypeWillChange]
public function gc($max_lifetime)
{
$separator = '\'';
$interval = implode($separator, ['', "{$max_lifetime} second", '']);
return $this->db->table($this->table)->where('timestamp <', "now() - INTERVAL {$interval}", false)->delete() ? 1 : $this->fail();
}
/**
* Lock the session.
*/
protected function lockSession(string $sessionID): bool
{
$arg = "hashtext('{$sessionID}')" . ($this->matchIP ? ", hashtext('{$this->ipAddress}')" : '');
if ($this->db->simpleQuery("SELECT pg_advisory_lock({$arg})") !== false) {
$this->lock = $arg;
return true;
}
return $this->fail();
}
/**
* Releases the lock, if any.
*/
protected function releaseLock(): bool
{
if (! $this->lock) {
return true;
}
if ($this->db->simpleQuery("SELECT pg_advisory_unlock({$this->lock})") !== false) {
$this->lock = false;
return true;
}
return $this->fail();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Session/Handlers/Database/MySQLiHandler.php | system/Session/Handlers/Database/MySQLiHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Session\Handlers\Database;
use CodeIgniter\Session\Handlers\DatabaseHandler;
/**
* Session handler for MySQLi
*
* @see \CodeIgniter\Session\Handlers\Database\MySQLiHandlerTest
*/
class MySQLiHandler extends DatabaseHandler
{
/**
* Lock the session.
*/
protected function lockSession(string $sessionID): bool
{
$arg = md5($sessionID . ($this->matchIP ? '_' . $this->ipAddress : ''));
if ($this->db->query("SELECT GET_LOCK('{$arg}', 300) AS ci_session_lock")->getRow()->ci_session_lock) {
$this->lock = $arg;
return true;
}
return $this->fail();
}
/**
* Releases the lock, if any.
*/
protected function releaseLock(): bool
{
if (! $this->lock) {
return true;
}
if ($this->db->query("SELECT RELEASE_LOCK('{$this->lock}') AS ci_session_lock")->getRow()->ci_session_lock) {
$this->lock = false;
return true;
}
return $this->fail();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Log/Logger.php | system/Log/Logger.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Log;
use CodeIgniter\Exceptions\RuntimeException;
use CodeIgniter\Log\Exceptions\LogException;
use CodeIgniter\Log\Handlers\HandlerInterface;
use Psr\Log\LoggerInterface;
use Stringable;
use Throwable;
/**
* The CodeIgntier Logger
*
* The message MUST be a string or object implementing __toString().
*
* The message MAY contain placeholders in the form: {foo} where foo
* will be replaced by the context data in key "foo".
*
* The context array can contain arbitrary data, the only assumption that
* can be made by implementors is that if an Exception instance is given
* to produce a stack trace, it MUST be in a key named "exception".
*
* @see \CodeIgniter\Log\LoggerTest
*/
class Logger implements LoggerInterface
{
/**
* Used by the logThreshold Config setting to define
* which errors to show.
*
* @var array<string, int>
*/
protected $logLevels = [
'emergency' => 1,
'alert' => 2,
'critical' => 3,
'error' => 4,
'warning' => 5,
'notice' => 6,
'info' => 7,
'debug' => 8,
];
/**
* Array of levels to be logged. The rest will be ignored.
*
* Set in app/Config/Logger.php
*
* @var list<string>
*/
protected $loggableLevels = [];
/**
* File permissions
*
* @var int
*/
protected $filePermissions = 0644;
/**
* Format of the timestamp for log files.
*
* @var string
*/
protected $dateFormat = 'Y-m-d H:i:s';
/**
* Filename Extension
*
* @var string
*/
protected $fileExt;
/**
* Caches instances of the handlers.
*
* @var array<class-string<HandlerInterface>, HandlerInterface>
*/
protected $handlers = [];
/**
* Holds the configuration for each handler.
* The key is the handler's class name. The
* value is an associative array of configuration
* items.
*
* @var array<class-string<HandlerInterface>, array<string, int|list<string>|string>>
*/
protected $handlerConfig = [];
/**
* Caches logging calls for debugbar.
*
* @var list<array{level: string, msg: string}>
*/
public $logCache;
/**
* Should we cache our logged items?
*
* @var bool
*/
protected $cacheLogs = false;
/**
* Constructor.
*
* @param \Config\Logger $config
*
* @throws RuntimeException
*/
public function __construct($config, bool $debug = CI_DEBUG)
{
$loggableLevels = is_array($config->threshold) ? $config->threshold : range(1, (int) $config->threshold);
// Now convert loggable levels to strings.
// We only use numbers to make the threshold setting convenient for users.
foreach ($loggableLevels as $level) {
/** @var false|string $stringLevel */
$stringLevel = array_search($level, $this->logLevels, true);
if ($stringLevel === false) {
continue;
}
$this->loggableLevels[] = $stringLevel;
}
if (isset($config->dateFormat)) {
$this->dateFormat = $config->dateFormat;
}
if ($config->handlers === []) {
throw LogException::forNoHandlers('LoggerConfig');
}
// Save the handler configuration for later.
// Instances will be created on demand.
$this->handlerConfig = $config->handlers;
$this->cacheLogs = $debug;
if ($this->cacheLogs) {
$this->logCache = [];
}
}
/**
* System is unusable.
*/
public function emergency(string|Stringable $message, array $context = []): void
{
$this->log('emergency', $message, $context);
}
/**
* Action must be taken immediately.
*
* Example: Entire website down, database unavailable, etc. This should
* trigger the SMS alerts and wake you up.
*/
public function alert(string|Stringable $message, array $context = []): void
{
$this->log('alert', $message, $context);
}
/**
* Critical conditions.
*
* Example: Application component unavailable, unexpected exception.
*/
public function critical(string|Stringable $message, array $context = []): void
{
$this->log('critical', $message, $context);
}
/**
* Runtime errors that do not require immediate action but should typically
* be logged and monitored.
*/
public function error(string|Stringable $message, array $context = []): void
{
$this->log('error', $message, $context);
}
/**
* Exceptional occurrences that are not errors.
*
* Example: Use of deprecated APIs, poor use of an API, undesirable things
* that are not necessarily wrong.
*/
public function warning(string|Stringable $message, array $context = []): void
{
$this->log('warning', $message, $context);
}
/**
* Normal but significant events.
*/
public function notice(string|Stringable $message, array $context = []): void
{
$this->log('notice', $message, $context);
}
/**
* Interesting events.
*
* Example: User logs in, SQL logs.
*/
public function info(string|Stringable $message, array $context = []): void
{
$this->log('info', $message, $context);
}
/**
* Detailed debug information.
*/
public function debug(string|Stringable $message, array $context = []): void
{
$this->log('debug', $message, $context);
}
/**
* Logs with an arbitrary level.
*
* @param mixed $level
*/
public function log($level, string|Stringable $message, array $context = []): void
{
if (is_numeric($level)) {
$level = array_search((int) $level, $this->logLevels, true);
}
if (! array_key_exists($level, $this->logLevels)) {
throw LogException::forInvalidLogLevel($level);
}
if (! in_array($level, $this->loggableLevels, true)) {
return;
}
$message = $this->interpolate($message, $context);
if ($this->cacheLogs) {
$this->logCache[] = ['level' => $level, 'msg' => $message];
}
foreach ($this->handlerConfig as $className => $config) {
if (! array_key_exists($className, $this->handlers)) {
$this->handlers[$className] = new $className($config);
}
$handler = $this->handlers[$className];
if (! $handler->canHandle($level)) {
continue;
}
// If the handler returns false, then we don't execute any other handlers.
if (! $handler->setDateFormat($this->dateFormat)->handle($level, $message)) {
break;
}
}
}
/**
* Replaces any placeholders in the message with variables
* from the context, as well as a few special items like:
*
* {session_vars}
* {post_vars}
* {get_vars}
* {env}
* {env:foo}
* {file}
* {line}
*
* @param string|Stringable $message
* @param array<string, mixed> $context
*
* @return string
*/
protected function interpolate($message, array $context = [])
{
if (! is_string($message)) {
return print_r($message, true);
}
$replace = [];
foreach ($context as $key => $val) {
// Verify that the 'exception' key is actually an exception
// or error, both of which implement the 'Throwable' interface.
if ($key === 'exception' && $val instanceof Throwable) {
$val = $val->getMessage() . ' ' . clean_path($val->getFile()) . ':' . $val->getLine();
}
// todo - sanitize input before writing to file?
$replace['{' . $key . '}'] = $val;
}
$replace['{post_vars}'] = '$_POST: ' . print_r($_POST, true);
$replace['{get_vars}'] = '$_GET: ' . print_r($_GET, true);
$replace['{env}'] = ENVIRONMENT;
// Allow us to log the file/line that we are logging from
if (str_contains($message, '{file}') || str_contains($message, '{line}')) {
[$file, $line] = $this->determineFile();
$replace['{file}'] = $file;
$replace['{line}'] = $line;
}
// Match up environment variables in {env:foo} tags.
if (str_contains($message, 'env:')) {
preg_match('/env:[^}]+/', $message, $matches);
foreach ($matches as $str) {
$key = str_replace('env:', '', $str);
$replace["{{$str}}"] = $_ENV[$key] ?? 'n/a';
}
}
if (isset($_SESSION)) {
$replace['{session_vars}'] = '$_SESSION: ' . print_r($_SESSION, true);
}
return strtr($message, $replace);
}
/**
* Determines the file and line that the logging call
* was made from by analyzing the backtrace.
* Find the earliest stack frame that is part of our logging system.
*
* @return array{string, int|string}
*/
public function determineFile(): array
{
$logFunctions = [
'log_message',
'log',
'error',
'debug',
'info',
'warning',
'critical',
'emergency',
'alert',
'notice',
];
$trace = debug_backtrace(0);
$stackFrames = array_reverse($trace);
foreach ($stackFrames as $frame) {
if (in_array($frame['function'], $logFunctions, true)) {
$file = isset($frame['file']) ? clean_path($frame['file']) : 'unknown';
$line = $frame['line'] ?? 'unknown';
return [$file, $line];
}
}
return ['unknown', 'unknown'];
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Log/Exceptions/LogException.php | system/Log/Exceptions/LogException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Log\Exceptions;
use CodeIgniter\Exceptions\FrameworkException;
class LogException extends FrameworkException
{
/**
* @return static
*/
public static function forInvalidLogLevel(string $level)
{
return new static(lang('Log.invalidLogLevel', [$level]));
}
/**
* @return static
*/
public static function forInvalidMessageType(string $messageType)
{
return new static(lang('Log.invalidMessageType', [$messageType]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Log/Handlers/ChromeLoggerHandler.php | system/Log/Handlers/ChromeLoggerHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Log\Handlers;
use CodeIgniter\HTTP\ResponseInterface;
/**
* Allows for logging items to the Chrome console for debugging.
* Requires the ChromeLogger extension installed in your browser.
*
* @see https://craig.is/writing/chrome-logger
* @see \CodeIgniter\Log\Handlers\ChromeLoggerHandlerTest
*/
class ChromeLoggerHandler extends BaseHandler
{
/**
* Version of this library - for ChromeLogger use.
*/
public const VERSION = 1.0;
/**
* The number of track frames returned from the backtrace.
*
* @var int
*/
protected $backtraceLevel = 0;
/**
* The final data that is sent to the browser.
*
* @var array{
* version: float,
* columns: list<string>,
* rows: list<array{
* 0: list<string>,
* 1: string,
* 2: string,
* }>,
* request_uri?: string,
* }
*/
protected $json = [
'version' => self::VERSION,
'columns' => [
'log',
'backtrace',
'type',
],
'rows' => [],
];
/**
* The header used to pass the data.
*
* @var string
*/
protected $header = 'X-ChromeLogger-Data';
/**
* Maps the log levels to the ChromeLogger types.
*
* @var array<string, string>
*/
protected $levels = [
'emergency' => 'error',
'alert' => 'error',
'critical' => 'error',
'error' => 'error',
'warning' => 'warn',
'notice' => 'warn',
'info' => 'info',
'debug' => 'info',
];
/**
* @param array{handles?: list<string>} $config
*/
public function __construct(array $config = [])
{
parent::__construct($config);
$this->json['request_uri'] = current_url();
}
/**
* Handles logging the message.
* If the handler returns false, then execution of handlers
* will stop. Any handlers that have not run, yet, will not
* be run.
*
* @param string $level
* @param string $message
*/
public function handle($level, $message): bool
{
$message = $this->format($message);
$backtrace = debug_backtrace(0, $this->backtraceLevel);
$backtrace = end($backtrace);
$backtraceMessage = 'unknown';
if (isset($backtrace['file'], $backtrace['line'])) {
$backtraceMessage = $backtrace['file'] . ':' . $backtrace['line'];
}
// Default to 'log' type.
$type = '';
if (array_key_exists($level, $this->levels)) {
$type = $this->levels[$level];
}
$this->json['rows'][] = [[$message], $backtraceMessage, $type];
$this->sendLogs();
return true;
}
/**
* Converts the object to display nicely in the Chrome Logger UI.
*
* @param object|string $object
*
* @return array<string, mixed>|string
*/
protected function format($object)
{
if (! is_object($object)) {
return $object;
}
// @todo Modify formatting of objects once we can view them in browser.
$objectArray = (array) $object;
$objectArray['___class_name'] = $object::class;
return $objectArray;
}
/**
* Attaches the header and the content to the passed in request object.
*
* @param-out ResponseInterface $response
*
* @return void
*/
public function sendLogs(?ResponseInterface &$response = null)
{
if (! $response instanceof ResponseInterface) {
$response = service('response', null, true);
}
$data = base64_encode(
mb_convert_encoding(json_encode($this->json), 'UTF-8', mb_list_encodings()),
);
$response->setHeader($this->header, $data);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Log/Handlers/ErrorlogHandler.php | system/Log/Handlers/ErrorlogHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Log\Handlers;
use CodeIgniter\Log\Exceptions\LogException;
/**
* Log handler that writes to PHP's `error_log()`
*
* @see \CodeIgniter\Log\Handlers\ErrorlogHandlerTest
*/
class ErrorlogHandler extends BaseHandler
{
/**
* Message is sent to PHP's system logger, using the Operating System's
* system logging mechanism or a file, depending on what the error_log
* configuration directive is set to.
*/
public const TYPE_OS = 0;
/**
* Message is sent directly to the SAPI logging handler.
*/
public const TYPE_SAPI = 4;
/**
* Says where the error should go. Currently supported are
* 0 (`TYPE_OS`) and 4 (`TYPE_SAPI`).
*
* @var 0|4
*/
protected $messageType = 0;
/**
* Constructor.
*
* @param array{handles?: list<string>, messageType?: int} $config
*/
public function __construct(array $config = [])
{
parent::__construct($config);
$messageType = $config['messageType'] ?? self::TYPE_OS;
if (! is_int($messageType) || ! in_array($messageType, [self::TYPE_OS, self::TYPE_SAPI], true)) {
throw LogException::forInvalidMessageType(print_r($messageType, true));
}
$this->messageType = $messageType;
}
/**
* Handles logging the message.
* If the handler returns false, then execution of handlers
* will stop. Any handlers that have not run, yet, will not
* be run.
*
* @param string $level
* @param string $message
*/
public function handle($level, $message): bool
{
$message = strtoupper($level) . ' --> ' . $message . "\n";
return $this->errorLog($message, $this->messageType);
}
/**
* Extracted call to `error_log()` in order to be tested.
*
* @param 0|4 $messageType
*
* @codeCoverageIgnore
*/
protected function errorLog(string $message, int $messageType): bool
{
return error_log($message, $messageType);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Log/Handlers/FileHandler.php | system/Log/Handlers/FileHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Log\Handlers;
use DateTime;
use Exception;
/**
* Log error messages to file system
*
* @see \CodeIgniter\Log\Handlers\FileHandlerTest
*/
class FileHandler extends BaseHandler
{
/**
* Folder to hold logs
*
* @var string
*/
protected $path;
/**
* Extension to use for log files
*
* @var string
*/
protected $fileExtension;
/**
* Permissions for new log files
*
* @var int
*/
protected $filePermissions;
/**
* @param array{handles?: list<string>, path?: string, fileExtension?: string, filePermissions?: int} $config
*/
public function __construct(array $config = [])
{
parent::__construct($config);
$defaults = ['path' => WRITEPATH . 'logs/', 'fileExtension' => 'log', 'filePermissions' => 0644];
$config = [...$defaults, ...$config];
$this->path = $config['path'] === '' ? $defaults['path'] : $config['path'];
$this->fileExtension = $config['fileExtension'] === ''
? $defaults['fileExtension']
: ltrim($config['fileExtension'], '.');
$this->filePermissions = $config['filePermissions'];
}
/**
* Handles logging the message.
* If the handler returns false, then execution of handlers
* will stop. Any handlers that have not run, yet, will not
* be run.
*
* @param string $level
* @param string $message
*
* @throws Exception
*/
public function handle($level, $message): bool
{
$filepath = $this->path . 'log-' . date('Y-m-d') . '.' . $this->fileExtension;
$msg = '';
$newfile = false;
if (! is_file($filepath)) {
$newfile = true;
// Only add protection to php files
if ($this->fileExtension === 'php') {
$msg .= "<?php defined('SYSTEMPATH') || exit('No direct script access allowed'); ?>\n\n";
}
}
if (! $fp = @fopen($filepath, 'ab')) {
return false;
}
// Instantiating DateTime with microseconds appended to initial date is needed for proper support of this format
if (str_contains($this->dateFormat, 'u')) {
$microtimeFull = microtime(true);
$microtimeShort = sprintf('%06d', ($microtimeFull - floor($microtimeFull)) * 1_000_000);
$date = new DateTime(date('Y-m-d H:i:s.' . $microtimeShort, (int) $microtimeFull));
$date = $date->format($this->dateFormat);
} else {
$date = date($this->dateFormat);
}
$msg .= strtoupper($level) . ' - ' . $date . ' --> ' . $message . "\n";
flock($fp, LOCK_EX);
$result = null;
for ($written = 0, $length = strlen($msg); $written < $length; $written += $result) {
if (($result = fwrite($fp, substr($msg, $written))) === false) {
// if we get this far, we'll never see this during unit testing
break; // @codeCoverageIgnore
}
}
flock($fp, LOCK_UN);
fclose($fp);
if ($newfile) {
chmod($filepath, $this->filePermissions);
}
return is_int($result);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Log/Handlers/BaseHandler.php | system/Log/Handlers/BaseHandler.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Log\Handlers;
/**
* Base class for logging
*/
abstract class BaseHandler implements HandlerInterface
{
/**
* Handles
*
* @var list<string>
*/
protected $handles;
/**
* Date format for logging
*
* @var string
*/
protected $dateFormat = 'Y-m-d H:i:s';
/**
* @param array{handles?: list<string>} $config
*/
public function __construct(array $config)
{
$this->handles = $config['handles'] ?? [];
}
/**
* Checks whether the Handler will handle logging items of this
* log Level.
*/
public function canHandle(string $level): bool
{
return in_array($level, $this->handles, true);
}
/**
* Stores the date format to use while logging messages.
*/
public function setDateFormat(string $format): HandlerInterface
{
$this->dateFormat = $format;
return $this;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/Log/Handlers/HandlerInterface.php | system/Log/Handlers/HandlerInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Log\Handlers;
/**
* Expected behavior for a Log handler
*/
interface HandlerInterface
{
/**
* Handles logging the message.
* If the handler returns false, then execution of handlers
* will stop. Any handlers that have not run, yet, will not
* be run.
*
* @param string $level
* @param string $message
*/
public function handle($level, $message): bool;
/**
* Checks whether the Handler will handle logging items of this
* log Level.
*/
public function canHandle(string $level): bool;
/**
* Sets the preferred date format to use when logging.
*
* @return HandlerInterface
*/
public function setDateFormat(string $format);
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/View/Cell.php | system/View/Cell.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\Cache\CacheInterface;
use CodeIgniter\Config\Factories;
use CodeIgniter\View\Cells\Cell as BaseCell;
use CodeIgniter\View\Exceptions\ViewException;
use ReflectionException;
use ReflectionMethod;
/**
* Class Cell
*
* A simple class that can call any other class that can be loaded,
* and echo out it's result. Intended for displaying small blocks of
* content within views that can be managed by other libraries and
* not require they are loaded within controller.
*
* Used with the helper function, it's use will look like:
*
* viewCell('\Some\Class::method', 'limit=5 sort=asc', 60, 'cache-name');
*
* Parameters are matched up with the callback method's arguments of the same name:
*
* class Class {
* function method($limit, $sort)
* }
*
* Alternatively, the params will be passed into the callback method as a simple array
* if matching params are not found.
*
* class Class {
* function method(array $params=null)
* }
*
* @see \CodeIgniter\View\CellTest
*/
class Cell
{
/**
* Instance of the current Cache Instance
*
* @var CacheInterface
*/
protected $cache;
/**
* Cell constructor.
*/
public function __construct(CacheInterface $cache)
{
$this->cache = $cache;
}
/**
* Render a cell, returning its body as a string.
*
* @param string $library Cell class and method name.
* @param array<string, string>|string|null $params Parameters to pass to the method.
* @param int $ttl Number of seconds to cache the cell.
* @param string|null $cacheName Cache item name.
*
* @throws ReflectionException
*/
public function render(string $library, $params = null, int $ttl = 0, ?string $cacheName = null): string
{
[$instance, $method] = $this->determineClass($library);
$class = is_object($instance)
? $instance::class
: null;
$params = $this->prepareParams($params);
// Is the output cached?
$cacheName ??= str_replace(['\\', '/'], '', $class) . $method . md5(serialize($params));
$output = $this->cache->get($cacheName);
if (is_string($output) && $output !== '') {
return $output;
}
if (method_exists($instance, 'initController')) {
$instance->initController(service('request'), service('response'), service('logger'));
}
if (! method_exists($instance, $method)) {
throw ViewException::forInvalidCellMethod($class, $method);
}
$output = $instance instanceof BaseCell
? $this->renderCell($instance, $method, $params)
: $this->renderSimpleClass($instance, $method, $params, $class);
// Can we cache it?
if ($ttl !== 0) {
$this->cache->save($cacheName, $output, $ttl);
}
return $output;
}
/**
* Parses the params attribute. If an array, returns untouched.
* If a string, it should be in the format "key1=value key2=value".
* It will be split and returned as an array.
*
* @param array<string, string>|float|string|null $params
*
* @return array<string, string>
*/
public function prepareParams($params)
{
if (
($params === null || $params === '' || $params === [])
|| (! is_string($params) && ! is_array($params))
) {
return [];
}
if (is_string($params)) {
$newParams = [];
$separator = ' ';
if (str_contains($params, ',')) {
$separator = ',';
}
$params = explode($separator, $params);
unset($separator);
foreach ($params as $p) {
if ($p !== '') {
[$key, $val] = explode('=', $p);
$newParams[trim($key)] = trim($val, ', ');
}
}
$params = $newParams;
unset($newParams);
}
if ($params === []) {
return [];
}
return $params;
}
/**
* Given the library string, attempts to determine the class and method
* to call.
*/
protected function determineClass(string $library): array
{
// We don't want to actually call static methods
// by default, so convert any double colons.
$library = str_replace('::', ':', $library);
// controlled cells might be called with just
// the class name, so add a default method
if (! str_contains($library, ':')) {
$library .= ':render';
}
[$class, $method] = explode(':', $library);
if ($class === '') {
throw ViewException::forNoCellClass();
}
// locate and return an instance of the cell
$object = Factories::cells($class, ['getShared' => false]);
if (! is_object($object)) {
throw ViewException::forInvalidCellClass($class);
}
if ($method === '') {
$method = 'index';
}
return [
$object,
$method,
];
}
/**
* Renders a cell that extends the BaseCell class.
*/
final protected function renderCell(BaseCell $instance, string $method, array $params): string
{
// Only allow public properties to be set, or protected/private
// properties that have a method to get them (get<Foo>Property())
$publicProperties = $instance->getPublicProperties();
$privateProperties = array_column($instance->getNonPublicProperties(), 'name');
$publicParams = array_intersect_key($params, $publicProperties);
foreach ($params as $key => $value) {
$getter = 'get' . ucfirst((string) $key) . 'Property';
if (in_array($key, $privateProperties, true) && method_exists($instance, $getter)) {
$publicParams[$key] = $value;
}
}
// Fill in any public properties that were passed in
// but only ones that are in the $pulibcProperties array.
$instance = $instance->fill($publicParams);
// If there are any protected/private properties, we need to
// send them to the mount() method.
if (method_exists($instance, 'mount')) {
// if any $params have keys that match the name of an argument in the
// mount method, pass those variables to the method.
$mountParams = $this->getMethodParams($instance, 'mount', $params);
$instance->mount(...$mountParams);
}
return $instance->{$method}();
}
/**
* Returns the values from $params that match the parameters
* for a method, in the order they are defined. This allows
* them to be passed directly into the method.
*/
private function getMethodParams(BaseCell $instance, string $method, array $params): array
{
$mountParams = [];
try {
$reflectionMethod = new ReflectionMethod($instance, $method);
$reflectionParams = $reflectionMethod->getParameters();
foreach ($reflectionParams as $reflectionParam) {
$paramName = $reflectionParam->getName();
if (array_key_exists($paramName, $params)) {
$mountParams[] = $params[$paramName];
}
}
} catch (ReflectionException) {
// do nothing
}
return $mountParams;
}
/**
* Renders the non-Cell class, passing in the string/array params.
*
* @todo Determine if this can be refactored to use $this-getMethodParams().
*
* @param object $instance
*/
final protected function renderSimpleClass($instance, string $method, array $params, string $class): string
{
// Try to match up the parameter list we were provided
// with the parameter name in the callback method.
$refMethod = new ReflectionMethod($instance, $method);
$paramCount = $refMethod->getNumberOfParameters();
$refParams = $refMethod->getParameters();
if ($paramCount === 0) {
if ($params !== []) {
throw ViewException::forMissingCellParameters($class, $method);
}
$output = $instance->{$method}();
} elseif (($paramCount === 1)
&& ((! array_key_exists($refParams[0]->name, $params))
|| (array_key_exists($refParams[0]->name, $params)
&& count($params) !== 1))
) {
$output = $instance->{$method}($params);
} else {
$fireArgs = [];
$methodParams = [];
foreach ($refParams as $arg) {
$methodParams[$arg->name] = true;
if (array_key_exists($arg->name, $params)) {
$fireArgs[$arg->name] = $params[$arg->name];
}
}
foreach (array_keys($params) as $key) {
if (! isset($methodParams[$key])) {
throw ViewException::forInvalidCellParameter($key);
}
}
$output = $instance->{$method}(...array_values($fireArgs));
}
return $output;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/View/ViewDecoratorTrait.php | system/View/ViewDecoratorTrait.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\View\Exceptions\ViewException;
use Config\View as ViewConfig;
trait ViewDecoratorTrait
{
/**
* Runs the generated output through any declared
* view decorators.
*/
protected function decorateOutput(string $html): string
{
$decorators = $this->config->decorators ?? config(ViewConfig::class)->decorators;
foreach ($decorators as $decorator) {
if (! is_subclass_of($decorator, ViewDecoratorInterface::class)) {
throw ViewException::forInvalidDecorator($decorator);
}
$html = $decorator::decorate($html);
}
return $html;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/View/Table.php | system/View/Table.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\Database\BaseResult;
/**
* HTML Table Generating Class
*
* Lets you create tables manually or from database result objects, or arrays.
*
* @see \CodeIgniter\View\TableTest
*/
class Table
{
/**
* Data for table rows
*
* @var list<array<string, string>>|list<list<array<string, string>>>
*/
public $rows = [];
/**
* Data for table heading
*
* @var array<int, mixed>
*/
public $heading = [];
/**
* Data for table footing
*
* @var array<int, mixed>
*/
public $footing = [];
/**
* Whether or not to automatically create the table header
*
* @var bool
*/
public $autoHeading = true;
/**
* Table caption
*
* @var string|null
*/
public $caption;
/**
* Table layout template
*
* @var array<string, string>
*/
public $template;
/**
* Newline setting
*
* @var string
*/
public $newline = "\n";
/**
* Contents of empty cells
*
* @var string
*/
public $emptyCells = '';
/**
* Callback for custom table layout
*
* @var callable|null
*/
public $function;
/**
* Order each inserted row by heading keys
*/
private bool $syncRowsWithHeading = false;
/**
* Set the template from the table config file if it exists
*
* @param array<string, string> $config (default: array())
*/
public function __construct($config = [])
{
// initialize config
foreach ($config as $key => $val) {
$this->template[$key] = $val;
}
}
/**
* Set the template
*
* @param array<string, string>|string $template
*
* @return bool
*/
public function setTemplate($template)
{
if (! is_array($template)) {
return false;
}
$this->template = $template;
return true;
}
/**
* Set the table heading
*
* Can be passed as an array or discreet params
*
* @return Table
*/
public function setHeading()
{
$this->heading = $this->_prepArgs(func_get_args());
return $this;
}
/**
* Set the table footing
*
* Can be passed as an array or discreet params
*
* @return Table
*/
public function setFooting()
{
$this->footing = $this->_prepArgs(func_get_args());
return $this;
}
/**
* Set columns. Takes a one-dimensional array as input and creates
* a multi-dimensional array with a depth equal to the number of
* columns. This allows a single array with many elements to be
* displayed in a table that has a fixed column count.
*
* @param list<string> $array
* @param int $columnLimit
*
* @return array<int, mixed>|false
*/
public function makeColumns($array = [], $columnLimit = 0)
{
if (! is_array($array) || $array === [] || ! is_int($columnLimit)) {
return false;
}
// Turn off the auto-heading feature since it's doubtful we
// will want headings from a one-dimensional array
$this->autoHeading = false;
$this->syncRowsWithHeading = false;
if ($columnLimit === 0) {
return $array;
}
$new = [];
do {
$temp = array_splice($array, 0, $columnLimit);
if (count($temp) < $columnLimit) {
for ($i = count($temp); $i < $columnLimit; $i++) {
$temp[] = ' ';
}
}
$new[] = $temp;
} while ($array !== []);
return $new;
}
/**
* Set "empty" cells
*
* @param string $value
*
* @return Table
*/
public function setEmpty($value)
{
$this->emptyCells = $value;
return $this;
}
/**
* Add a table row
*
* Can be passed as an array or discreet params
*
* @return Table
*/
public function addRow()
{
$tmpRow = $this->_prepArgs(func_get_args());
if ($this->syncRowsWithHeading && $this->heading !== []) {
// each key has an index
$keyIndex = array_flip(array_keys($this->heading));
// figure out which keys need to be added
$missingKeys = array_diff_key($keyIndex, $tmpRow);
// Remove all keys which don't exist in $keyIndex
$tmpRow = array_filter($tmpRow, static fn ($k): bool => array_key_exists($k, $keyIndex), ARRAY_FILTER_USE_KEY);
// add missing keys to row, but use $this->emptyCells
$tmpRow = array_merge($tmpRow, array_map(fn ($v): array => ['data' => $this->emptyCells], $missingKeys));
// order keys by $keyIndex values
uksort($tmpRow, static fn ($k1, $k2): int => $keyIndex[$k1] <=> $keyIndex[$k2]);
}
$this->rows[] = $tmpRow;
return $this;
}
/**
* Set to true if each row column should be synced by keys defined in heading.
*
* If a row has a key which does not exist in heading, it will be filtered out
* If a row does not have a key which exists in heading, the field will stay empty
*
* @return $this
*/
public function setSyncRowsWithHeading(bool $orderByKey)
{
$this->syncRowsWithHeading = $orderByKey;
return $this;
}
/**
* Prep Args
*
* Ensures a standard associative array format for all cell data
*
* @param array<int, mixed> $args
*
* @return array<string, array<string, mixed>>|list<array<string, mixed>>
*/
protected function _prepArgs(array $args)
{
// If there is no $args[0], skip this and treat as an associative array
// This can happen if there is only a single key, for example this is passed to table->generate
// array(array('foo'=>'bar'))
if (isset($args[0]) && count($args) === 1 && is_array($args[0])) {
$args = $args[0];
}
foreach ($args as $key => $val) {
if (! is_array($val)) {
$args[$key] = ['data' => $val];
}
}
return $args;
}
/**
* Add a table caption
*
* @param string $caption
*
* @return Table
*/
public function setCaption($caption)
{
$this->caption = $caption;
return $this;
}
/**
* Generate the table
*
* @param array<int, mixed>|BaseResult|null $tableData
*
* @return string
*/
public function generate($tableData = null)
{
// The table data can optionally be passed to this function
// either as a database result object or an array
if ($tableData !== null && $tableData !== []) {
if ($tableData instanceof BaseResult) {
$this->_setFromDBResult($tableData);
} elseif (is_array($tableData)) {
$this->_setFromArray($tableData);
}
}
// Is there anything to display? No? Smite them!
if ($this->heading === [] && $this->rows === []) {
return 'Undefined table data';
}
// Compile and validate the template date
$this->_compileTemplate();
// Validate a possibly existing custom cell manipulation function
if (isset($this->function) && ! is_callable($this->function)) {
$this->function = null;
}
// Build the table!
$out = $this->template['table_open'] . $this->newline;
// Add any caption here
if (isset($this->caption) && $this->caption !== '') {
$out .= '<caption>' . $this->caption . '</caption>' . $this->newline;
}
// Is there a table heading to display?
if ($this->heading !== []) {
$headerTag = null;
if (preg_match('/(<)(td|th)(?=\h|>)/i', $this->template['heading_cell_start'], $matches) === 1) {
$headerTag = $matches[0];
}
$out .= $this->template['thead_open'] . $this->newline . $this->template['heading_row_start'] . $this->newline;
foreach ($this->heading as $heading) {
$temp = $this->template['heading_cell_start'];
foreach ($heading as $key => $val) {
if ($key !== 'data' && $headerTag !== null) {
$temp = str_replace($headerTag, $headerTag . ' ' . $key . '="' . $val . '"', $temp);
}
}
$out .= $temp . ($heading['data'] ?? '') . $this->template['heading_cell_end'];
}
$out .= $this->template['heading_row_end'] . $this->newline . $this->template['thead_close'] . $this->newline;
}
// Build the table rows
if ($this->rows !== []) {
$out .= $this->template['tbody_open'] . $this->newline;
$i = 1;
foreach ($this->rows as $row) {
// We use modulus to alternate the row colors
$name = fmod($i++, 2) !== 0.0 ? '' : 'alt_';
$out .= $this->template['row_' . $name . 'start'] . $this->newline;
foreach ($row as $cell) {
$temp = $this->template['cell_' . $name . 'start'];
foreach ($cell as $key => $val) {
if ($key !== 'data') {
$temp = str_replace('<td', '<td ' . $key . '="' . $val . '"', $temp);
}
}
$cell = $cell['data'] ?? '';
$out .= $temp;
if ($cell === '') {
$out .= $this->emptyCells;
} elseif (isset($this->function)) {
$out .= ($this->function)($cell);
} else {
$out .= $cell;
}
$out .= $this->template['cell_' . $name . 'end'];
}
$out .= $this->template['row_' . $name . 'end'] . $this->newline;
}
$out .= $this->template['tbody_close'] . $this->newline;
}
// Any table footing to display?
if ($this->footing !== []) {
$footerTag = null;
if (preg_match('/(<)(td|th)(?=\h|>)/i', $this->template['footing_cell_start'], $matches)) {
$footerTag = $matches[0];
}
$out .= $this->template['tfoot_open'] . $this->newline . $this->template['footing_row_start'] . $this->newline;
foreach ($this->footing as $footing) {
$temp = $this->template['footing_cell_start'];
foreach ($footing as $key => $val) {
if ($key !== 'data' && $footerTag !== null) {
$temp = str_replace($footerTag, $footerTag . ' ' . $key . '="' . $val . '"', $temp);
}
}
$out .= $temp . ($footing['data'] ?? '') . $this->template['footing_cell_end'];
}
$out .= $this->template['footing_row_end'] . $this->newline . $this->template['tfoot_close'] . $this->newline;
}
// And finally, close off the table
$out .= $this->template['table_close'];
// Clear table class properties before generating the table
$this->clear();
return $out;
}
/**
* Clears the table arrays. Useful if multiple tables are being generated
*
* @return Table
*/
public function clear()
{
$this->rows = [];
$this->heading = [];
$this->footing = [];
$this->autoHeading = true;
$this->caption = null;
return $this;
}
/**
* Set table data from a database result object
*
* @param BaseResult $object Database result object
*
* @return void
*/
protected function _setFromDBResult($object)
{
// First generate the headings from the table column names
if ($this->autoHeading && $this->heading === []) {
$this->heading = $this->_prepArgs($object->getFieldNames());
}
foreach ($object->getResultArray() as $row) {
$this->rows[] = $this->_prepArgs($row);
}
}
/**
* Set table data from an array
*
* @param array<int, mixed> $data
*
* @return void
*/
protected function _setFromArray($data)
{
if ($this->autoHeading && $this->heading === []) {
$this->heading = $this->_prepArgs(array_shift($data));
}
foreach ($data as &$row) {
$this->addRow($row);
}
}
/**
* Compile Template
*
* @return void
*/
protected function _compileTemplate()
{
if ($this->template === null) {
$this->template = $this->_defaultTemplate();
return;
}
foreach ($this->_defaultTemplate() as $field => $template) {
if (! isset($this->template[$field])) {
$this->template[$field] = $template;
}
}
}
/**
* Default Template
*
* @return array<string, string>
*/
protected function _defaultTemplate()
{
return [
'table_open' => '<table border="0" cellpadding="4" cellspacing="0">',
'thead_open' => '<thead>',
'thead_close' => '</thead>',
'heading_row_start' => '<tr>',
'heading_row_end' => '</tr>',
'heading_cell_start' => '<th>',
'heading_cell_end' => '</th>',
'tfoot_open' => '<tfoot>',
'tfoot_close' => '</tfoot>',
'footing_row_start' => '<tr>',
'footing_row_end' => '</tr>',
'footing_cell_start' => '<td>',
'footing_cell_end' => '</td>',
'tbody_open' => '<tbody>',
'tbody_close' => '</tbody>',
'row_start' => '<tr>',
'row_end' => '</tr>',
'cell_start' => '<td>',
'cell_end' => '</td>',
'row_alt_start' => '<tr>',
'row_alt_end' => '</tr>',
'cell_alt_start' => '<td>',
'cell_alt_end' => '</td>',
'table_close' => '</table>',
];
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/View/Filters.php | system/View/Filters.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use NumberFormatter;
/**
* View filters
*/
class Filters
{
/**
* Returns $value as all lowercase with the first letter capitalized.
*/
public static function capitalize(string $value): string
{
return ucfirst(strtolower($value));
}
/**
* Formats a date into the given $format.
*
* @param int|string|null $value
*/
public static function date($value, string $format): string
{
if (is_string($value) && ! is_numeric($value)) {
$value = strtotime($value);
}
if ($value !== null) {
$value = (int) $value;
}
return date($format, $value);
}
/**
* Given a string or DateTime object, will return the date modified
* by the given value. Returns the value as a unix timestamp
*
* Example:
* my_date|date_modify(+1 day)
*
* @param int|string|null $value
*
* @return false|int
*/
public static function date_modify($value, string $adjustment)
{
$value = static::date($value, 'Y-m-d H:i:s');
return strtotime($adjustment, strtotime($value));
}
/**
* Returns the given default value if $value is empty or undefined.
*
* @param bool|float|int|list<string>|object|resource|string|null $value
*/
public static function default($value, string $default): string
{
return empty($value) ? $default : $value;
}
/**
* Escapes the given value with our `esc()` helper function.
*
* @param string $value
* @param 'attr'|'css'|'html'|'js'|'raw'|'url' $context
*/
public static function esc($value, string $context = 'html'): string
{
return esc($value, $context);
}
/**
* Returns an excerpt of the given string.
*/
public static function excerpt(string $value, string $phrase, int $radius = 100): string
{
helper('text');
return excerpt($value, $phrase, $radius);
}
/**
* Highlights a given phrase within the text using '<mark></mark>' tags.
*/
public static function highlight(string $value, string $phrase): string
{
helper('text');
return highlight_phrase($value, $phrase);
}
/**
* Highlights code samples with HTML/CSS.
*
* @param string $value
*/
public static function highlight_code($value): string
{
helper('text');
return highlight_code($value);
}
/**
* Limits the number of characters to $limit, and trails of with an ellipsis.
* Will break at word break so may be more or less than $limit.
*
* @param string $value
*/
public static function limit_chars($value, int $limit = 500): string
{
helper('text');
return character_limiter($value, $limit);
}
/**
* Limits the number of words to $limit, and trails of with an ellipsis.
*
* @param string $value
*/
public static function limit_words($value, int $limit = 100): string
{
helper('text');
return word_limiter($value, $limit);
}
/**
* Returns the $value displayed in a localized manner.
*
* @param float|int $value
*/
public static function local_number($value, string $type = 'decimal', int $precision = 4, ?string $locale = null): string
{
helper('number');
$types = [
'decimal' => NumberFormatter::DECIMAL,
'currency' => NumberFormatter::CURRENCY,
'percent' => NumberFormatter::PERCENT,
'scientific' => NumberFormatter::SCIENTIFIC,
'spellout' => NumberFormatter::SPELLOUT,
'ordinal' => NumberFormatter::ORDINAL,
'duration' => NumberFormatter::DURATION,
];
return format_number((float) $value, $precision, $locale, ['type' => $types[$type]]);
}
/**
* Returns the $value displayed as a currency string.
*
* @param float|int $value
* @param int $fraction
*/
public static function local_currency($value, string $currency, ?string $locale = null, $fraction = null): string
{
helper('number');
$fraction ??= 0;
$options = [
'type' => NumberFormatter::CURRENCY,
'currency' => $currency,
'fraction' => $fraction,
];
return format_number((float) $value, 2, $locale, $options);
}
/**
* Returns a string with all instances of newline character (\n)
* converted to an HTML <br> tag.
*/
public static function nl2br(string $value): string
{
$typography = service('typography');
return $typography->nl2brExceptPre($value);
}
/**
* Takes a body of text and uses the auto_typography() method to
* turn it into prettier, easier-to-read, prose.
*/
public static function prose(string $value): string
{
$typography = service('typography');
return $typography->autoTypography($value);
}
/**
* Rounds a given $value in one of 3 ways;
*
* - common Normal rounding
* - ceil always rounds up
* - floor always rounds down
*
* @param int|string $precision precision or type
*
* @return float|string
*/
public static function round(string $value, $precision = 2, string $type = 'common')
{
// In case that $precision is a type like `{ value1|round(ceil) }`
if (! is_numeric($precision)) {
$type = $precision;
$precision = 2;
} else {
$precision = (int) $precision;
}
return match ($type) {
'common' => round((float) $value, $precision),
'ceil' => ceil((float) $value),
'floor' => floor((float) $value),
// Still here, just return the value.
default => $value,
};
}
/**
* Returns a "title case" version of the string.
*/
public static function title(string $value): string
{
return ucwords(strtolower($value));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/View/Plugins.php | system/View/Plugins.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\HTTP\URI;
/**
* View plugins
*/
class Plugins
{
/**
* Wrap helper function to use as view plugin.
*
* @return string|URI
*/
public static function currentURL()
{
return current_url();
}
/**
* Wrap helper function to use as view plugin.
*
* @return string|URI
*/
public static function previousURL()
{
return previous_url();
}
/**
* Wrap helper function to use as view plugin.
*
* @param array{email?: string, title?: string, attributes?: array<string, string>|object|string} $params
*/
public static function mailto(array $params = []): string
{
$email = $params['email'] ?? '';
$title = $params['title'] ?? '';
$attrs = $params['attributes'] ?? '';
return mailto($email, $title, $attrs);
}
/**
* Wrap helper function to use as view plugin.
*
* @param array{email?: string, title?: string, attributes?: array<string, string>|object|string} $params
*/
public static function safeMailto(array $params = []): string
{
$email = $params['email'] ?? '';
$title = $params['title'] ?? '';
$attrs = $params['attributes'] ?? '';
return safe_mailto($email, $title, $attrs);
}
/**
* Wrap helper function to use as view plugin.
*
* @param array<int|string, string>|list<string> $params
*/
public static function lang(array $params = []): string
{
$line = array_shift($params);
return lang($line, $params);
}
/**
* Wrap helper function to use as view plugin.
*
* @param array{field?: string} $params
*/
public static function validationErrors(array $params = []): string
{
$validator = service('validation');
if ($params === []) {
return $validator->listErrors();
}
return $validator->showError($params['field']);
}
/**
* Wrap helper function to use as view plugin.
*
* @param list<string> $params
*
* @return false|string
*/
public static function route(array $params = [])
{
return route_to(...$params);
}
/**
* Wrap helper function to use as view plugin.
*
* @param list<string> $params
*/
public static function siteURL(array $params = []): string
{
return site_url(...$params);
}
/**
* Wrap csp_script_nonce() function to use as view plugin.
*/
public static function cspScriptNonce(): string
{
return csp_script_nonce();
}
/**
* Wrap csp_style_nonce() function to use as view plugin.
*/
public static function cspStyleNonce(): string
{
return csp_style_nonce();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/View/ViewDecoratorInterface.php | system/View/ViewDecoratorInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
/**
* View Decorators are simple classes that are given the
* chance to modify the output from the view() calls
* prior to it being cached.
*/
interface ViewDecoratorInterface
{
/**
* Takes $html and has a chance to alter it.
* MUST return the modified HTML.
*/
public static function decorate(string $html): string;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/View/RendererInterface.php | system/View/RendererInterface.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
/**
* Interface RendererInterface
*
* The interface used for displaying Views and/or theme files.
*/
interface RendererInterface
{
/**
* Builds the output based upon a file name and any
* data that has already been set.
*
* @param array<string, mixed>|null $options Reserved for 3rd-party uses since
* it might be needed to pass additional info
* to other template engines.
* @param bool $saveData Whether to save data for subsequent calls
*/
public function render(string $view, ?array $options = null, bool $saveData = false): string;
/**
* Builds the output based upon a string and any
* data that has already been set.
*
* @param string $view The view contents
* @param array<string, mixed>|null $options Reserved for 3rd-party uses since
* it might be needed to pass additional info
* to other template engines.
* @param bool $saveData Whether to save data for subsequent calls
*/
public function renderString(string $view, ?array $options = null, bool $saveData = false): string;
/**
* Sets several pieces of view data at once.
*
* @param array<string, mixed> $data
* @param 'attr'|'css'|'html'|'js'|'raw'|'url'|null $context The context to escape it for.
* If 'raw', no escaping will happen.
*
* @return RendererInterface
*/
public function setData(array $data = [], ?string $context = null);
/**
* Sets a single piece of view data.
*
* @param mixed $value
* @param 'attr'|'css'|'html'|'js'|'raw'|'url'|null $context The context to escape it for.
* If 'raw', no escaping will happen.
*
* @return RendererInterface
*/
public function setVar(string $name, $value = null, ?string $context = null);
/**
* Removes all of the view data from the system.
*
* @return RendererInterface
*/
public function resetData();
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/View/Parser.php | system/View/Parser.php | <?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\Autoloader\FileLocatorInterface;
use CodeIgniter\View\Exceptions\ViewException;
use Config\View as ViewConfig;
use ParseError;
use Psr\Log\LoggerInterface;
/**
* Class for parsing pseudo-vars
*
* @phpstan-type parser_callable (callable(mixed): mixed)
* @phpstan-type parser_callable_string (callable(mixed): mixed)&string
*
* @see \CodeIgniter\View\ParserTest
*/
class Parser extends View
{
use ViewDecoratorTrait;
/**
* Left delimiter character for pseudo vars
*
* @var string
*/
public $leftDelimiter = '{';
/**
* Right delimiter character for pseudo vars
*
* @var string
*/
public $rightDelimiter = '}';
/**
* Left delimiter characters for conditionals
*/
protected string $leftConditionalDelimiter = '{';
/**
* Right delimiter characters for conditionals
*/
protected string $rightConditionalDelimiter = '}';
/**
* Stores extracted noparse blocks.
*
* @var list<string>
*/
protected $noparseBlocks = [];
/**
* Stores any plugins registered at run-time.
*
* @var array<string, callable|list<string>|string>
* @phpstan-var array<string, array<parser_callable_string>|parser_callable_string|parser_callable>
*/
protected $plugins = [];
/**
* Stores the context for each data element
* when set by `setData` so the context is respected.
*
* @var array<string, mixed>
*/
protected $dataContexts = [];
/**
* Constructor
*
* @param FileLocatorInterface|null $loader
*/
public function __construct(
ViewConfig $config,
?string $viewPath = null,
$loader = null,
?bool $debug = null,
?LoggerInterface $logger = null,
) {
// Ensure user plugins override core plugins.
$this->plugins = $config->plugins;
parent::__construct($config, $viewPath, $loader, $debug, $logger);
}
/**
* Parse a template
*
* Parses pseudo-variables contained in the specified template view,
* replacing them with any data that has already been set.
*
* @param array<string, mixed>|null $options Reserved for 3rd-party uses since
* it might be needed to pass additional info
* to other template engines.
*/
public function render(string $view, ?array $options = null, ?bool $saveData = null): string
{
$start = microtime(true);
if ($saveData === null) {
$saveData = $this->config->saveData;
}
$fileExt = pathinfo($view, PATHINFO_EXTENSION);
$view = ($fileExt === '') ? $view . '.php' : $view; // allow Views as .html, .tpl, etc (from CI3)
$cacheName = $options['cache_name'] ?? str_replace('.php', '', $view);
// Was it cached?
if (isset($options['cache'])) {
$output = cache($cacheName);
if (is_string($output) && $output !== '') {
$this->logPerformance($start, microtime(true), $view);
return $output;
}
}
$file = $this->viewPath . $view;
if (! is_file($file)) {
$fileOrig = $file;
$file = $this->loader->locateFile($view, 'Views');
// locateFile() will return false if the file cannot be found.
if ($file === false) {
throw ViewException::forInvalidFile($fileOrig);
}
}
if ($this->tempData === null) {
$this->tempData = $this->data;
}
$template = file_get_contents($file);
$output = $this->parse($template, $this->tempData, $options);
$this->logPerformance($start, microtime(true), $view);
if ($saveData) {
$this->data = $this->tempData;
}
$output = $this->decorateOutput($output);
// Should we cache?
if (isset($options['cache'])) {
cache()->save($cacheName, $output, (int) $options['cache']);
}
$this->tempData = null;
return $output;
}
/**
* Parse a String
*
* Parses pseudo-variables contained in the specified string,
* replacing them with any data that has already been set.
*
* @param array<string, mixed>|null $options Reserved for 3rd-party uses since
* it might be needed to pass additional info
* to other template engines.
*/
public function renderString(string $template, ?array $options = null, ?bool $saveData = null): string
{
$start = microtime(true);
if ($saveData === null) {
$saveData = $this->config->saveData;
}
if ($this->tempData === null) {
$this->tempData = $this->data;
}
$output = $this->parse($template, $this->tempData, $options);
$this->logPerformance($start, microtime(true), $this->excerpt($template));
if ($saveData) {
$this->data = $this->tempData;
}
$this->tempData = null;
return $output;
}
/**
* Sets several pieces of view data at once.
* In the Parser, we need to store the context here
* so that the variable is correctly handled within the
* parsing itself, and contexts (including raw) are respected.
*
* @param array<string, mixed> $data
* @param 'attr'|'css'|'html'|'js'|'raw'|'url'|null $context The context to escape it for.
* If 'raw', no escaping will happen.
*/
public function setData(array $data = [], ?string $context = null): RendererInterface
{
if ($context !== null && $context !== '') {
foreach ($data as $key => &$value) {
if (is_array($value)) {
foreach ($value as &$obj) {
$obj = $this->objectToArray($obj);
}
} else {
$value = $this->objectToArray($value);
}
$this->dataContexts[$key] = $context;
}
}
$this->tempData ??= $this->data;
$this->tempData = array_merge($this->tempData, $data);
return $this;
}
/**
* Parse a template
*
* Parses pseudo-variables contained in the specified template,
* replacing them with the data in the second param
*
* @param array<string, mixed> $data
* @param array<string, mixed> $options Future options
*/
protected function parse(string $template, array $data = [], ?array $options = null): string
{
if ($template === '') {
return '';
}
// Remove any possible PHP tags since we don't support it
// and parseConditionals needs it clean anyway...
$template = str_replace(['<?', '?>'], ['<?', '?>'], $template);
$template = $this->parseComments($template);
$template = $this->extractNoparse($template);
// Replace any conditional code here so we don't have to parse as much
$template = $this->parseConditionals($template);
// Handle any plugins before normal data, so that
// it can potentially modify any template between its tags.
$template = $this->parsePlugins($template);
// Parse stack for each parse type (Single and Pairs)
$replaceSingleStack = [];
$replacePairsStack = [];
// loop over the data variables, saving regex and data
// for later replacement.
foreach ($data as $key => $val) {
$escape = true;
if (is_array($val)) {
$escape = false;
$replacePairsStack[] = [
'replace' => $this->parsePair($key, $val, $template),
'escape' => $escape,
];
} else {
$replaceSingleStack[] = [
'replace' => $this->parseSingle($key, (string) $val),
'escape' => $escape,
];
}
}
// Merge both stacks, pairs first + single stacks
// This allows for nested data with the same key to be replaced properly
$replace = array_merge($replacePairsStack, $replaceSingleStack);
// Loop over each replace array item which
// holds all the data to be replaced
foreach ($replace as $replaceItem) {
// Loop over the actual data to be replaced
foreach ($replaceItem['replace'] as $pattern => $content) {
$template = $this->replaceSingle($pattern, $content, $template, $replaceItem['escape']);
}
}
return $this->insertNoparse($template);
}
/**
* Parse a single key/value, extracting it
*
* @return array<string, string>
*/
protected function parseSingle(string $key, string $val): array
{
$pattern = '#' . $this->leftDelimiter . '!?\s*' . preg_quote($key, '#')
. '(?(?=\s*\|\s*)(\s*\|*\s*([|\w<>=\(\),:.\-\s\+\\\\/]+)*\s*))(\s*)!?'
. $this->rightDelimiter . '#ums';
return [$pattern => $val];
}
/**
* Parse a tag pair
*
* Parses tag pairs: {some_tag} string... {/some_tag}
*
* @param array<string, mixed> $data
*
* @return array<string, string>
*/
protected function parsePair(string $variable, array $data, string $template): array
{
// Holds the replacement patterns and contents
// that will be used within a preg_replace in parse()
$replace = [];
// Find all matches of space-flexible versions of {tag}{/tag} so we
// have something to loop over.
preg_match_all(
'#' . $this->leftDelimiter . '\s*' . preg_quote($variable, '#') . '\s*' . $this->rightDelimiter . '(.+?)' .
$this->leftDelimiter . '\s*/' . preg_quote($variable, '#') . '\s*' . $this->rightDelimiter . '#us',
$template,
$matches,
PREG_SET_ORDER,
);
/*
* Each match looks like:
*
* $match[0] {tag}...{/tag}
* $match[1] Contents inside the tag
*/
foreach ($matches as $match) {
// Loop over each piece of $data, replacing
// its contents so that we know what to replace in parse()
$str = ''; // holds the new contents for this tag pair.
foreach ($data as $row) {
// Objects that have a `toArray()` method should be
// converted with that method (i.e. Entities)
if (is_object($row) && method_exists($row, 'toArray')) {
$row = $row->toArray();
}
// Otherwise, cast as an array and it will grab public properties.
elseif (is_object($row)) {
$row = (array) $row;
}
$temp = [];
$pairs = [];
$out = $match[1];
foreach ($row as $key => $val) {
// For nested data, send us back through this method...
if (is_array($val)) {
$pair = $this->parsePair($key, $val, $match[1]);
if ($pair !== []) {
$pairs[array_keys($pair)[0]] = true;
$temp = array_merge($temp, $pair);
}
continue;
}
if (is_object($val)) {
$val = 'Class: ' . $val::class;
} elseif (is_resource($val)) {
$val = 'Resource';
}
$temp['#' . $this->leftDelimiter . '!?\s*' . preg_quote($key, '#') . '(?(?=\s*\|\s*)(\s*\|*\s*([|\w<>=\(\),:.\-\s\+\\\\/]+)*\s*))(\s*)!?' . $this->rightDelimiter . '#us'] = $val;
}
// Now replace our placeholders with the new content.
foreach ($temp as $pattern => $content) {
$out = $this->replaceSingle($pattern, $content, $out, ! isset($pairs[$pattern]));
}
$str .= $out;
}
$escapedMatch = preg_quote($match[0], '#');
$replace['#' . $escapedMatch . '#us'] = $str;
}
return $replace;
}
/**
* Removes any comments from the file. Comments are wrapped in {# #} symbols:
*
* {# This is a comment #}
*/
protected function parseComments(string $template): string
{
return preg_replace('/\{#.*?#\}/us', '', $template);
}
/**
* Extracts noparse blocks, inserting a hash in its place so that
* those blocks of the page are not touched by parsing.
*/
protected function extractNoparse(string $template): string
{
$pattern = '/\{\s*noparse\s*\}(.*?)\{\s*\/noparse\s*\}/ums';
/*
* $matches[][0] is the raw match
* $matches[][1] is the contents
*/
if (preg_match_all($pattern, $template, $matches, PREG_SET_ORDER) >= 1) {
foreach ($matches as $match) {
// Create a hash of the contents to insert in its place.
$hash = md5($match[1]);
$this->noparseBlocks[$hash] = $match[1];
$template = str_replace($match[0], "noparse_{$hash}", $template);
}
}
return $template;
}
/**
* Re-inserts the noparsed contents back into the template.
*/
public function insertNoparse(string $template): string
{
foreach ($this->noparseBlocks as $hash => $replace) {
$template = str_replace("noparse_{$hash}", $replace, $template);
unset($this->noparseBlocks[$hash]);
}
return $template;
}
/**
* Parses any conditionals in the code, removing blocks that don't
* pass so we don't try to parse it later.
*
* Valid conditionals:
* - if
* - elseif
* - else
*/
protected function parseConditionals(string $template): string
{
$leftDelimiter = preg_quote($this->leftConditionalDelimiter, '/');
$rightDelimiter = preg_quote($this->rightConditionalDelimiter, '/');
$pattern = '/'
. $leftDelimiter
. '\s*(if|elseif)\s*((?:\()?(.*?)(?:\))?)\s*'
. $rightDelimiter
. '/ums';
/*
* For each match:
* [0] = raw match `{if var}`
* [1] = conditional `if`
* [2] = condition `do === true`
* [3] = same as [2]
*/
preg_match_all($pattern, $template, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
// Build the string to replace the `if` statement with.
$condition = $match[2];
$statement = $match[1] === 'elseif' ? '<?php elseif (' . $condition . '): ?>' : '<?php if (' . $condition . '): ?>';
$template = str_replace($match[0], $statement, $template);
}
$template = preg_replace(
'/' . $leftDelimiter . '\s*else\s*' . $rightDelimiter . '/ums',
'<?php else: ?>',
$template,
);
$template = preg_replace(
'/' . $leftDelimiter . '\s*endif\s*' . $rightDelimiter . '/ums',
'<?php endif; ?>',
$template,
);
// Parse the PHP itself, or insert an error so they can debug
ob_start();
if ($this->tempData === null) {
$this->tempData = $this->data;
}
extract($this->tempData);
try {
eval('?>' . $template . '<?php ');
} catch (ParseError) {
ob_end_clean();
throw ViewException::forTagSyntaxError(str_replace(['?>', '<?php '], '', $template));
}
return ob_get_clean();
}
/**
* Over-ride the substitution field delimiters.
*
* @param string $leftDelimiter
* @param string $rightDelimiter
*/
public function setDelimiters($leftDelimiter = '{', $rightDelimiter = '}'): RendererInterface
{
$this->leftDelimiter = $leftDelimiter;
$this->rightDelimiter = $rightDelimiter;
return $this;
}
/**
* Over-ride the substitution conditional delimiters.
*
* @param string $leftDelimiter
* @param string $rightDelimiter
*/
public function setConditionalDelimiters($leftDelimiter = '{', $rightDelimiter = '}'): RendererInterface
{
$this->leftConditionalDelimiter = $leftDelimiter;
$this->rightConditionalDelimiter = $rightDelimiter;
return $this;
}
/**
* Handles replacing a pseudo-variable with the actual content. Will double-check
* for escaping brackets.
*
* @param array|string $pattern
* @param string $content
* @param string $template
*/
protected function replaceSingle($pattern, $content, $template, bool $escape = false): string
{
$content = (string) $content;
// Replace the content in the template
return preg_replace_callback($pattern, function ($matches) use ($content, $escape): string {
// Check for {! !} syntax to not escape this one.
if (
str_starts_with($matches[0], $this->leftDelimiter . '!')
&& substr($matches[0], -1 - strlen($this->rightDelimiter)) === '!' . $this->rightDelimiter
) {
$escape = false;
}
return $this->prepareReplacement($matches, $content, $escape);
}, (string) $template);
}
/**
* Callback used during parse() to apply any filters to the value.
*
* @param list<string> $matches
*/
protected function prepareReplacement(array $matches, string $replace, bool $escape = true): string
{
$orig = array_shift($matches);
// Our regex earlier will leave all chained values on a single line
// so we need to break them apart so we can apply them all.
$filters = (isset($matches[1]) && $matches[1] !== '') ? explode('|', $matches[1]) : [];
if ($escape && $filters === [] && ($context = $this->shouldAddEscaping($orig))) {
$filters[] = "esc({$context})";
}
return $this->applyFilters($replace, $filters);
}
/**
* Checks the placeholder the view provided to see if we need to provide any autoescaping.
*
* @return false|string
*/
public function shouldAddEscaping(string $key)
{
$escape = false;
$key = trim(str_replace(['{', '}'], '', $key));
// If the key has a context stored (from setData)
// we need to respect that.
if (array_key_exists($key, $this->dataContexts)) {
if ($this->dataContexts[$key] !== 'raw') {
return $this->dataContexts[$key];
}
}
// No pipes, then we know we need to escape
elseif (! str_contains($key, '|')) {
$escape = 'html';
}
// If there's a `noescape` then we're definitely false.
elseif (str_contains($key, 'noescape')) {
$escape = false;
}
// If no `esc` filter is found, then we'll need to add one.
elseif (preg_match('/\s+esc/u', $key) !== 1) {
$escape = 'html';
}
return $escape;
}
/**
* Given a set of filters, will apply each of the filters in turn
* to $replace, and return the modified string.
*
* @param list<string> $filters
*/
protected function applyFilters(string $replace, array $filters): string
{
// Determine the requested filters
foreach ($filters as $filter) {
// Grab any parameter we might need to send
preg_match('/\([\w<>=\/\\\,:.\-\s\+]+\)/u', $filter, $param);
// Remove the () and spaces to we have just the parameter left
$param = ($param !== []) ? trim($param[0], '() ') : null;
// Params can be separated by commas to allow multiple parameters for the filter
if ($param !== null && $param !== '') {
$param = explode(',', $param);
// Clean it up
foreach ($param as &$p) {
$p = trim($p, ' "');
}
} else {
$param = [];
}
// Get our filter name
$filter = $param !== [] ? trim(strtolower(substr($filter, 0, strpos($filter, '(')))) : trim($filter);
if (! array_key_exists($filter, $this->config->filters)) {
continue;
}
// Filter it....
// We can't know correct param types, so can't set `declare(strict_types=1)`.
$replace = $this->config->filters[$filter]($replace, ...$param);
}
return (string) $replace;
}
// Plugins
/**
* Scans the template for any parser plugins, and attempts to execute them.
* Plugins are delimited by {+ ... +}
*
* @return string
*/
protected function parsePlugins(string $template)
{
foreach ($this->plugins as $plugin => $callable) {
// Paired tags are enclosed in an array in the config array.
$isPair = is_array($callable);
$callable = $isPair ? array_shift($callable) : $callable;
// See https://regex101.com/r/BCBBKB/1
$pattern = $isPair
? '#\{\+\s*' . $plugin . '([\w=\-_:\+\s\(\)/"@.]*)?\s*\+\}(.+?)\{\+\s*/' . $plugin . '\s*\+\}#uims'
: '#\{\+\s*' . $plugin . '([\w=\-_:\+\s\(\)/"@.]*)?\s*\+\}#uims';
/**
* Match tag pairs
*
* Each match is an array:
* $matches[0] = entire matched string
* $matches[1] = all parameters string in opening tag
* $matches[2] = content between the tags to send to the plugin.
*/
if (preg_match_all($pattern, $template, $matches, PREG_SET_ORDER) < 1) {
continue;
}
foreach ($matches as $match) {
$params = [];
preg_match_all('/([\w-]+=\"[^"]+\")|([\w-]+=[^\"\s=]+)|(\"[^"]+\")|(\S+)/u', trim($match[1]), $matchesParams);
foreach ($matchesParams[0] as $item) {
$keyVal = explode('=', $item);
if (count($keyVal) === 2) {
$params[$keyVal[0]] = str_replace('"', '', $keyVal[1]);
} else {
$params[] = str_replace('"', '', $item);
}
}
$template = $isPair
? str_replace($match[0], $callable($match[2], $params), $template)
: str_replace($match[0], $callable($params), $template);
}
}
return $template;
}
/**
* Makes a new plugin available during the parsing of the template.
*
* @return $this
*/
public function addPlugin(string $alias, callable $callback, bool $isPair = false)
{
$this->plugins[$alias] = $isPair ? [$callback] : $callback;
return $this;
}
/**
* Removes a plugin from the available plugins.
*
* @return $this
*/
public function removePlugin(string $alias)
{
unset($this->plugins[$alias]);
return $this;
}
/**
* Converts an object to an array, respecting any
* toArray() methods on an object.
*
* @param array<string, mixed>|bool|float|int|object|string|null $value
*
* @return array<string, mixed>|bool|float|int|string|null
*/
protected function objectToArray($value)
{
// Objects that have a `toArray()` method should be
// converted with that method (i.e. Entities)
if (is_object($value) && method_exists($value, 'toArray')) {
$value = $value->toArray();
}
// Otherwise, cast as an array and it will grab public properties.
elseif (is_object($value)) {
$value = (array) $value;
}
return $value;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/View/View.php | system/View/View.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View;
use CodeIgniter\Autoloader\FileLocatorInterface;
use CodeIgniter\Debug\Toolbar\Collectors\Views;
use CodeIgniter\Exceptions\RuntimeException;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\View\Exceptions\ViewException;
use Config\Toolbar;
use Config\View as ViewConfig;
use Psr\Log\LoggerInterface;
/**
* Class View
*
* @see \CodeIgniter\View\ViewTest
*/
class View implements RendererInterface
{
use ViewDecoratorTrait;
/**
* Saved Data.
*
* @var array<string, mixed>
*/
protected $data = [];
/**
* Data for the variables that are available in the Views.
*
* @var array<string, mixed>|null
*/
protected $tempData;
/**
* The base directory to look in for our Views.
*
* @var string
*/
protected $viewPath;
/**
* Data for rendering including Caching and Debug Toolbar data.
*
* @var array<string, mixed>
*/
protected $renderVars = [];
/**
* Instance of FileLocator for when
* we need to attempt to find a view
* that's not in standard place.
*
* @var FileLocatorInterface
*/
protected $loader;
/**
* Logger instance.
*
* @var LoggerInterface
*/
protected $logger;
/**
* Should we store performance info?
*
* @var bool
*/
protected $debug = false;
/**
* Cache stats about our performance here,
* when CI_DEBUG = true
*
* @var list<array{start: float, end: float, view: string}>
*/
protected $performanceData = [];
/**
* @var ViewConfig
*/
protected $config;
/**
* Whether data should be saved between renders.
*
* @var bool
*/
protected $saveData;
/**
* Number of loaded views
*
* @var int
*/
protected $viewsCount = 0;
/**
* The name of the layout being used, if any.
* Set by the `extend` method used within views.
*
* @var string|null
*/
protected $layout;
/**
* Holds the sections and their data.
*
* @var array<string, list<string>>
*/
protected $sections = [];
/**
* The name of the current section being rendered,
* if any.
*
* @var list<string>
*/
protected $sectionStack = [];
public function __construct(
ViewConfig $config,
?string $viewPath = null,
?FileLocatorInterface $loader = null,
?bool $debug = null,
?LoggerInterface $logger = null,
) {
$this->config = $config;
$this->viewPath = rtrim($viewPath, '\\/ ') . DIRECTORY_SEPARATOR;
$this->loader = $loader ?? service('locator');
$this->logger = $logger ?? service('logger');
$this->debug = $debug ?? CI_DEBUG;
$this->saveData = (bool) $config->saveData;
}
/**
* Builds the output based upon a file name and any
* data that has already been set.
*
* Valid $options:
* - cache Number of seconds to cache for
* - cache_name Name to use for cache
*
* @param string $view File name of the view source
* @param array<string, mixed>|null $options Reserved for 3rd-party uses since
* it might be needed to pass additional info
* to other template engines.
* @param bool|null $saveData If true, saves data for subsequent calls,
* if false, cleans the data after displaying,
* if null, uses the config setting.
*/
public function render(string $view, ?array $options = null, ?bool $saveData = null): string
{
$this->renderVars['start'] = microtime(true);
// Store the results here so even if
// multiple views are called in a view, it won't
// clean it unless we mean it to.
$saveData ??= $this->saveData;
$fileExt = pathinfo($view, PATHINFO_EXTENSION);
// allow Views as .html, .tpl, etc (from CI3)
$this->renderVars['view'] = ($fileExt === '') ? $view . '.php' : $view;
$this->renderVars['options'] = $options ?? [];
// Was it cached?
if (isset($this->renderVars['options']['cache'])) {
$cacheName = $this->renderVars['options']['cache_name']
?? str_replace('.php', '', $this->renderVars['view']);
$cacheName = str_replace(['\\', '/'], '', $cacheName);
$this->renderVars['cacheName'] = $cacheName;
$output = cache($this->renderVars['cacheName']);
if (is_string($output) && $output !== '') {
$this->logPerformance(
$this->renderVars['start'],
microtime(true),
$this->renderVars['view'],
);
return $output;
}
}
$this->renderVars['file'] = $this->viewPath . $this->renderVars['view'];
if (! is_file($this->renderVars['file'])) {
$this->renderVars['file'] = $this->loader->locateFile(
$this->renderVars['view'],
'Views',
($fileExt === '') ? 'php' : $fileExt,
);
}
// locateFile() will return false if the file cannot be found.
if ($this->renderVars['file'] === false) {
throw ViewException::forInvalidFile($this->renderVars['view']);
}
// Make our view data available to the view.
$this->prepareTemplateData($saveData);
// Save current vars
$renderVars = $this->renderVars;
$output = (function (): string {
extract($this->tempData);
ob_start();
include $this->renderVars['file'];
return ob_get_clean() ?: '';
})();
// Get back current vars
$this->renderVars = $renderVars;
// When using layouts, the data has already been stored
// in $this->sections, and no other valid output
// is allowed in $output so we'll overwrite it.
if ($this->layout !== null && $this->sectionStack === []) {
$layoutView = $this->layout;
$this->layout = null;
// Save current vars
$renderVars = $this->renderVars;
$output = $this->render($layoutView, $options, $saveData);
// Get back current vars
$this->renderVars = $renderVars;
}
$output = $this->decorateOutput($output);
$this->logPerformance(
$this->renderVars['start'],
microtime(true),
$this->renderVars['view'],
);
// Check if DebugToolbar is enabled.
$filters = service('filters');
$requiredAfterFilters = $filters->getRequiredFilters('after')[0];
if (in_array('toolbar', $requiredAfterFilters, true)) {
$debugBarEnabled = true;
} else {
$afterFilters = $filters->getFiltersClass()['after'];
$debugBarEnabled = in_array(DebugToolbar::class, $afterFilters, true);
}
if (
$this->debug && $debugBarEnabled
&& (! isset($options['debug']) || $options['debug'] === true)
) {
$toolbarCollectors = config(Toolbar::class)->collectors;
if (in_array(Views::class, $toolbarCollectors, true)) {
// Clean up our path names to make them a little cleaner
$this->renderVars['file'] = clean_path($this->renderVars['file']);
$this->renderVars['file'] = ++$this->viewsCount . ' ' . $this->renderVars['file'];
$output = '<!-- DEBUG-VIEW START ' . $this->renderVars['file'] . ' -->' . PHP_EOL
. $output . PHP_EOL
. '<!-- DEBUG-VIEW ENDED ' . $this->renderVars['file'] . ' -->' . PHP_EOL;
}
}
// Should we cache?
if (isset($this->renderVars['options']['cache'])) {
cache()->save(
$this->renderVars['cacheName'],
$output,
(int) $this->renderVars['options']['cache'],
);
}
$this->tempData = null;
return $output;
}
/**
* Builds the output based upon a string and any
* data that has already been set.
* Cache does not apply, because there is no "key".
*
* @param string $view The view contents
* @param array<string, mixed>|null $options Reserved for 3rd-party uses since
* it might be needed to pass additional info
* to other template engines.
* @param bool|null $saveData If true, saves data for subsequent calls,
* if false, cleans the data after displaying,
* if null, uses the config setting.
*/
public function renderString(string $view, ?array $options = null, ?bool $saveData = null): string
{
$start = microtime(true);
$saveData ??= $this->saveData;
$this->prepareTemplateData($saveData);
$output = (function (string $view): string {
extract($this->tempData);
ob_start();
eval('?>' . $view);
return ob_get_clean() ?: '';
})($view);
$this->logPerformance($start, microtime(true), $this->excerpt($view));
$this->tempData = null;
return $output;
}
/**
* Extract first bit of a long string and add ellipsis
*/
public function excerpt(string $string, int $length = 20): string
{
return (mb_strlen($string) > $length) ? mb_substr($string, 0, $length - 3) . '...' : $string;
}
/**
* Sets several pieces of view data at once.
*
* @param 'attr'|'css'|'html'|'js'|'raw'|'url'|null $context The context to escape it for.
* If 'raw', no escaping will happen.
*/
public function setData(array $data = [], ?string $context = null): RendererInterface
{
if ($context !== null) {
$data = \esc($data, $context);
}
$this->tempData ??= $this->data;
$this->tempData = array_merge($this->tempData, $data);
return $this;
}
/**
* Sets a single piece of view data.
*
* @param mixed $value
* @param 'attr'|'css'|'html'|'js'|'raw'|'url'|null $context The context to escape it for.
* If 'raw', no escaping will happen.
*/
public function setVar(string $name, $value = null, ?string $context = null): RendererInterface
{
if ($context !== null) {
$value = esc($value, $context);
}
$this->tempData ??= $this->data;
$this->tempData[$name] = $value;
return $this;
}
/**
* Removes all of the view data from the system.
*/
public function resetData(): RendererInterface
{
$this->data = [];
return $this;
}
/**
* Returns the current data that will be displayed in the view.
*
* @return array<string, mixed>
*/
public function getData(): array
{
return $this->tempData ?? $this->data;
}
/**
* Specifies that the current view should extend an existing layout.
*
* @return void
*/
public function extend(string $layout)
{
$this->layout = $layout;
}
/**
* Starts holds content for a section within the layout.
*
* @param string $name Section name
*
* @return void
*/
public function section(string $name)
{
$this->sectionStack[] = $name;
ob_start();
}
/**
* Captures the last section
*
* @return void
*
* @throws RuntimeException
*/
public function endSection()
{
$contents = ob_get_clean();
if ($this->sectionStack === []) {
throw new RuntimeException('View themes, no current section.');
}
$section = array_pop($this->sectionStack);
// Ensure an array exists so we can store multiple entries for this.
if (! array_key_exists($section, $this->sections)) {
$this->sections[$section] = [];
}
$this->sections[$section][] = $contents;
}
/**
* Renders a section's contents.
*
* @param bool $saveData If true, saves data for subsequent calls,
* if false, cleans the data after displaying.
*/
public function renderSection(string $sectionName, bool $saveData = false): string
{
if (! isset($this->sections[$sectionName])) {
return '';
}
$output = '';
foreach ($this->sections[$sectionName] as $key => $contents) {
$output .= $contents;
if ($saveData === false) {
unset($this->sections[$sectionName][$key]);
}
}
return $output;
}
/**
* Used within layout views to include additional views.
*
* @param array<string, mixed>|null $options
* @param bool $saveData
*/
public function include(string $view, ?array $options = null, $saveData = true): string
{
return $this->render($view, $options, $saveData);
}
/**
* Returns the performance data that might have been collected
* during the execution. Used primarily in the Debug Toolbar.
*
* @return list<array{start: float, end: float, view: string}>
*/
public function getPerformanceData(): array
{
return $this->performanceData;
}
/**
* Logs performance data for rendering a view.
*
* @return void
*/
protected function logPerformance(float $start, float $end, string $view)
{
if ($this->debug) {
$this->performanceData[] = [
'start' => $start,
'end' => $end,
'view' => $view,
];
}
}
protected function prepareTemplateData(bool $saveData): void
{
$this->tempData ??= $this->data;
if ($saveData) {
$this->data = $this->tempData;
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/View/Exceptions/ViewException.php | system/View/Exceptions/ViewException.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View\Exceptions;
use CodeIgniter\Exceptions\FrameworkException;
class ViewException extends FrameworkException
{
/**
* @return static
*/
public static function forInvalidCellMethod(string $class, string $method)
{
return new static(lang('View.invalidCellMethod', ['class' => $class, 'method' => $method]));
}
/**
* @return static
*/
public static function forMissingCellParameters(string $class, string $method)
{
return new static(lang('View.missingCellParameters', ['class' => $class, 'method' => $method]));
}
/**
* @return static
*/
public static function forInvalidCellParameter(string $key)
{
return new static(lang('View.invalidCellParameter', [$key]));
}
/**
* @return static
*/
public static function forNoCellClass()
{
return new static(lang('View.noCellClass'));
}
/**
* @return static
*/
public static function forInvalidCellClass(?string $class = null)
{
return new static(lang('View.invalidCellClass', [$class]));
}
/**
* @return static
*/
public static function forTagSyntaxError(string $output)
{
return new static(lang('View.tagSyntaxError', [$output]));
}
/**
* @return static
*/
public static function forInvalidDecorator(string $className)
{
return new static(lang('View.invalidDecoratorClass', [$className]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/system/View/Cells/Cell.php | system/View/Cells/Cell.php | <?php
declare(strict_types=1);
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\View\Cells;
use CodeIgniter\Exceptions\LogicException;
use CodeIgniter\Traits\PropertiesTrait;
use ReflectionClass;
use Stringable;
/**
* Class Cell
*
* The base class that View Cells should extend.
* Provides extended features for managing/rendering
* a single cell's contents.
*
* @function mount()
*/
class Cell implements Stringable
{
use PropertiesTrait;
/**
* The name of the view to render.
* If empty, will be determined based
* on the cell class' name.
*/
protected string $view = '';
/**
* Responsible for converting the view into HTML.
* Expected to be overridden by the child class
* in many occasions, but not all.
*/
public function render(): string
{
if (! function_exists('decamelize')) {
helper('inflector');
}
return $this->view($this->view);
}
/**
* Sets the view to use when rendered.
*
* @return $this
*/
public function setView(string $view)
{
$this->view = $view;
return $this;
}
/**
* Actually renders the view, and returns the HTML.
* In order to provide access to public properties and methods
* from within the view, this method extracts $data into the
* current scope and captures the output buffer instead of
* relying on the view service.
*
* @throws LogicException
*/
final protected function view(?string $view, array $data = []): string
{
$properties = $this->getPublicProperties();
$properties = $this->includeComputedProperties($properties);
$properties = array_merge($properties, $data);
$view = (string) $view;
if ($view === '') {
$viewName = decamelize(class_basename(static::class));
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;
$possibleView1 = $directory . substr($viewName, 0, strrpos($viewName, '_cell')) . '.php';
$possibleView2 = $directory . $viewName . '.php';
}
if ($view !== '' && ! is_file($view)) {
$directory = dirname((new ReflectionClass($this))->getFileName()) . DIRECTORY_SEPARATOR;
$view = $directory . $view . '.php';
}
$candidateViews = array_filter(
[$view, $possibleView1 ?? '', $possibleView2 ?? ''],
static fn (string $path): bool => $path !== '' && is_file($path),
);
if ($candidateViews === []) {
throw new LogicException(sprintf(
'Cannot locate the view file for the "%s" cell.',
static::class,
));
}
$foundView = current($candidateViews);
return (function () use ($properties, $foundView): string {
extract($properties);
ob_start();
include $foundView;
return ob_get_clean();
})();
}
/**
* Provides capability to render on string casting.
*/
public function __toString(): string
{
return $this->render();
}
/**
* Allows the developer to define computed properties
* as methods with `get` prefixed to the protected/private property name.
*/
private function includeComputedProperties(array $properties): array
{
$reservedProperties = ['data', 'view'];
$privateProperties = $this->getNonPublicProperties();
foreach ($privateProperties as $property) {
$name = $property->getName();
// don't include any methods in the base class
if (in_array($name, $reservedProperties, true)) {
continue;
}
$computedMethod = 'get' . ucfirst($name) . 'Property';
if (method_exists($this, $computedMethod)) {
$properties[$name] = $this->{$computedMethod}();
}
}
return $properties;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Common.php | app/Common.php | <?php
/**
* The goal of this file is to allow developers a location
* where they can overwrite core procedural functions and
* replace them with their own. This file is loaded during
* the bootstrap process and is called during the framework's
* execution.
*
* This can be looked at as a `master helper` file that is
* loaded early on, and may also contain additional functions
* that you'd like to use throughout your entire application
*
* @see: https://codeigniter.com/user_guide/extending/common.html
*/
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Controllers/Runs.php | app/Controllers/Runs.php | <?php
/**
* Copyright (C) 2014, 2024 Richard Lobb
* The controller for managing posts to the 'runs' resource.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use Jobe\ResultObject;
use Jobe\JobException;
use Jobe\OverloadException;
use Jobe\RunSpecifier;
use Jobe\LanguageTask;
class Runs extends ResourceController
{
public function post()
{
// Extract the run object from the post data and validate.
try {
// Extract info from the POST data, raising JobException if bad.
$json = $this->request->getJSON();
$run = new RunSpecifier($json);
// Create the task.
$reqdTaskClass = "\\Jobe\\" . ucwords($run->language_id) . 'Task';
$this->task = new $reqdTaskClass($run->sourcefilename, $run->input, $run->parameters);
// The nested tries here are a bit ugly, but the point is that we want to
// to clean up the task with close() before handling the exception.
try {
$this->task->prepareExecutionEnvironment($run->sourcecode, $run->files);
log_message('debug', "runs_post: compiling job {$this->task->id}");
$this->task->compile();
if (empty($this->task->cmpinfo)) {
log_message('debug', "runs_post: executing job {$this->task->id}");
$this->task->execute();
}
} finally {
// Free user and delete task run directory unless it's a debug run.
$this->task->close(!$run->debug);
}
// Success!
log_message('debug', "runs_post: returning 200 OK for task {$this->task->id}");
return $this->respond($this->task->resultObject(), 200);
// Report any errors.
} catch (JobException $e) {
$message = $e->getMessage();
log_message('error', "runs_post: $message");
return $this->respond($message, $e->getHttpStatusCode());
} catch (OverloadException $e) {
log_message('error', 'runs_post: overload exception occurred');
$resultobject = new ResultObject(0, LanguageTask::RESULT_SERVER_OVERLOAD);
return $this->respond($resultobject, 200);
} catch (\Throwable $e) {
$message = 'Server exception (' . $e->getMessage() . ')';
log_message('error', "runs_post: $message");
return $this->respond($message, 500);
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Controllers/Languages.php | app/Controllers/Languages.php | <?php
/**
* Copyright (C) 2014, 2024 Richard Lobb
* The controller for managing the index request on the Languages resource.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\LanguagesModel;
class Languages extends ResourceController
{
use ResponseTrait;
public function get()
{
$data = LanguagesModel::findAll();
return $this->respond($data);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Controllers/BaseController.php | app/Controllers/BaseController.php | <?php
namespace App\Controllers;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\IncomingRequest;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
/**
* Class BaseController
*
* BaseController provides a convenient place for loading components
* and performing functions that are needed by all your controllers.
* Extend this class in any new controllers:
* class Home extends BaseController
*
* For security be sure to declare any new methods as protected or private.
*/
abstract class BaseController extends Controller
{
/**
* Instance of the main Request object.
*
* @var CLIRequest|IncomingRequest
*/
protected $request;
/**
* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
*
* @var list<string>
*/
protected $helpers = [];
/**
* Be sure to declare properties for any property fetch you initialized.
* The creation of dynamic property is deprecated in PHP 8.2.
*/
// protected $session;
/**
* @return void
*/
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
// Do Not Edit This Line
parent::initController($request, $response, $logger);
// Preload any models, libraries, etc, here.
// E.g.: $this->session = service('session');
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Controllers/Files.php | app/Controllers/Files.php | <?php
/**
* Copyright (C) 2014, 2024 Richard Lobb
* The controller for managing PUTs and HEADs to the 'files' resource.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use Jobe\ResultObject;
use Jobe\JobException;
use Jobe\FileCache;
class Files extends ResourceController
{
// Put (i.e. create or update) a file
public function put($fileId = false)
{
log_message('debug', "Put file called with fileId $fileId");
if ($fileId === false) {
return $this->respond('No file id in URL', 400);
}
$json = $this->request->getJSON();
if (!$json || !isset($json->file_contents)) {
return $this->respond('put: missing file_contents parameter', 400);
}
$contents = base64_decode($json->file_contents, true);
if ($contents === false) {
return $this->respond("put: contents of file $fileId are not valid base-64", 400);
}
if (FileCache::filePutContents($fileId, $contents) === false) {
return $this->respond("put: failed to write file $fileId to cache", 500);
}
$len = strlen($contents);
log_message('debug', "Put file $fileId, size $len");
return $this->respond(null, 204);
}
// Check file
public function head($fileId)
{
if (!$fileId) {
return $this->respond('head: missing file ID parameter in URL', 400);
} elseif (FileCache::fileExists($fileId)) {
log_message('debug', "head: file $fileId exists");
return $this->respond(null, 204);
} else {
log_message('debug', "head: file $fileId not found");
return $this->respond(null, 404);
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Helpers/MY_cors_helper.php | app/Helpers/MY_cors_helper.php | <?php
/**
* Add the CORS headers to the given response and return it, unless it already has a
* an Access-Control-Allow-Origin header, in which case return it unchanged.
* @param $response The response object to be updated.
* @return The updated response object.
*/
use CodeIgniter\HTTP\Response;
function addCorsHeaders(Response $response)
{
if (! $response->hasHeader('Access-Control-Allow-Origin')) {
$response = $response->setHeader('Access-Control-Allow-Origin', '*');
$response = $response->setHeader('Access-Control-Allow-Headers', 'X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method');
$response = $response->setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, HEAD, DELETE');
}
return $response;
} | php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/NodejsTask.php | app/Libraries/NodejsTask.php | <?php
/* ==============================================================
*
* Node-js
*
* ==============================================================
*
* @copyright 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
class NodejsTask extends LanguageTask
{
public function __construct($filename, $input, $params)
{
parent::__construct($filename, $input, $params);
$this->default_params['interpreterargs'] = array('--use_strict');
}
public static function getVersionCommand()
{
return array('nodejs --version', '/v([0-9._]*)/');
}
public function compile()
{
$this->executableFileName = $this->sourceFileName;
if (strpos('.js', $this->executableFileName) != strlen($this->executableFileName) - 3) {
$this->executableFileName .= '.js';
}
if (!copy($this->sourceFileName, $this->executableFileName)) {
throw new exception("Node_Task: couldn't copy source file");
}
}
// A default name forjs programs
public function defaultFileName($sourcecode)
{
return 'prog.js';
}
public function getExecutablePath()
{
return '/usr/bin/nodejs';
}
public function getTargetFile()
{
return $this->sourceFileName;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/PhpTask.php | app/Libraries/PhpTask.php | <?php
/* ==============================================================
*
* PHP5
*
* ==============================================================
*
* @copyright 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
class PhpTask extends LanguageTask
{
public function __construct($filename, $input, $params)
{
parent::__construct($filename, $input, $params);
$this->default_params['interpreterargs'] = ['--no-php-ini'];
$this->default_params['memorylimit'] = 400; // MB (Greedy PHP)
}
public static function getVersionCommand()
{
return array('php --version', '/PHP ([0-9._]*)/');
}
public function compile()
{
$outputLines = array();
$returnVar = 0;
list($output, $compileErrs) = $this->runInSandbox("/usr/bin/php -l {$this->sourceFileName}");
if (empty($compileErrs)) {
$this->cmpinfo = '';
$this->executableFileName = $this->sourceFileName;
} else {
if ($output) {
$this->cmpinfo = $output . "\n" . $compileErrs;
} else {
$this->cmpinfo = $compileErrs;
}
}
}
// A default name for PHP programs
public function defaultFileName($sourcecode)
{
return 'prog.php';
}
public function getExecutablePath()
{
return '/usr/bin/php';
}
public function getTargetFile()
{
return $this->sourceFileName;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/JavaTask.php | app/Libraries/JavaTask.php | <?php
/* ==============================================================
*
* Java
*
* ==============================================================
*
* @copyright 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
class JavaTask extends LanguageTask
{
public string $mainClassName;
public function __construct($filename, $input, $params)
{
$params['memorylimit'] = 0; // Disregard memory limit - let JVM manage memory
$this->default_params['numprocs'] = 256; // Java 8 wants lots of processes
$this->default_params['interpreterargs'] = array(
"-Xrs", // reduces usage signals by java, because that generates debug
// output when program is terminated on timelimit exceeded.
"-Xss8m",
"-Xmx200m"
);
$this->default_params['main_class'] = null;
// Extra global Java arguments
if (config('Jobe')->java_extraflags != '') {
array_push($this->default_params['interpreterargs'], config('Jobe')->java_extraflags);
}
if (isset($params['numprocs']) && $params['numprocs'] < 256) {
$params['numprocs'] = 256; // Minimum for Java 8 JVM
}
parent::__construct($filename, $input, $params);
}
public function prepareExecutionEnvironment($sourceCode, $fileList)
{
parent::prepareExecutionEnvironment($sourceCode, $fileList);
// Superclass calls subclasses to get filename if it's
// not provided, so $this->sourceFileName should now be set correctly.
$extStart = strpos($this->sourceFileName, '.'); // Start of extension
$this->mainClassName = substr($this->sourceFileName, 0, $extStart);
}
public static function getVersionCommand()
{
return array('java -version', '/version "?([0-9._]*)/');
}
public function compile()
{
// Extra global Javac arguments
$extra_javacflags = config('Jobe')->javac_extraflags;
$prog = file_get_contents($this->sourceFileName);
$compileArgs = $this->getParam('compileargs');
$cmd = '/usr/bin/javac ' . $extra_javacflags . ' ' . implode(' ', $compileArgs) . " {$this->sourceFileName}";
list($output, $this->cmpinfo) = $this->runInSandbox($cmd);
if (empty($this->cmpinfo)) {
$this->executableFileName = $this->sourceFileName;
}
}
// A default name for Java programs. [Called only if API-call does
// not provide a filename. As a side effect, also set the mainClassName.
public function defaultFileName($sourcecode)
{
$main = $this->getMainClass($sourcecode);
if ($main === false) {
$this->cmpinfo .= "WARNING: can't determine main class, so source file has been named 'prog.java', " .
"which probably won't compile.";
return 'prog.java'; // This will probably fail
} else {
return $main.'.java';
}
}
public function getExecutablePath()
{
return '/usr/bin/java';
}
public function getTargetFile()
{
return $this->getParam('main_class') ?? $this->mainClassName;
}
// Return the name of the main class in the given prog, or FALSE if no
// such class found. Uses a regular expression to find a public class with
// a public static void main method.
// Not totally safe as it doesn't parse the file, e.g. would be fooled
// by a commented-out main class with a different name.
private function getMainClass($prog)
{
$p = '/(^|\W)public\s+class\s+(\w+)[^{]*\{.*?(public\s+static|static\s+public)\s+void\s+main\s*\(\s*String/ms';
if (preg_match_all($p, $prog, $matches) !== 1) {
return false;
} else {
return $matches[2][0];
}
}
// Get rid of the tab characters at the start of indented lines in
// traceback output.
public function filteredStderr()
{
return str_replace("\n\t", "\n ", $this->stderr);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/PascalTask.php | app/Libraries/PascalTask.php | <?php
/* ==============================================================
*
* Pascal
*
* ==============================================================
*
* @copyright 2015 Fedor Lyanguzov, based on 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
class PascalTask extends LanguageTask
{
public function __construct($filename, $input, $params)
{
parent::__construct($filename, $input, $params);
$this->default_params['compileargs'] = array(
'-vew', // [v]erbose, [e]rrors, [w]arnings
'-Se'); // stop on first error
}
public static function getVersionCommand()
{
return array('fpc -iV', '/([0-9._]*)/');
}
public function compile()
{
$src = basename($this->sourceFileName);
$errorFileName = "$src.err";
$execFileName = "$src.exe";
$compileargs = $this->getParam('compileargs');
$cmd = "fpc " . implode(' ', $compileargs) . " -Fe$errorFileName -o$execFileName $src";
list($output, $stderr) = $this->runInSandbox($cmd);
if (!file_exists($execFileName)) {
$this->cmpinfo = file_get_contents($errorFileName);
} else {
$this->cmpinfo = '';
$this->executableFileName = $execFileName;
}
}
// A default name for Pascal programs
public function defaultFileName($sourcecode)
{
return 'prog.pas';
}
// The executable is the output from the compilation
public function getExecutablePath()
{
return "./" . $this->executableFileName;
}
public function getTargetFile()
{
return '';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/CTask.php | app/Libraries/CTask.php | <?php
/* ==============================================================
*
* C
*
* ==============================================================
*
* @copyright 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
class CTask extends LanguageTask
{
public function __construct($filename, $input, $params)
{
parent::__construct($filename, $input, $params);
$this->default_params['compileargs'] = array(
'-Wall',
'-Werror',
'-std=c99',
'-x c');
}
public static function getVersionCommand()
{
return array('gcc --version', '/gcc \(.*\) ([0-9.]*)/');
}
public function compile()
{
$src = basename($this->sourceFileName);
$this->executableFileName = $execFileName = "$src.exe";
$compileargs = $this->getParam('compileargs');
$linkargs = $this->getParam('linkargs');
$cmd = "gcc " . implode(' ', $compileargs) . " -o $execFileName $src " . implode(' ', $linkargs);
list($output, $this->cmpinfo) = $this->runInSandbox($cmd);
}
// A default name for C programs
public function defaultFileName($sourcecode)
{
return 'prog.c';
}
// The executable is the output from the compilation
public function getExecutablePath()
{
return "./" . $this->executableFileName;
}
public function getTargetFile()
{
return '';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/ResultObject.php | app/Libraries/ResultObject.php | <?php
/* ==============================================================
*
* This file defines the ResultObject class, which is the type of
* response from a job submission (but returned as a JSON object).
*
* ==============================================================
*
* @copyright 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
class ResultObject
{
public ?string $run_id;
public int $outcome;
public string $cmpinfo;
public string $stdout;
public string $stderr;
public function __construct(
$run_id,
$outcome,
$cmpinfo = '',
$stdout = '',
$stderr = ''
) {
$this->run_id = $run_id; // A unique identifying string
$this->outcome = $outcome; // Outcome of this job
$this->cmpinfo = $this->clean($cmpinfo);
$this->stdout = $this->clean($stdout);
$this->stderr = $this->clean($stderr);
}
protected static function clean(&$s)
{
// If the given parameter string is valid utf-8, it is returned
// as is. Otherise, the return value is a copy of $s sanitised by
// replacing all control chars except newlines, tabs and returns with hex
// equivalents. Implemented here because non-utf8 output causes the
// json-encoding of the result to fail.
if (mb_check_encoding($s, 'UTF-8')) {
return $s;
} else {
$new_s = ''; // Output string
$n = strlen($s);
for ($i = 0; $i < $n; $i++) {
$c = $s[$i];
if (($c != "\n" && $c != "\r" && $c != "\t" && $c < " ") || $c > "\x7E") {
$c = '\\x' . sprintf("%02x", ord($c));
}
$new_s .= $c;
}
return $new_s;
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/LanguageTask.php | app/Libraries/LanguageTask.php | <?php
/* ==============================================================
*
* This file defines the abstract LanguageTask class, a subclass of which
* must be defined for each implemented language.
*
* ==============================================================
*
* @copyright 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
define('ACTIVE_USERS', 1); // The key for the shared memory active users array
abstract class LanguageTask
{
// Symbolic constants as per ideone API
const RESULT_COMPILATION_ERROR = 11;
const RESULT_RUNTIME_ERROR = 12;
const RESULT_TIME_LIMIT = 13;
const RESULT_SUCCESS = 15;
const RESULT_MEMORY_LIMIT = 17;
const RESULT_ILLEGAL_SYSCALL = 19;
const RESULT_INTERNAL_ERR = 20;
const RESULT_SERVER_OVERLOAD = 21;
const SEM_KEY_FILE_PATH = APPPATH . '/../public/index.php';
const PROJECT_KEY = 'j'; // For ftok function. Irrelevant (?)
// Global default parameter values. Can be overridden by subclasses,
// and then further overridden by the individual run requests.
public $default_params = [
'disklimit' => 20, // MB (for normal files)
'streamsize' => 2, // MB (for stdout/stderr)
'cputime' => 5, // secs
'memorylimit' => 400, // MB
'numprocs' => 30,
'compileargs' => array(),
'linkargs' => array(),
'interpreterargs' => array(),
'runargs' => array()
];
// Global minima settings for runguard sandbox when compiling.
// These override the default and task specific settings when a task
// is compiling in the sense that the parameter value used cannot be
// less than the one specified here.
public $min_params_compile = array(
'disklimit' => 20, // MB
'cputime' => 2, // secs
'memorylimit' => 500, // MB
'numprocs' => 5 // processes
);
public string $id; // The task id - use the workdir basename
public string $input; // Stdin for this task
public string $sourceFileName; // The name to give the source file
public string $executableFileName; // The name of the compiled (if necessary) executable
public array $params; // Request parameters
public ?int $userId = null; // The user id (number counting from 0).
public ?string $user; // The corresponding user name (e.g. jobe01).
public string $cmpinfo = ''; // Output from compilation
public float $time = 0; // Execution time (secs)
public int $memory = 0; // Memory used (MB)
public int $signal = 0;
public string $stdout = ''; // Output from execution
public string $stderr = '';
public int $result = LanguageTask::RESULT_INTERNAL_ERR; // Should get overwritten
public ?string $workdir = ''; // The temporary working directory created in constructor
// ************************************************
// MAIN METHODS THAT HANDLE THE FLOW OF ONE JOB
// ************************************************
public function __construct($filename, $input, $params)
{
$this->input = $input;
$this->sourceFileName = $filename;
$this->params = $params;
$this->cmpinfo = ''; // Optimism (always look on the bright side of life).
}
// Grab any resources that will be needed to run the task. The contract
// is that if prepareExecutionEnvironment has been called, then
// the close method will be called before the request using this object
// is finished.
//
// For all languages it is necessary to store the source code in a
// temporary file. A temporary directory is made to hold the source code.
//
// WARNING: the /home/jobe/runs directory (below) is generated by the installer.
// If you change that directory for some reason, make sure the directory
// exists, is owned by jobe, with group www-data (or whatever your web
// server user is) and has access rights of 771. If it's readable by
// any of the jobe<n> users, running programs will be able
// to hoover up other students' submissions.
// HACK ALERT: as a special case for testing, if the source code is the
// string "!** TESTING OVERLOAD EXCEPTION **!", an OverloadException is
// thrown.
public function prepareExecutionEnvironment($sourceCode, $fileList)
{
// Create the temporary directory that will be used.
$this->workdir = tempnam("/home/jobe/runs", "jobe_");
if (!unlink($this->workdir) || !mkdir($this->workdir)) {
log_message('error', 'LanguageTask constructor: error making temp directory');
throw new Exception("LanguageTask: error making temp directory (race error?)");
}
chdir($this->workdir);
$this->id = basename($this->workdir);
// Save the source there.
if (empty($this->sourceFileName)) {
$this->sourceFileName = $this->defaultFileName($sourceCode);
}
file_put_contents($this->workdir . '/' . $this->sourceFileName, $sourceCode);
$this->loadFiles($fileList);
// Allocate one of the Jobe users (unless it's the special overload exception test).
if ($sourceCode == "!** TESTING OVERLOAD EXCEPTION **!") {
throw new OverloadException();
}
$this->userId = $this->getFreeUser();
$this->user = sprintf("jobe%02d", $this->userId);
// Give the user RW access.
exec("setfacl -m u:{$this->user}:rwX {$this->workdir}");
}
// Load the specified files into the working directory.
// The file list is an array of (fileId, filename) pairs.
// Throws an exception if any are not present.
public function loadFiles($fileList)
{
foreach ($fileList as $file) {
$fileId = $file[0];
$filename = $file[1];
if (FileCache::loadFileToWorkspace($fileId, $filename, $this->workdir) === false) {
throw new JobException(
'One or more of the specified files is missing/unavailable',
404
);
}
}
}
// Compile the current source file in the current directory, saving
// the compiled output in a file $this->executableFileName.
// Sets $this->cmpinfo accordingly.
abstract public function compile();
// Execute this task, which must already have been compiled if necessary
public function execute()
{
try {
$cmd = implode(' ', $this->getRunCommand());
list($this->stdout, $this->stderr) = $this->runInSandbox($cmd, false, $this->input);
$this->stderr = $this->filteredStderr();
$this->diagnoseResult(); // Analyse output and set result
} catch (OverloadException $e) {
$this->result = LanguageTask::RESULT_SERVER_OVERLOAD;
$this->stderr = $e->getMessage();
} catch (Exception $e) {
$this->result = LanguageTask::RESULT_INTERNAL_ERR;
$this->stderr = $e->getMessage();
}
}
// Called to clean up task when done
public function close($deleteFiles = true)
{
if ($this->userId !== null) {
exec("sudo /usr/bin/pkill -9 -u {$this->user}"); // Kill any remaining processes
$this->removeTemporaryFiles($this->user);
$this->freeUser($this->userId);
$this->userId = null;
$this->user = null;
}
if ($deleteFiles && $this->workdir) {
$dir = $this->workdir;
exec("sudo rm -R $dir");
$this->workdir = null;
}
}
// ************************************************
// METHODS TO ALLOCATE AND FREE ONE JOBE USER
// ************************************************
// Find a currently unused jobe user account.
// Uses a shared memory segment containing one byte (used as a 'busy'
// boolean) for each of the possible user accounts.
// If no free accounts exist at present, the function sleeps for a
// second then retries, up to a maximum of MAX_RETRIES retries.
// Throws OverloadException if a free user cannot be found, otherwise
// returns an integer in the range 0 to jobe_max_users - 1 inclusive.
private function getFreeUser()
{
$numUsers = config('Jobe')->jobe_max_users;
$jobe_wait_timeout = config('Jobe')->jobe_wait_timeout;
$key = ftok(LanguageTask::SEM_KEY_FILE_PATH, LanguageTask::PROJECT_KEY);
$sem = sem_get($key);
$user = -1;
$retries = 0;
while ($user == -1) { // Loop until we have a user (or an OverloadException is thrown)
$gotIt = sem_acquire($sem);
if ($key === -1 || $sem === false || $gotIt === false) {
throw new JobException("Semaphore code failed in getFreeUser", 500);
}
// Change default permission to 600 (read/write only by owner)
// 10000 is the default shm size
$shm = shm_attach($key, 10000, 0600);
if (!shm_has_var($shm, ACTIVE_USERS)) {
// First time since boot -- initialise active list
$active = array();
for ($i = 0; $i < $numUsers; $i++) {
$active[$i] = false;
}
shm_put_var($shm, ACTIVE_USERS, $active);
}
$active = shm_get_var($shm, ACTIVE_USERS);
for ($user = 0; $user < $numUsers; $user++) {
if (!$active[$user]) {
$active[$user] = true;
shm_put_var($shm, ACTIVE_USERS, $active);
break;
}
}
shm_detach($shm);
sem_release($sem);
if ($user == $numUsers) {
$user = -1;
$retries += 1;
if ($retries <= $jobe_wait_timeout) {
sleep(1);
} else {
throw new OverloadException();
}
}
}
return $user;
}
// Mark the given user number (0 to jobe_max_users - 1) as free.
private function freeUser($userNum)
{
$key = ftok(LanguageTask::SEM_KEY_FILE_PATH, LanguageTask::PROJECT_KEY);
$sem = sem_get($key);
$gotIt = sem_acquire($sem);
$shm = shm_attach($key);
if ($key === -1 || $sem === false || $gotIt === false || $shm === false) {
throw new JobException("Semaphore code failed in freeUser", 500);
}
$active = shm_get_var($shm, ACTIVE_USERS);
$active[$userNum] = false;
shm_put_var($shm, ACTIVE_USERS, $active);
shm_detach($shm);
sem_release($sem);
}
// ************************************************
// HELPER METHODS
// ************************************************
/**
* Run the given shell command in the runguard sandbox, using the given
* string for stdin (if given).
* @param string $wrappedCmd The shell command to execute
* @param boolean $iscompile true if this is a compilation (in which case
* parameter values must be greater than or equal to those in $min_params_compile.
* @param string $stdin The string to use as standard input. If not given use /dev/null
* @return array a two element array of the standard output and the standard error
* from running the given command.
*/
public function runInSandbox($wrappedCmd, $iscompile = true, $stdin = null)
{
$output = array();
$return_value = null;
$disklimit = $this->getParam('disklimit', $iscompile);
$filesize = $disklimit == -1 ? -1 : 1000 * $disklimit; // MB -> kB. -1 is deemed infinity.
$streamsize = 1000 * $this->getParam('streamsize', $iscompile); // MB -> kB
$memsize = 1000 * $this->getParam('memorylimit', $iscompile);
$cputime = $this->getParam('cputime', $iscompile);
$killtime = 2 * $cputime; // Kill the job after twice the allowed cpu time
$numProcs = $this->getParam('numprocs', $iscompile) + 1; // The + 1 allows for the sh command below.
// CPU pinning - only active if enabled
$sandboxCpuPinning = array();
if (config('Jobe')->cpu_pinning_enabled == true) {
$taskset_core_id = intval($this->userId) % config('Jobe')->cpu_pinning_num_cores;
$sandboxCpuPinning = array("taskset --cpu-list " . $taskset_core_id);
}
$sandboxCommandBits = [
"sudo " . dirname(__FILE__) . "/../../runguard/runguard",
"--user={$this->user}",
"--group=jobe",
"--cputime=$cputime", // Seconds of execution time allowed
"--time=$killtime", // Wall clock kill time
"--nproc=$numProcs", // Max num processes/threads for this *user*
"--no-core",
"--streamsize=$streamsize"
];
// Prepend CPU pinning command if enabled
$sandboxCommandBits = array_merge($sandboxCpuPinning, $sandboxCommandBits);
if ($memsize != 0) {
$sandboxCommandBits[] = "--memsize=$memsize";
}
if ($filesize != -1) { // Runguard's default filesize ulimit is unlimited.
$sandboxCommandBits[] = "--filesize=$filesize";
}
$sandboxCmd = implode(' ', $sandboxCommandBits) .
' sh -c ' . escapeshellarg($wrappedCmd) . ' >prog.out 2>prog.err';
// CD into the work directory and run the job
$workdir = $this->workdir;
chdir($workdir);
if ($stdin) {
$f = fopen('prog.in', 'w');
fwrite($f, $stdin);
fclose($f);
$sandboxCmd .= " <prog.in\n";
} else {
$sandboxCmd .= " </dev/null\n";
}
file_put_contents('prog.cmd', $sandboxCmd);
exec('bash prog.cmd');
$output = file_get_contents("$workdir/prog.out");
if (file_exists("{$this->workdir}/prog.err")) {
$stderr = file_get_contents("{$this->workdir}/prog.err");
} else {
$stderr = '';
}
return array($output, $stderr);
}
/*
* Get the value of the job parameter $key, which is taken from the
* value copied into $this from the run request if present or from the
* system defaults otherwise.
* If a non-numeric value is provided for a parameter that has a numeric
* default, the default is used instead. This prevents command injection
* as per issue #39 (https://github.com/trampgeek/jobe/issues/39). Thanks
* Marlon (myxl).
* If $iscompile is true and the parameter value is less than that specified
* in $min_params_compile (except if it's 0 meaning no limit), the minimum
* value is used instead.
*/
protected function getParam($key, $iscompile = false)
{
$default = $this->default_params[$key];
if (isset($this->params) && array_key_exists($key, $this->params)) {
$param = $this->params[$key];
if (is_numeric($default) && !is_numeric($param)) {
$param = $default; // Prevent command injection attacks.
}
} else {
$param = $default;
}
if ($iscompile && $param != 0 && array_key_exists($key, $this->min_params_compile) &&
$this->min_params_compile[$key] > $param) {
$param = $this->min_params_compile[$key];
}
return $param;
}
// Check if PHP exec environment includes a PATH. If not, set up a
// default, or gcc misbehaves. [Thanks to Binoj D for this bug fix,
// needed on his CentOS system.]
protected function setPath()
{
$envVars = array();
exec('printenv', $envVars);
$hasPath = false;
foreach ($envVars as $var) {
if (strpos($var, 'PATH=') === 0) {
$hasPath = true;
break;
}
}
if (!$hasPath) {
putenv("PATH=/sbin:/bin:/usr/sbin:/usr/bin");
}
}
// Return the Linux command to use to run the current job with the given
// standard input. It's an array of strings, which when joined with a
// a space character makes a bash command. The default is to use the
// name of the executable from getExecutablePath() followed by the strings
// in the 'interpreterargs' parameter followed by the name of the target file
// as returned by getTargetFile() followed by the strings in the
// 'runargs' parameter. For compiled languages, getExecutablePath
// should generally return the path to the compiled object file and
// getTargetFile() should return the empty string. The interpreterargs
// and runargs parameters are then just added (in that order) to the
// run command. For interpreted languages getExecutablePath should return
// the path to the interpreter and getTargetFile() should return the
// name of the file to be interpreted (in the current directory).
// This design allows for commands like java -Xss256k thing -blah.
public function getRunCommand()
{
$cmd = array($this->getExecutablePath());
$cmd = array_merge($cmd, $this->getParam('interpreterargs'));
if ($this->getTargetFile()) {
$cmd[] = $this->getTargetFile();
}
$cmd = array_merge($cmd, $this->getParam('runargs'));
return $cmd;
}
// Return a suitable default filename for the given sourcecode.
// Usually of form prog.py, prog.cpp etc but Java is a special case.
abstract public function defaultFileName($sourcecode);
// Return the path to the executable that runs this job. For compiled
// languages this will be the output from the compilation. For interpreted
// languages it will be the path to the interpreter or JVM etc.
abstract public function getExecutablePath();
// Return the name of the so called "target file", which will typically be empty
// for compiled languages and will be the name of the file to be interpreted
// (usually just $this->executableFileName) for interpreted languages.
abstract public function getTargetFile();
// Override the following function if the output from executing a program
// in this language needs post-filtering to remove stuff like
// header output.
public function filteredStdout()
{
return $this->stdout;
}
// Override the following function if the stderr from executing a program
// in this language needs post-filtering to remove stuff like
// backspaces and bells.
public function filteredStderr()
{
return $this->stderr;
}
// Called after each run to set the task result value. Default is to
// set the result to SUCCESS if there's no stderr output or to timelimit
// exceeded if the appropriate warning message is found in stdout or
// to runtime error otherwise.
// Note that Runguard does not identify memorylimit exceeded as a special
// type of runtime error so that value is not returned by default.
// Subclasses may wish to add further postprocessing, e.g. for memory
// limit exceeded if the language identifies this specifically.
public function diagnoseResult()
{
if (strlen($this->filteredStderr())) {
$this->result = LanguageTask::RESULT_RUNTIME_ERROR;
} else {
$this->result = LanguageTask::RESULT_SUCCESS;
}
// Refine RuntimeError if possible
if (preg_match("/time ?limit exceeded/", $this->stderr) !== 0) {
$this->result = LanguageTask::RESULT_TIME_LIMIT;
$this->signal = 9;
$this->stderr = '';
} else if (strpos($this->stderr, "warning: command terminated with signal 11")) {
$this->signal = 11;
$this->stderr = '';
}
}
// Return the JobeAPI result object to describe the state of this task
public function resultObject()
{
if ($this->cmpinfo) {
$this->result = LanguageTask::RESULT_COMPILATION_ERROR;
}
return new ResultObject(
$this->workdir,
$this->result,
$this->cmpinfo,
$this->filteredStdout(),
$this->filteredStderr()
);
}
// Remove any temporary files created by the given user on completion
// of a run
protected function removeTemporaryFiles($user)
{
$path = config('Jobe')->clean_up_path;
$dirs = explode(';', $path);
foreach ($dirs as $dir) {
exec("sudo /usr/bin/find $dir/ -user $user -delete");
}
}
// ************************************************
// METHODS FOR DIAGNOSING THE AVAILABLE LANGUAGES
// ************************************************
// Return a two-element array of the shell command to be run to obtain
// a version number and the RE pattern with which to extract the version
// string from the output. This should have a capturing parenthesised
// group so that $matches[1] is the required string after a call to
// preg_match. See getVersion below for details.
// Should be implemented by all subclasses. [Older versions of PHP
// don't allow me to declare this abstract. But it is!!]
public static function getVersionCommand()
{
}
// Return a string giving the version of language supported by this
// particular Language/Task.
// Return NULL if the version command (supplied by the subclass's
// getVersionCommand) fails or produces no output. This can be interpreted
// as a non-existent language that should be removed from the list of
// languages handled by this Jobe server.
// If the version command runs but yields a result in
// an unexpected format, returns the string "Unknown".
public static function getVersion()
{
list($command, $pattern) = static::getVersionCommand();
$output = array();
$retvalue = null;
exec($command . ' 2>&1', $output, $retvalue);
if ($retvalue != 0 || count($output) == 0) {
return null;
} else {
$matches = array();
$allOutput = implode("\n", $output);
$isMatch = preg_match($pattern, $allOutput, $matches);
return $isMatch ? $matches[1] : "Unknown";
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/Python3Task.php | app/Libraries/Python3Task.php | <?php
/* ==============================================================
*
* Python3
*
* ==============================================================
*
* @copyright 2014, 2020 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
class Python3Task extends LanguageTask
{
// Raise the memory limit for python to allow for numpy, matplolib
// etc. Set the interpreter args to ingore all Python
// environment variables and to suppress writing of .pyc files
// on import.
public function __construct($filename, $input, $params)
{
parent::__construct($filename, $input, $params);
$this->default_params['memorylimit'] = 1000; // NumpPy+matplotlib is getting greedier.
$this->default_params['interpreterargs'] = array('-BE');
}
public static function getVersionCommand()
{
$python = config('Jobe')->python3_version;
if (!file_exists($python)) {
$python = '/usr/bin/' . $python;
}
return array("$python --version", '/Python ([0-9._]*)/');
}
public function compile()
{
$python = Python3Task::pythonExecutable();
$cmd = "$python -m py_compile {$this->sourceFileName}";
$this->executableFileName = $this->sourceFileName;
list($output, $this->cmpinfo) = $this->runInSandbox($cmd);
if (!empty($this->cmpinfo) && !empty($output)) {
$this->cmpinfo = $output . '\n' . $this->cmpinfo;
}
}
// A default name for Python3 programs
public function defaultFileName($sourcecode)
{
return 'prog.py';
}
public function getExecutablePath()
{
return Python3Task::pythonExecutable();
}
public function getTargetFile()
{
return $this->sourceFileName;
}
private static function pythonExecutable()
{
$python = config('Jobe')->python3_version;
if (!file_exists($python)) {
$python = '/usr/bin/' . $python;
}
return $python;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/OverloadException.php | app/Libraries/OverloadException.php | <?php
/* ==============================================================
*
* Jobe Overload Exception
*
* ==============================================================
*
* @copyright 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
class OverloadException extends \Exception
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/JobException.php | app/Libraries/JobException.php | <?php
/*
* Copyright (C) 2014 Richard Lobb
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace Jobe;
class JobException extends \Exception
{
protected $logmessage;
protected $httpstatuscode;
public function __construct($message, $httpstatuscode, Throwable $cause = null)
{
parent::__construct($message, 0, $cause);
$this->httpstatuscode = $httpstatuscode;
}
public function getHttpStatusCode()
{
return $this->httpstatuscode;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/Python2Task.php | app/Libraries/Python2Task.php | <?php
/* ==============================================================
*
* Python2
*
* ==============================================================
*
* @copyright 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
class Python2Task extends LanguageTask
{
public function __construct($filename, $input, $params)
{
parent::__construct($filename, $input, $params);
$this->default_params['interpreterargs'] = array('-BESs');
}
public static function getVersionCommand()
{
return array('python2 --version', '/Python ([0-9._]*)/');
}
// A default name for Python2 programs
public function defaultFileName($sourcecode)
{
return 'prog.py2';
}
public function compile()
{
$this->executableFileName = $this->sourceFileName;
}
public function getExecutablePath()
{
return '/usr/bin/python2';
}
public function getTargetFile()
{
return $this->sourceFileName;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/CppTask.php | app/Libraries/CppTask.php | <?php
namespace Jobe;
/* ==============================================================
*
* C++
*
* ==============================================================
*
* @copyright 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class CppTask extends LanguageTask
{
public function __construct($filename, $input, $params)
{
parent::__construct($filename, $input, $params);
$this->default_params['compileargs'] = array(
'-Wall',
'-Werror');
}
public static function getVersionCommand()
{
return array('gcc --version', '/gcc \(.*\) ([0-9.]*)/');
}
public function compile()
{
$src = basename($this->sourceFileName);
$this->executableFileName = $execFileName = "$src.exe";
$compileargs = $this->getParam('compileargs');
$linkargs = $this->getParam('linkargs');
$cmd = "g++ " . implode(' ', $compileargs) . " -o $execFileName $src " . implode(' ', $linkargs);
list($output, $this->cmpinfo) = $this->runInSandbox($cmd);
}
// A default name for C++ programs
public function defaultFileName($sourcecode)
{
return 'prog.cpp';
}
// The executable is the output from the compilation
public function getExecutablePath()
{
return "./" . $this->executableFileName;
}
public function getTargetFile()
{
return '';
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/FileCache.php | app/Libraries/FileCache.php | <?php
/*
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/* ==============================================================
*
* This file defines the FileCache class, which manages the local file
* cache. Files are stored in the /home/jobe/files subtree with file names
* being the fileIDs supplied in the RestAPI 'put' requests. Normally these
* are the MD5 hashes of the file contents. Files are stored in a 2 level
* directory hierarchy like the Moodle file cache, with the first two letters of
* the fileID specifying the top-level directory name and the next two letters
* the second-level directory name. The rest of the fileID is used as the
* linux file name.
*
* ==============================================================
*
* @copyright 2019, 2024 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
define('FILE_CACHE_BASE', '/home/jobe/files');
define('MD5_PATTERN', '/[0-9abcdef]{32}/');
define('MAX_PERCENT_FULL', 0.95);
define('TESTING_FILE_CACHE_CLEAR', false);
class FileCache
{
/**
* @param string $fileid the externally supplied file id (a.k.a. filename)
* @return true iff the given file exists in the file cache.
*/
public static function fileExists($fileid)
{
$path = self::idToPath($fileid);
return file_exists($path);
}
/**
* Load the specified file into the workspace.
* @param string $fileid the id of the required file (aka filename)
* @param string $filename the name to give the file in the workspace
* @param string workspaceDir the directory in which to create the file
* @return true if copy succeeds or false if no such file exists
* or the copy fails for some other reason (e.g. workspace not writeable).
*/
public static function loadFileToWorkspace($fileid, $filename, $workspaceDir)
{
if (! self::fileExists($fileid)) {
return false;
}
$sourcepath = self::idToPath($fileid);
$destpath = $workspaceDir . '/' . $filename;
return copy($sourcepath, $destpath);
}
/**
* Insert the given file contents into the file cache with the given id
* aka filename. This is normally the md5 hash of the file contents. If
* it doesn't appear to be, the file is stored just with the given name
* at the top level of the cache hierarchy. Otherwise the first and
* second pair of characters from the filename are taken as the top and
* second level directory names respectively.
* @param string $fileid the external file id (aka filename).
*/
public static function filePutContents($fileid, $contents)
{
$freespace = disk_free_space(FILE_CACHE_BASE);
$volumesize = disk_total_space(FILE_CACHE_BASE);
if (TESTING_FILE_CACHE_CLEAR || $freespace / $volumesize > MAX_PERCENT_FULL) {
self:: cleanCache();
}
if (preg_match(MD5_PATTERN, $fileid) !== 1) {
$result = @file_put_contents(FILE_CACHE_BASE . '/' . $fileid, $contents);
} else {
$topdir = FILE_CACHE_BASE . '/' . substr($fileid, 0, 2);
$seconddir = $topdir . '/' . substr($fileid, 2, 2);
$fullpath = $seconddir . '/' . substr($fileid, 4);
if (!is_dir($topdir)) {
@mkdir($topdir, 0751);
}
if (!is_dir($seconddir)) {
@mkdir($seconddir, 0751);
}
$result = @file_put_contents($fullpath, $contents);
}
return $result;
}
/**
* Delete all files in the file cache that were last accessed over two
* days ago.
* This method is called by the filePutContents method
* if, before adding a file, the volume containing the file cache directory
* (/home/jobe/files) is over 95% full.
*
* If Jobe is providing services just to a Moodle/CodeRunner instance, this
* method should rarely if ever be called. Usually (and indeed always, prior
* to 2019) the only files being uploaded are the support files attached to
* questions by question authors. The total of all such files is usually small
* enough to leave plenty of space in a typical Linux install.
* However, if question authors are allowing/requiring students to attach
* files to their submissions, the file cache could fill up over time and/or
* with large classes and/or with large attachments. Then a cache clean up
* will be required. However, it should still be a very rare event and is
* certainly no worse than switching CodeRunner to a new Jobe server.
*
* Note that CodeRunner always tries running a job without first uploading
* files. Only if the run fails with a 404 Not Found do the files then
* get uploaded. With this mode of operation, deleting files unused for
* 2 days should be safe. However, non-CodeRunner users using HEAD to
* check file existence need to be prepared to re-upload files in the event
* of a 404 Not Found.
*/
public static function cleanCache()
{
log_message('info', '*jobe*: cleaning file cache');
@shell_exec("find " . FILE_CACHE_BASE . " -type f -atime +1 -delete &> /dev/null &");
}
// Return the cache file path for the given fileID.
private static function idToPath($fileid)
{
if (preg_match(MD5_PATTERN, $fileid) !== 1) {
$relativepath = $fileid;
} else {
$top = substr($fileid, 0, 2);
$second = substr($fileid, 2, 2);
$rest = substr($fileid, 4);
$relativepath = "$top/$second/$rest";
}
return FILE_CACHE_BASE . '/' . $relativepath;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/MatlabTask.php | app/Libraries/MatlabTask.php | <?php
/* ==============================================================
*
* Matlab
*
* ==============================================================
*
* @copyright 2014, 2015 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace jobe;
class MatlabTask extends LanguageTask
{
public function __construct($filename, $input, $params)
{
parent::__construct($filename, $input, $params);
$this->default_params['interpreterargs'] = array(
'-nojvm', // don't load the Java VM
'-r' // script filename follows
);
}
public static function getVersionCommand()
{
return array('/usr/local/bin/matlab_exec_cli -nodisplay -nojvm -nosplash -r exit', '/\(([0-9.]*)\)/');
}
public function compile()
{
$this->setPath();
$filename = basename($this->sourceFileName); // Strip any path bits
$dotpos = strpos($filename, '.');
if ($dotpos !== false) { // Strip trailing .matlab if given
$filename = substr($filename, 0, $dotpos);
}
$this->executableFileName = $filename; // Matlab's idea of the executable filename doesn't include .m
if (!copy($this->sourceFileName, $this->executableFileName . '.m')) {
throw new exception("Matlab_Task: couldn't copy source file");
}
}
// A default name for Matlab programs
public function defaultFileName($sourcecode)
{
return 'prog.m';
}
// Matlab throws in backspaces (grrr). There's also an extra BEL char
// at the end of any abort error message (presumably introduced at some
// point due to the EOF on stdin, which shuts down matlab).
public function filteredStderr()
{
$out = '';
for ($i = 0; $i < strlen($this->stderr); $i++) {
$c = $this->stderr[$i];
if ($c === "\x07") {
// pass
} elseif ($c === "\x08" && strlen($out) > 0) {
$out = substr($out, 0, -1);
} else {
$out .= $c;
}
}
return $out;
}
public function filteredStdout()
{
$lines = explode("\n", $this->stdout);
$outlines = array();
$headerEnded = false;
$endOfHeader = 'Research and commercial use is prohibited.';
foreach ($lines as $line) {
$line = rtrim($line);
if ($headerEnded) {
$outlines[] = $line;
} elseif (strpos($line, 'R2017b') !== false) {
// For R2017b, need a different end-of-header line
$endOfHeader = 'Classroom License -- for classroom instructional use only.';
} elseif (strpos($line, $endOfHeader) !== false) {
$headerEnded = true;
}
}
// Remove blank lines at the start and end
while (count($outlines) > 0 && strlen($outlines[0]) == 0) {
array_shift($outlines);
}
while (count($outlines) > 0 && strlen(end($outlines)) == 0) {
array_pop($outlines);
}
return implode("\n", $outlines) . "\n";
}
// The Matlab CLI program is the executable
public function getExecutablePath()
{
return '/usr/local/bin/matlab_exec_cli';
}
// The target file is the matlab file without its extension
public function getTargetFile()
{
return $this->executableFileName;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/RunSpecifier.php | app/Libraries/RunSpecifier.php | <?php
/* ==============================================================
*
* This file defines the RunSpecifier class, which captures all
* the data from the POST run-specifier.
*
* ==============================================================
*
* @copyright 2024 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
use App\Models\LanguagesModel;
define('MIN_FILE_IDENTIFIER_SIZE', 8);
class RunSpecifier
{
public string $input = '';
public string $sourcecode;
public string $language_id;
public string $sourcefilename='';
public array $parameters = [];
public array $files = [];
public bool $debug = false;
public function __construct($postDataJson)
{
if (!is_object($postDataJson)) {
throw new JobException('Non-JSON post data received', 400);
}
// throw new JobException(var_dump($postDataJson, true), 500);
$run = $postDataJson->run_spec;
if (!is_object($run)) {
throw new JobException('No run_spec attribute found in post data', 400);
}
foreach (['sourcecode', 'language_id'] as $attr) {
if (!isset($run->$attr)) {
throw new JobException("run_spec is missing the required attribute '$attr'", 400);
}
$this->$attr = $run->$attr;
}
$this->language_id = strtolower($this->language_id); // Normalise it.
$languages = LanguagesModel::supportedLanguages();
if (!array_key_exists($this->language_id, $languages)) {
throw new JobException("Language '{$this->language_id}' is not known", 400);
}
// Get any input.
$this->input = $run->input ?? '';
// Get debug flag.
$this->debug = $run->debug ?? config('Jobe')->debugging;
// Get the parameters, and validate.
$this->parameters = (array) ($run->parameters ?? []);
$config = config('Jobe');
$max_cpu_time = $config->cputime_upper_limit_secs;
if (intval($this->parameters['cputime'] ?? 0) > $max_cpu_time) {
throw new JobException("cputime exceeds maximum allowed on this Jobe server ($max_cpu_time secs)", 400);
}
if (isset($run->sourcefilename)) {
if (!self:: isValidSourceFilename($run->sourcefilename)) {
throw new JobException('The sourcefilename for the run_spec is illegal', 400);
} elseif ($run->sourcefilename !== 'prog.java') {
// As special case hack for legacy CodeRunner, ignore the almost-certainly-wrong
// name 'prog.java' for Java programs.
$this->sourcefilename = $run->sourcefilename;
}
}
// If there are files, check them.
$files = $run->file_list ?? [];
foreach ($files as $file) {
if (!$this->isValidFilespec($file)) {
throw new JobException("Invalid file specifier: " . print_r($file, true), 400);
}
$this->files[] = $file;
}
}
// Return true unless the given filename looks dangerous, e.g. has '/' or '..'
// substrings. Uses code from https://stackoverflow.com/questions/2021624/string-sanitizer-for-filename
private static function isValidSourceFilename($filename)
{
$sanitised = preg_replace(
'~
[<>:"/\\|?*]| # file system reserved https://en.wikipedia.org/wiki/Filename#Reserved_characters_and_words
[\x00-\x1F]| # ctrl chars http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247%28v=vs.85%29.aspx
[\x7F\xA0\xAD]| # non-printing characters DEL, NO-BREAK SPACE, SOFT HYPHEN
[#\[\]@!$&\'()+,;=]| # URI reserved https://tools.ietf.org/html/rfc3986#section-2.2
[{}^\~`] # URL unsafe characters https://www.ietf.org/rfc/rfc1738.txt
~x',
'-',
$filename
);
// Avoid ".", ".." or ".hiddenFiles"
$sanitised = ltrim($sanitised, '.-');
return $sanitised === $filename;
}
private function isValidFilespec($file)
{
return (count($file) == 2 || count($file) == 3) &&
is_string($file[0]) &&
is_string($file[1]) &&
strlen($file[0]) >= MIN_FILE_IDENTIFIER_SIZE &&
ctype_alnum($file[0]) &&
strlen($file[1]) > 0 &&
ctype_alnum(str_replace(array('-', '_', '.'), '', $file[1]));
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Libraries/OctaveTask.php | app/Libraries/OctaveTask.php | <?php
/* ==============================================================
*
* Octave
*
* ==============================================================
*
* @copyright 2014 Richard Lobb, University of Canterbury
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace Jobe;
class OctaveTask extends LanguageTask
{
public function __construct($filename, $input, $params)
{
parent::__construct($filename, $input, $params);
$this->default_params['interpreterargs'] = array(
'--norc',
'--no-window-system',
'--silent',
'-H');
$this->default_params['memorylimit'] = 500;
}
public static function getVersionCommand()
{
return array('octave --version --norc --no-window-system --silent', '/GNU Octave, version ([0-9._]*)/');
}
public function compile()
{
$this->executableFileName = $this->sourceFileName . '.m';
if (!copy($this->sourceFileName, $this->executableFileName)) {
throw new exception("Octave_Task: couldn't copy source file");
}
}
// A default name for Octave programs
public function defaultFileName($sourcecode)
{
return 'prog.m';
}
public function getExecutablePath()
{
return '/usr/bin/octave';
}
public function getTargetFile()
{
return $this->sourceFileName;
}
// Remove return chars and delete the extraneous error: lines at the end
public function filteredStderr()
{
$out1 = str_replace("\r", '', $this->stderr);
$lines = explode("\n", $out1);
while (count($lines) > 0 && trim($lines[count($lines) - 1]) === '') {
array_pop($lines);
}
if (count($lines) > 0 &&
strpos(
$lines[count($lines) - 1],
'error: ignoring octave_execution_exception'
) === 0) {
array_pop($lines);
}
// A bug in octave results in some errors lines at the end due to the
// non-existence of some environment variables that we can't set up
// in jobe. So trim them off.
if (count($lines) >= 1 &&
$lines[count($lines) - 1] == 'error: No such file or directory') {
array_pop($lines);
}
if (count($lines) > 0) {
return implode("\n", $lines) . "\n";
} else {
return '';
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Views/welcome_message.php | app/Views/welcome_message.php | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Welcome to CodeIgniter 4!</title>
<meta name="description" content="The small framework with powerful features">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" type="image/png" href="/favicon.ico">
<!-- STYLES -->
<style {csp-style-nonce}>
* {
transition: background-color 300ms ease, color 300ms ease;
}
*:focus {
background-color: rgba(221, 72, 20, .2);
outline: none;
}
html, body {
color: rgba(33, 37, 41, 1);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji";
font-size: 16px;
margin: 0;
padding: 0;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-rendering: optimizeLegibility;
}
header {
background-color: rgba(247, 248, 249, 1);
padding: .4rem 0 0;
}
.menu {
padding: .4rem 2rem;
}
header ul {
border-bottom: 1px solid rgba(242, 242, 242, 1);
list-style-type: none;
margin: 0;
overflow: hidden;
padding: 0;
text-align: right;
}
header li {
display: inline-block;
}
header li a {
border-radius: 5px;
color: rgba(0, 0, 0, .5);
display: block;
height: 44px;
text-decoration: none;
}
header li.menu-item a {
border-radius: 5px;
margin: 5px 0;
height: 38px;
line-height: 36px;
padding: .4rem .65rem;
text-align: center;
}
header li.menu-item a:hover,
header li.menu-item a:focus {
background-color: rgba(221, 72, 20, .2);
color: rgba(221, 72, 20, 1);
}
header .logo {
float: left;
height: 44px;
padding: .4rem .5rem;
}
header .menu-toggle {
display: none;
float: right;
font-size: 2rem;
font-weight: bold;
}
header .menu-toggle button {
background-color: rgba(221, 72, 20, .6);
border: none;
border-radius: 3px;
color: rgba(255, 255, 255, 1);
cursor: pointer;
font: inherit;
font-size: 1.3rem;
height: 36px;
padding: 0;
margin: 11px 0;
overflow: visible;
width: 40px;
}
header .menu-toggle button:hover,
header .menu-toggle button:focus {
background-color: rgba(221, 72, 20, .8);
color: rgba(255, 255, 255, .8);
}
header .heroe {
margin: 0 auto;
max-width: 1100px;
padding: 1rem 1.75rem 1.75rem 1.75rem;
}
header .heroe h1 {
font-size: 2.5rem;
font-weight: 500;
}
header .heroe h2 {
font-size: 1.5rem;
font-weight: 300;
}
section {
margin: 0 auto;
max-width: 1100px;
padding: 2.5rem 1.75rem 3.5rem 1.75rem;
}
section h1 {
margin-bottom: 2.5rem;
}
section h2 {
font-size: 120%;
line-height: 2.5rem;
padding-top: 1.5rem;
}
section pre {
background-color: rgba(247, 248, 249, 1);
border: 1px solid rgba(242, 242, 242, 1);
display: block;
font-size: .9rem;
margin: 2rem 0;
padding: 1rem 1.5rem;
white-space: pre-wrap;
word-break: break-all;
}
section code {
display: block;
}
section a {
color: rgba(221, 72, 20, 1);
}
section svg {
margin-bottom: -5px;
margin-right: 5px;
width: 25px;
}
.further {
background-color: rgba(247, 248, 249, 1);
border-bottom: 1px solid rgba(242, 242, 242, 1);
border-top: 1px solid rgba(242, 242, 242, 1);
}
.further h2:first-of-type {
padding-top: 0;
}
.svg-stroke {
fill: none;
stroke: #000;
stroke-width: 32px;
}
footer {
background-color: rgba(221, 72, 20, .8);
text-align: center;
}
footer .environment {
color: rgba(255, 255, 255, 1);
padding: 2rem 1.75rem;
}
footer .copyrights {
background-color: rgba(62, 62, 62, 1);
color: rgba(200, 200, 200, 1);
padding: .25rem 1.75rem;
}
@media (max-width: 629px) {
header ul {
padding: 0;
}
header .menu-toggle {
padding: 0 1rem;
}
header .menu-item {
background-color: rgba(244, 245, 246, 1);
border-top: 1px solid rgba(242, 242, 242, 1);
margin: 0 15px;
width: calc(100% - 30px);
}
header .menu-toggle {
display: block;
}
header .hidden {
display: none;
}
header li.menu-item a {
background-color: rgba(221, 72, 20, .1);
}
header li.menu-item a:hover,
header li.menu-item a:focus {
background-color: rgba(221, 72, 20, .7);
color: rgba(255, 255, 255, .8);
}
}
</style>
</head>
<body>
<!-- HEADER: MENU + HEROE SECTION -->
<header>
<div class="menu">
<ul>
<li class="logo">
<a href="https://codeigniter.com" target="_blank">
<svg role="img" aria-label="Visit CodeIgniter.com official website!" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 2100 500" height="44"><path fill="#dd4814" d="M148.2 411c-20.53-9.07-34.48-28.61-36.31-50.99 1.2-23.02 13.36-44.06 32.67-56.61-3.17 7.73-2.4 16.53 2 23.6 5.01 7 13.63 10.36 22.07 8.61 12.02-3.38 19.06-15.86 15.68-27.89-1.2-4.21-3.6-8.03-6.88-10.91-13.6-11.06-20.43-28.44-18-45.81 2.33-9.2 7.42-17.52 14.61-23.8-5.4 14.4 9.83 28.61 20.05 35.6 18.14 10.88 35.6 22.84 52.32 35.81 18.27 14.4 28.23 36.94 26.67 60-4.11 24.54-21.47 44.8-45.13 52.4 47.33-10.53 96.13-48.13 97.06-101.46-.93-42.67-26.4-80.96-65.33-98.4h-1.73c.86 2.09 1.28 4.34 1.2 6.61.13-1.47.13-2.93 0-4.4.21 1.73.21 3.47 0 5.2-2.96 12.13-15.2 19.6-27.36 16.64-4.86-1.2-9.2-3.93-12.32-7.87-15.6-20 0-42.76 2.61-64.76 1.6-28.13-11.25-55.02-34.05-71.46 11.41 19.02-3.79 44-14.84 58.21-11.07 14.21-27.07 24.8-40.11 37.2-14.05 13.07-26.93 27.44-38.49 42.8-24.99 30.53-34.8 70.8-26.67 109.4 11.15 37.2 42.07 65.15 80.2 72.4h.21l-.13-.12Zm324.56-159.8q0-17.92 6.16-35.56 6.44-17.92 18.48-31.92t29.68-22.68q17.64-8.96 40.04-8.96 26.6 0 45.36 12.04 19.04 12.04 28 31.36l-15.4 9.52q-4.76-9.8-11.76-16.52-6.72-6.72-14.56-10.92-7.84-4.2-16.24-5.88-8.4-1.96-16.52-1.96-17.92 0-31.64 7.28-13.72 7.28-23.24 19.04-9.24 11.76-14 26.6-4.76 14.56-4.76 29.68 0 16.52 5.6 31.64 5.88 15.12 15.68 26.88 10.08 11.48 23.52 18.48 13.72 6.72 29.68 6.72 8.4 0 17.08-1.96 8.96-2.24 17.08-6.72 8.4-4.76 15.4-11.48 7-7 11.76-16.8l16.24 8.4q-4.76 11.2-13.44 19.88-8.68 8.4-19.32 14.28-10.64 5.88-22.68 8.96-11.76 3.08-23.24 3.08-20.44 0-37.52-8.96-17.08-8.96-29.4-23.24-12.32-14.56-19.32-32.76-6.72-18.48-6.72-37.52Zm263.48 103.6q-15.96 0-29.12-5.88-13.16-6.16-22.96-16.52-9.52-10.36-14.84-24.08Q664 294.6 664 279.48q0-15.4 5.32-29.12 5.6-13.72 15.12-24.08 9.8-10.36 22.96-16.52t28.84-6.16q15.68 0 28.84 6.16 13.44 6.16 22.96 16.52 9.8 10.36 15.12 24.08 5.6 13.72 5.6 29.12 0 15.12-5.32 28.84t-15.12 24.08q-9.52 10.36-22.96 16.52-13.16 5.88-29.12 5.88Zm-52.92-75.04q0 12.32 4.2 22.96 4.2 10.36 11.2 18.48 7.28 7.84 16.8 12.32 9.8 4.48 20.72 4.48 10.92 0 20.44-4.48 9.8-4.76 17.08-12.6 7.28-8.12 11.48-18.76 4.2-10.64 4.2-22.96 0-12.04-4.2-22.68-4.2-10.92-11.48-18.76-7.28-8.12-17.08-12.6-9.52-4.76-20.44-4.76-10.92 0-20.44 4.76-9.52 4.48-16.8 12.6-7.28 8.12-11.48 19.04-4.2 10.64-4.2 22.96ZM900.6 354.8q-15.12 0-28-6.16-12.88-6.44-22.12-16.8t-14.56-23.8q-5.04-13.72-5.04-28.56 0-15.4 5.04-29.12 5.04-14 13.72-24.36 8.96-10.36 21-16.24 12.32-6.16 26.88-6.16 18.48 0 32.76 9.8 14.28 9.52 22.4 23.24V147.6h19.04v179.76q0 7.84 6.72 7.84V352q-4.2.84-6.72.84-6.72 0-11.76-4.2-5.04-4.48-5.04-10.64v-14.28Q946.24 338 931.4 346.4t-30.8 8.4Zm4.2-16.8q7 0 14.84-2.8 8.12-2.8 15.12-7.56 7-5.04 11.76-11.48 5.04-6.72 6.16-14.28V256.8q-2.8-7.56-8.12-14-5.32-6.72-12.32-11.76-6.72-5.04-14.56-7.84-7.84-2.8-15.4-2.8-11.76 0-21.28 5.04-9.52 5.04-16.52 13.44-6.72 8.12-10.36 18.76-3.64 10.64-3.64 21.84 0 11.76 4.2 22.4 4.2 10.64 11.48 18.76 7.28 7.84 17.08 12.6Q893.32 338 904.8 338Zm173.04 16.8q-15.96 0-29.4-5.88-13.16-6.16-22.96-16.52-9.8-10.64-15.4-24.36-5.32-13.72-5.32-29.4 0-15.4 5.32-28.84 5.6-13.72 15.12-23.8 9.8-10.36 23.24-16.24 13.44-6.16 29.12-6.16 15.96 0 29.12 6.16 13.44 5.88 22.96 16.24 9.52 10.36 14.84 23.8 5.32 13.44 5.32 28.56v4.48q0 2.24-.28 3.08h-124.88q.84 11.76 5.32 21.84 4.76 9.8 12.04 17.08 7.28 7.28 16.52 11.48 9.52 3.92 20.16 3.92 7 0 14-1.96t12.88-5.32q5.88-3.36 10.64-8.12 4.76-5.04 7.28-10.92l16.52 4.48q-3.36 8.12-9.52 14.84-6.16 6.44-14.28 11.48-8.12 4.76-17.92 7.56-9.8 2.52-20.44 2.52Zm-53.48-83.44h107.24q-.84-11.76-5.6-21.28-4.48-9.8-11.76-16.8-7-7-16.52-10.92-9.24-3.92-19.88-3.92-10.64 0-20.16 3.92t-16.8 10.92q-7 7-11.48 16.8-4.2 9.8-5.04 21.28Zm193.2 80.64h-38.64V153.2h38.64V352Zm93.52.84q-14.84 0-26.88-5.88t-21-15.96q-8.68-10.36-13.44-23.8-4.76-13.44-4.76-28.56 0-15.96 5.04-29.68 5.04-13.72 14-24.08 8.96-10.36 21.56-16.24 12.6-5.88 27.72-5.88 17.08 0 29.96 7.84 12.88 7.56 21.28 20.44v-25.76h32.76V345q0 16.24-6.16 29.12-6.16 12.88-17.08 21.84-10.64 8.96-25.76 13.72-14.84 4.76-32.48 4.76-24.08 0-40.6-7.84-16.24-8.12-28-22.68l20.44-19.88q8.4 10.36 21 16.24 12.88 5.88 27.16 5.88 8.68 0 16.52-2.24 8.12-2.52 14.28-7.56 6.16-5.04 9.52-12.88 3.64-7.84 3.64-18.48v-18.48q-7.28 12.6-20.44 19.6-13.16 6.72-28.28 6.72Zm12.6-29.96q6.16 0 11.76-1.96t10.36-5.32q4.76-3.36 8.4-7.84 3.64-4.48 5.6-9.52v-35q-5.04-12.88-15.96-20.72-10.64-7.84-22.4-7.84-8.68 0-15.68 3.92-7 3.64-12.04 10.08-5.04 6.16-7.84 14.28-2.52 8.12-2.52 16.8 0 8.96 3.08 16.8t8.4 13.72q5.6 5.88 12.88 9.24 7.28 3.36 15.96 3.36Zm243.88-62.44V352h-37.52v-82.32q0-17.64-6.16-25.76-6.16-8.12-17.08-8.12-5.6 0-11.48 2.24-5.88 2.24-11.2 6.44-5.04 3.92-9.24 9.52t-6.16 12.32V352h-37.52V205.28h33.88v27.16q8.12-14 23.52-21.84t34.72-7.84q13.72 0 22.4 5.04 8.68 5.04 13.44 13.16 4.76 8.12 6.44 18.48 1.96 10.36 1.96 21Zm70.28 91.56h-37.52V205.28h37.52V352Zm0-167.16h-37.52V147.6h37.52v37.24Zm114.24 129.92 7.56 29.68q-7.56 3.36-18.48 6.72-10.92 3.36-22.96 3.36-7.84 0-14.84-1.96-6.72-1.96-12.04-6.16-5.04-4.48-8.12-11.2-3.08-7-3.08-16.8v-84.28h-19.32v-28.84h19.32v-47.6h37.52v47.6h30.8v28.84h-30.8v71.68q0 7.84 3.92 11.2 4.2 3.08 10.08 3.08t11.48-1.96q5.6-1.96 8.96-3.36Zm91.56 40.04q-17.64 0-31.92-5.88-14.28-6.16-24.36-16.52t-15.68-24.08q-5.32-13.72-5.32-28.84 0-15.68 5.32-29.4 5.32-14 15.4-24.36 10.08-10.64 24.36-16.8 14.56-6.16 32.48-6.16 17.92 0 31.92 6.16 14.28 6.16 24.08 16.52 10.08 10.36 15.12 24.08 5.32 13.72 5.32 28.56 0 3.64-.28 7 0 3.36-.56 5.6h-113.4q.84 8.68 4.2 15.4 3.36 6.72 8.68 11.48 5.32 4.76 12.04 7.28 6.72 2.52 14 2.52 11.2 0 21-5.32 10.08-5.6 13.72-14.56l32.2 8.96q-8.12 16.8-26.04 27.72-17.64 10.64-42.28 10.64Zm-38.08-88.48h76.16q-1.4-16.52-12.32-26.32-10.64-10.08-26.04-10.08-7.56 0-14.28 2.8-6.44 2.52-11.48 7.28t-8.4 11.48q-3.08 6.72-3.64 14.84Zm225.12-62.72v34.16q-17.08.28-30.52 6.72-13.44 6.16-19.32 18.76V352h-37.52V205.28h34.44v31.36q3.92-7.56 9.24-13.44 5.32-6.16 11.48-10.64t12.32-6.72q6.44-2.52 12.32-2.52h4.48q1.68 0 3.08.28Z"/></svg>
</a>
</li>
<li class="menu-toggle">
<button id="menuToggle">☰</button>
</li>
<li class="menu-item hidden"><a href="#">Home</a></li>
<li class="menu-item hidden"><a href="https://codeigniter.com/user_guide/" target="_blank">Docs</a>
</li>
<li class="menu-item hidden"><a href="https://forum.codeigniter.com/" target="_blank">Community</a></li>
<li class="menu-item hidden"><a
href="https://codeigniter.com/contribute" target="_blank">Contribute</a>
</li>
</ul>
</div>
<div class="heroe">
<h1>Welcome to CodeIgniter <?= CodeIgniter\CodeIgniter::CI_VERSION ?></h1>
<h2>The small framework with powerful features</h2>
</div>
</header>
<!-- CONTENT -->
<section>
<h1>About this page</h1>
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you will find it located at:</p>
<pre><code>app/Views/welcome_message.php</code></pre>
<p>The corresponding controller for this page can be found at:</p>
<pre><code>app/Controllers/Home.php</code></pre>
</section>
<div class="further">
<section>
<h1>Go further</h1>
<h2>
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><rect x='32' y='96' width='64' height='368' rx='16' ry='16' class="svg-stroke" /><line x1='112' y1='224' x2='240' y2='224' class="svg-stroke" /><line x1='112' y1='400' x2='240' y2='400' class="svg-stroke" /><rect x='112' y='160' width='128' height='304' rx='16' ry='16' class="svg-stroke" /><rect x='256' y='48' width='96' height='416' rx='16' ry='16' class="svg-stroke" /><path d='M422.46,96.11l-40.4,4.25c-11.12,1.17-19.18,11.57-17.93,23.1l34.92,321.59c1.26,11.53,11.37,20,22.49,18.84l40.4-4.25c11.12-1.17,19.18-11.57,17.93-23.1L445,115C443.69,103.42,433.58,94.94,422.46,96.11Z' class="svg-stroke"/></svg>
Learn
</h2>
<p>The User Guide contains an introduction, tutorial, a number of "how to"
guides, and then reference documentation for the components that make up
the framework. Check the <a href="https://codeigniter.com/user_guide/"
target="_blank">User Guide</a> !</p>
<h2>
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><path d='M431,320.6c-1-3.6,1.2-8.6,3.3-12.2a33.68,33.68,0,0,1,2.1-3.1A162,162,0,0,0,464,215c.3-92.2-77.5-167-173.7-167C206.4,48,136.4,105.1,120,180.9a160.7,160.7,0,0,0-3.7,34.2c0,92.3,74.8,169.1,171,169.1,15.3,0,35.9-4.6,47.2-7.7s22.5-7.2,25.4-8.3a26.44,26.44,0,0,1,9.3-1.7,26,26,0,0,1,10.1,2L436,388.6a13.52,13.52,0,0,0,3.9,1,8,8,0,0,0,8-8,12.85,12.85,0,0,0-.5-2.7Z' class="svg-stroke" /><path d='M66.46,232a146.23,146.23,0,0,0,6.39,152.67c2.31,3.49,3.61,6.19,3.21,8s-11.93,61.87-11.93,61.87a8,8,0,0,0,2.71,7.68A8.17,8.17,0,0,0,72,464a7.26,7.26,0,0,0,2.91-.6l56.21-22a15.7,15.7,0,0,1,12,.2c18.94,7.38,39.88,12,60.83,12A159.21,159.21,0,0,0,284,432.11' class="svg-stroke" /></svg>
Discuss
</h2>
<p>CodeIgniter is a community-developed open source project, with several
venues for the community members to gather and exchange ideas. View all
the threads on <a href="https://forum.codeigniter.com/"
target="_blank">CodeIgniter's forum</a>, or <a href="https://join.slack.com/t/codeigniterchat/shared_invite/zt-rl30zw00-obL1Hr1q1ATvkzVkFp8S0Q"
target="_blank">chat on Slack</a> !</p>
<h2>
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 512'><line x1='176' y1='48' x2='336' y2='48' class="svg-stroke" /><line x1='118' y1='304' x2='394' y2='304' class="svg-stroke" /><path d='M208,48v93.48a64.09,64.09,0,0,1-9.88,34.18L73.21,373.49C48.4,412.78,76.63,464,123.08,464H388.92c46.45,0,74.68-51.22,49.87-90.51L313.87,175.66A64.09,64.09,0,0,1,304,141.48V48' class="svg-stroke" /></svg>
Contribute
</h2>
<p>CodeIgniter is a community driven project and accepts contributions
of code and documentation from the community. Why not
<a href="https://codeigniter.com/contribute" target="_blank">
join us</a> ?</p>
</section>
</div>
<!-- FOOTER: DEBUG INFO + COPYRIGHTS -->
<footer>
<div class="environment">
<p>Page rendered in {elapsed_time} seconds using {memory_usage} MB of memory.</p>
<p>Environment: <?= ENVIRONMENT ?></p>
</div>
<div class="copyrights">
<p>© <?= date('Y') ?> CodeIgniter Foundation. CodeIgniter is open source project released under the MIT
open source licence.</p>
</div>
</footer>
<!-- SCRIPTS -->
<script {csp-script-nonce}>
document.getElementById("menuToggle").addEventListener('click', toggleMenu);
function toggleMenu() {
var menuItems = document.getElementsByClassName('menu-item');
for (var i = 0; i < menuItems.length; i++) {
var menuItem = menuItems[i];
menuItem.classList.toggle("hidden");
}
}
</script>
<!-- -->
</body>
</html>
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Views/errors/html/error_exception.php | app/Views/errors/html/error_exception.php | <?php
use CodeIgniter\HTTP\Header;
use CodeIgniter\CodeIgniter;
$errorId = uniqid('error', true);
?>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title><?= esc($title) ?></title>
<style>
<?= preg_replace('#[\r\n\t ]+#', ' ', file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'debug.css')) ?>
</style>
<script>
<?= file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'debug.js') ?>
</script>
</head>
<body onload="init()">
<!-- Header -->
<div class="header">
<div class="environment">
Displayed at <?= esc(date('H:i:s')) ?> —
PHP: <?= esc(PHP_VERSION) ?> —
CodeIgniter: <?= esc(CodeIgniter::CI_VERSION) ?> --
Environment: <?= ENVIRONMENT ?>
</div>
<div class="container">
<h1><?= esc($title), esc($exception->getCode() ? ' #' . $exception->getCode() : '') ?></h1>
<p>
<?= nl2br(esc($exception->getMessage())) ?>
<a href="https://www.duckduckgo.com/?q=<?= urlencode($title . ' ' . preg_replace('#\'.*\'|".*"#Us', '', $exception->getMessage())) ?>"
rel="noreferrer" target="_blank">search →</a>
</p>
</div>
</div>
<!-- Source -->
<div class="container">
<p><b><?= esc(clean_path($file)) ?></b> at line <b><?= esc($line) ?></b></p>
<?php if (is_file($file)) : ?>
<div class="source">
<?= static::highlightFile($file, $line, 15); ?>
</div>
<?php endif; ?>
</div>
<div class="container">
<?php
$last = $exception;
while ($prevException = $last->getPrevious()) {
$last = $prevException;
?>
<pre>
Caused by:
<?= esc($prevException::class), esc($prevException->getCode() ? ' #' . $prevException->getCode() : '') ?>
<?= nl2br(esc($prevException->getMessage())) ?>
<a href="https://www.duckduckgo.com/?q=<?= urlencode($prevException::class . ' ' . preg_replace('#\'.*\'|".*"#Us', '', $prevException->getMessage())) ?>"
rel="noreferrer" target="_blank">search →</a>
<?= esc(clean_path($prevException->getFile()) . ':' . $prevException->getLine()) ?>
</pre>
<?php
}
?>
</div>
<?php if (defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE) : ?>
<div class="container">
<ul class="tabs" id="tabs">
<li><a href="#backtrace">Backtrace</a></li>
<li><a href="#server">Server</a></li>
<li><a href="#request">Request</a></li>
<li><a href="#response">Response</a></li>
<li><a href="#files">Files</a></li>
<li><a href="#memory">Memory</a></li>
</ul>
<div class="tab-content">
<!-- Backtrace -->
<div class="content" id="backtrace">
<ol class="trace">
<?php foreach ($trace as $index => $row) : ?>
<li>
<p>
<!-- Trace info -->
<?php if (isset($row['file']) && is_file($row['file'])) : ?>
<?php
if (isset($row['function']) && in_array($row['function'], ['include', 'include_once', 'require', 'require_once'], true)) {
echo esc($row['function'] . ' ' . clean_path($row['file']));
} else {
echo esc(clean_path($row['file']) . ' : ' . $row['line']);
}
?>
<?php else: ?>
{PHP internal code}
<?php endif; ?>
<!-- Class/Method -->
<?php if (isset($row['class'])) : ?>
— <?= esc($row['class'] . $row['type'] . $row['function']) ?>
<?php if (! empty($row['args'])) : ?>
<?php $argsId = $errorId . 'args' . $index ?>
( <a href="#" onclick="return toggle('<?= esc($argsId, 'attr') ?>');">arguments</a> )
<div class="args" id="<?= esc($argsId, 'attr') ?>">
<table cellspacing="0">
<?php
$params = null;
// Reflection by name is not available for closure function
if (! str_ends_with($row['function'], '}')) {
$mirror = isset($row['class']) ? new ReflectionMethod($row['class'], $row['function']) : new ReflectionFunction($row['function']);
$params = $mirror->getParameters();
}
foreach ($row['args'] as $key => $value) : ?>
<tr>
<td><code><?= esc(isset($params[$key]) ? '$' . $params[$key]->name : "#{$key}") ?></code></td>
<td><pre><?= esc(print_r($value, true)) ?></pre></td>
</tr>
<?php endforeach ?>
</table>
</div>
<?php else : ?>
()
<?php endif; ?>
<?php endif; ?>
<?php if (! isset($row['class']) && isset($row['function'])) : ?>
— <?= esc($row['function']) ?>()
<?php endif; ?>
</p>
<!-- Source? -->
<?php if (isset($row['file']) && is_file($row['file']) && isset($row['class'])) : ?>
<div class="source">
<?= static::highlightFile($row['file'], $row['line']) ?>
</div>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ol>
</div>
<!-- Server -->
<div class="content" id="server">
<?php foreach (['_SERVER', '_SESSION'] as $var) : ?>
<?php
if (empty($GLOBALS[$var]) || ! is_array($GLOBALS[$var])) {
continue;
} ?>
<h3>$<?= esc($var) ?></h3>
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($GLOBALS[$var] as $key => $value) : ?>
<tr>
<td><?= esc($key) ?></td>
<td>
<?php if (is_string($value)) : ?>
<?= esc($value) ?>
<?php else: ?>
<pre><?= esc(print_r($value, true)) ?></pre>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endforeach ?>
<!-- Constants -->
<?php $constants = get_defined_constants(true); ?>
<?php if (! empty($constants['user'])) : ?>
<h3>Constants</h3>
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($constants['user'] as $key => $value) : ?>
<tr>
<td><?= esc($key) ?></td>
<td>
<?php if (is_string($value)) : ?>
<?= esc($value) ?>
<?php else: ?>
<pre><?= esc(print_r($value, true)) ?></pre>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- Request -->
<div class="content" id="request">
<?php $request = service('request'); ?>
<table>
<tbody>
<tr>
<td style="width: 10em">Path</td>
<td><?= esc($request->getUri()) ?></td>
</tr>
<tr>
<td>HTTP Method</td>
<td><?= esc($request->getMethod()) ?></td>
</tr>
<tr>
<td>IP Address</td>
<td><?= esc($request->getIPAddress()) ?></td>
</tr>
<tr>
<td style="width: 10em">Is AJAX Request?</td>
<td><?= $request->isAJAX() ? 'yes' : 'no' ?></td>
</tr>
<tr>
<td>Is CLI Request?</td>
<td><?= $request->isCLI() ? 'yes' : 'no' ?></td>
</tr>
<tr>
<td>Is Secure Request?</td>
<td><?= $request->isSecure() ? 'yes' : 'no' ?></td>
</tr>
<tr>
<td>User Agent</td>
<td><?= esc($request->getUserAgent()->getAgentString()) ?></td>
</tr>
</tbody>
</table>
<?php $empty = true; ?>
<?php foreach (['_GET', '_POST', '_COOKIE'] as $var) : ?>
<?php
if (empty($GLOBALS[$var]) || ! is_array($GLOBALS[$var])) {
continue;
} ?>
<?php $empty = false; ?>
<h3>$<?= esc($var) ?></h3>
<table style="width: 100%">
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($GLOBALS[$var] as $key => $value) : ?>
<tr>
<td><?= esc($key) ?></td>
<td>
<?php if (is_string($value)) : ?>
<?= esc($value) ?>
<?php else: ?>
<pre><?= esc(print_r($value, true)) ?></pre>
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endforeach ?>
<?php if ($empty) : ?>
<div class="alert">
No $_GET, $_POST, or $_COOKIE Information to show.
</div>
<?php endif; ?>
<?php $headers = $request->headers(); ?>
<?php if (! empty($headers)) : ?>
<h3>Headers</h3>
<table>
<thead>
<tr>
<th>Header</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($headers as $name => $value) : ?>
<tr>
<td><?= esc($name, 'html') ?></td>
<td>
<?php
if ($value instanceof Header) {
echo esc($value->getValueLine(), 'html');
} else {
foreach ($value as $i => $header) {
echo ' ('. $i+1 . ') ' . esc($header->getValueLine(), 'html');
}
}
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- Response -->
<?php
$response = service('response');
$response->setStatusCode(http_response_code());
?>
<div class="content" id="response">
<table>
<tr>
<td style="width: 15em">Response Status</td>
<td><?= esc($response->getStatusCode() . ' - ' . $response->getReasonPhrase()) ?></td>
</tr>
</table>
<?php $headers = $response->headers(); ?>
<?php if (! empty($headers)) : ?>
<h3>Headers</h3>
<table>
<thead>
<tr>
<th>Header</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<?php foreach ($headers as $name => $value) : ?>
<tr>
<td><?= esc($name, 'html') ?></td>
<td>
<?php
if ($value instanceof Header) {
echo esc($response->getHeaderLine($name), 'html');
} else {
foreach ($value as $i => $header) {
echo ' ('. $i+1 . ') ' . esc($header->getValueLine(), 'html');
}
}
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
</div>
<!-- Files -->
<div class="content" id="files">
<?php $files = get_included_files(); ?>
<ol>
<?php foreach ($files as $file) :?>
<li><?= esc(clean_path($file)) ?></li>
<?php endforeach ?>
</ol>
</div>
<!-- Memory -->
<div class="content" id="memory">
<table>
<tbody>
<tr>
<td>Memory Usage</td>
<td><?= esc(static::describeMemory(memory_get_usage(true))) ?></td>
</tr>
<tr>
<td style="width: 12em">Peak Memory Usage:</td>
<td><?= esc(static::describeMemory(memory_get_peak_usage(true))) ?></td>
</tr>
<tr>
<td>Memory Limit:</td>
<td><?= esc(ini_get('memory_limit')) ?></td>
</tr>
</tbody>
</table>
</div>
</div> <!-- /tab-content -->
</div> <!-- /container -->
<?php endif; ?>
</body>
</html>
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Views/errors/html/error_400.php | app/Views/errors/html/error_400.php | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= lang('Errors.badRequest') ?></title>
<style>
div.logo {
height: 200px;
width: 155px;
display: inline-block;
opacity: 0.08;
position: absolute;
top: 2rem;
left: 50%;
margin-left: -73px;
}
body {
height: 100%;
background: #fafafa;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #777;
font-weight: 300;
}
h1 {
font-weight: lighter;
letter-spacing: normal;
font-size: 3rem;
margin-top: 0;
margin-bottom: 0;
color: #222;
}
.wrap {
max-width: 1024px;
margin: 5rem auto;
padding: 2rem;
background: #fff;
text-align: center;
border: 1px solid #efefef;
border-radius: 0.5rem;
position: relative;
}
pre {
white-space: normal;
margin-top: 1.5rem;
}
code {
background: #fafafa;
border: 1px solid #efefef;
padding: 0.5rem 1rem;
border-radius: 5px;
display: block;
}
p {
margin-top: 1.5rem;
}
.footer {
margin-top: 2rem;
border-top: 1px solid #efefef;
padding: 1em 2em 0 2em;
font-size: 85%;
color: #999;
}
a:active,
a:link,
a:visited {
color: #dd4814;
}
</style>
</head>
<body>
<div class="wrap">
<h1>400</h1>
<p>
<?php if (ENVIRONMENT !== 'production') : ?>
<?= nl2br(esc($message)) ?>
<?php else : ?>
<?= lang('Errors.sorryBadRequest') ?>
<?php endif; ?>
</p>
</div>
</body>
</html>
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Views/errors/html/error_404.php | app/Views/errors/html/error_404.php | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= lang('Errors.pageNotFound') ?></title>
<style>
div.logo {
height: 200px;
width: 155px;
display: inline-block;
opacity: 0.08;
position: absolute;
top: 2rem;
left: 50%;
margin-left: -73px;
}
body {
height: 100%;
background: #fafafa;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #777;
font-weight: 300;
}
h1 {
font-weight: lighter;
letter-spacing: normal;
font-size: 3rem;
margin-top: 0;
margin-bottom: 0;
color: #222;
}
.wrap {
max-width: 1024px;
margin: 5rem auto;
padding: 2rem;
background: #fff;
text-align: center;
border: 1px solid #efefef;
border-radius: 0.5rem;
position: relative;
}
pre {
white-space: normal;
margin-top: 1.5rem;
}
code {
background: #fafafa;
border: 1px solid #efefef;
padding: 0.5rem 1rem;
border-radius: 5px;
display: block;
}
p {
margin-top: 1.5rem;
}
.footer {
margin-top: 2rem;
border-top: 1px solid #efefef;
padding: 1em 2em 0 2em;
font-size: 85%;
color: #999;
}
a:active,
a:link,
a:visited {
color: #dd4814;
}
</style>
</head>
<body>
<div class="wrap">
<h1>404</h1>
<p>
<?php if (ENVIRONMENT !== 'production') : ?>
<?= nl2br(esc($message)) ?>
<?php else : ?>
<?= lang('Errors.sorryCannotFind') ?>
<?php endif; ?>
</p>
</div>
</body>
</html>
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Views/errors/html/production.php | app/Views/errors/html/production.php | <!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="robots" content="noindex">
<title><?= lang('Errors.whoops') ?></title>
<style>
<?= preg_replace('#[\r\n\t ]+#', ' ', file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'debug.css')) ?>
</style>
</head>
<body>
<div class="container text-center">
<h1 class="headline"><?= lang('Errors.whoops') ?></h1>
<p class="lead"><?= lang('Errors.weHitASnag') ?></p>
</div>
</body>
</html>
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Views/errors/cli/error_exception.php | app/Views/errors/cli/error_exception.php | <?php
use CodeIgniter\CLI\CLI;
// The main Exception
CLI::write('[' . $exception::class . ']', 'light_gray', 'red');
CLI::write($message);
CLI::write('at ' . CLI::color(clean_path($exception->getFile()) . ':' . $exception->getLine(), 'green'));
CLI::newLine();
$last = $exception;
while ($prevException = $last->getPrevious()) {
$last = $prevException;
CLI::write(' Caused by:');
CLI::write(' [' . $prevException::class . ']', 'red');
CLI::write(' ' . $prevException->getMessage());
CLI::write(' at ' . CLI::color(clean_path($prevException->getFile()) . ':' . $prevException->getLine(), 'green'));
CLI::newLine();
}
// The backtrace
if (defined('SHOW_DEBUG_BACKTRACE') && SHOW_DEBUG_BACKTRACE) {
$backtraces = $last->getTrace();
if ($backtraces) {
CLI::write('Backtrace:', 'green');
}
foreach ($backtraces as $i => $error) {
$padFile = ' '; // 4 spaces
$padClass = ' '; // 7 spaces
$c = str_pad($i + 1, 3, ' ', STR_PAD_LEFT);
if (isset($error['file'])) {
$filepath = clean_path($error['file']) . ':' . $error['line'];
CLI::write($c . $padFile . CLI::color($filepath, 'yellow'));
} else {
CLI::write($c . $padFile . CLI::color('[internal function]', 'yellow'));
}
$function = '';
if (isset($error['class'])) {
$type = ($error['type'] === '->') ? '()' . $error['type'] : $error['type'];
$function .= $padClass . $error['class'] . $type . $error['function'];
} elseif (! isset($error['class']) && isset($error['function'])) {
$function .= $padClass . $error['function'];
}
$args = implode(', ', array_map(static fn ($value): string => match (true) {
is_object($value) => 'Object(' . $value::class . ')',
is_array($value) => $value !== [] ? '[...]' : '[]',
$value === null => 'null', // return the lowercased version
default => var_export($value, true),
}, array_values($error['args'] ?? [])));
$function .= '(' . $args . ')';
CLI::write($function);
CLI::newLine();
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Views/errors/cli/error_404.php | app/Views/errors/cli/error_404.php | <?php
use CodeIgniter\CLI\CLI;
CLI::error('ERROR: ' . $code);
CLI::write($message);
CLI::newLine();
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Views/errors/cli/production.php | app/Views/errors/cli/production.php | <?php
// On the CLI, we still want errors in productions
// so just use the exception template.
include __DIR__ . '/error_exception.php';
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Encryption.php | app/Config/Encryption.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Encryption configuration.
*
* These are the settings used for encryption, if you don't pass a parameter
* array to the encrypter for creation/initialization.
*/
class Encryption extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Encryption Key Starter
* --------------------------------------------------------------------------
*
* If you use the Encryption class you must set an encryption key (seed).
* You need to ensure it is long enough for the cipher and mode you plan to use.
* See the user guide for more info.
*/
public string $key = '';
/**
* --------------------------------------------------------------------------
* Encryption Driver to Use
* --------------------------------------------------------------------------
*
* One of the supported encryption drivers.
*
* Available drivers:
* - OpenSSL
* - Sodium
*/
public string $driver = 'OpenSSL';
/**
* --------------------------------------------------------------------------
* SodiumHandler's Padding Length in Bytes
* --------------------------------------------------------------------------
*
* This is the number of bytes that will be padded to the plaintext message
* before it is encrypted. This value should be greater than zero.
*
* See the user guide for more information on padding.
*/
public int $blockSize = 16;
/**
* --------------------------------------------------------------------------
* Encryption digest
* --------------------------------------------------------------------------
*
* HMAC digest to use, e.g. 'SHA512' or 'SHA256'. Default value is 'SHA512'.
*/
public string $digest = 'SHA512';
/**
* Whether the cipher-text should be raw. If set to false, then it will be base64 encoded.
* This setting is only used by OpenSSLHandler.
*
* Set to false for CI3 Encryption compatibility.
*/
public bool $rawData = true;
/**
* Encryption key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'encryption' for CI3 Encryption compatibility.
*/
public string $encryptKeyInfo = '';
/**
* Authentication key info.
* This setting is only used by OpenSSLHandler.
*
* Set to 'authentication' for CI3 Encryption compatibility.
*/
public string $authKeyInfo = '';
/**
* Cipher to use.
* This setting is only used by OpenSSLHandler.
*
* Set to 'AES-128-CBC' to decrypt encrypted data that encrypted
* by CI3 Encryption default configuration.
*/
public string $cipher = 'AES-256-CTR';
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Cors.php | app/Config/Cors.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Cross-Origin Resource Sharing (CORS) Configuration
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
*/
class Cors extends BaseConfig
{
/**
* The default CORS configuration.
*
* @var array{
* allowedOrigins: list<string>,
* allowedOriginsPatterns: list<string>,
* supportsCredentials: bool,
* allowedHeaders: list<string>,
* exposedHeaders: list<string>,
* allowedMethods: list<string>,
* maxAge: int,
* }
*/
public array $default = [
/**
* Origins for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* E.g.:
* - ['http://localhost:8080']
* - ['https://www.example.com']
*/
'allowedOrigins' => [],
/**
* Origin regex patterns for the `Access-Control-Allow-Origin` header.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin
*
* NOTE: A pattern specified here is part of a regular expression. It will
* be actually `#\A<pattern>\z#`.
*
* E.g.:
* - ['https://\w+\.example\.com']
*/
'allowedOriginsPatterns' => [],
/**
* Weather to send the `Access-Control-Allow-Credentials` header.
*
* The Access-Control-Allow-Credentials response header tells browsers whether
* the server allows cross-origin HTTP requests to include credentials.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Credentials
*/
'supportsCredentials' => false,
/**
* Set headers to allow.
*
* The Access-Control-Allow-Headers response header is used in response to
* a preflight request which includes the Access-Control-Request-Headers to
* indicate which HTTP headers can be used during the actual request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Headers
*/
'allowedHeaders' => [],
/**
* Set headers to expose.
*
* The Access-Control-Expose-Headers response header allows a server to
* indicate which response headers should be made available to scripts running
* in the browser, in response to a cross-origin request.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
*/
'exposedHeaders' => [],
/**
* Set methods to allow.
*
* The Access-Control-Allow-Methods response header specifies one or more
* methods allowed when accessing a resource in response to a preflight
* request.
*
* E.g.:
* - ['GET', 'POST', 'PUT', 'DELETE']
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Methods
*/
'allowedMethods' => [],
/**
* Set how many seconds the results of a preflight request can be cached.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age
*/
'maxAge' => 7200,
];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Routing.php | app/Config/Routing.php | <?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace Config;
use CodeIgniter\Config\Routing as BaseRouting;
/**
* Routing configuration
*/
class Routing extends BaseRouting
{
/**
* For Defined Routes.
* An array of files that contain route definitions.
* Route files are read in order, with the first match
* found taking precedence.
*
* Default: APPPATH . 'Config/Routes.php'
*
* @var list<string>
*/
public array $routeFiles = [
APPPATH . 'Config/Routes.php',
];
/**
* For Defined Routes and Auto Routing.
* The default namespace to use for Controllers when no other
* namespace has been specified.
*
* Default: 'App\Controllers'
*/
public string $defaultNamespace = 'App\Controllers';
/**
* For Auto Routing.
* The default controller to use when no other controller has been
* specified.
*
* Default: 'Home'
*/
public string $defaultController = 'Home';
/**
* For Defined Routes and Auto Routing.
* The default method to call on the controller when no other
* method has been set in the route.
*
* Default: 'index'
*/
public string $defaultMethod = 'index';
/**
* For Auto Routing.
* Whether to translate dashes in URIs for controller/method to underscores.
* Primarily useful when using the auto-routing.
*
* Default: false
*/
public bool $translateURIDashes = false;
/**
* Sets the class/method that should be called if routing doesn't
* find a match. It can be the controller/method name like: Users::index
*
* This setting is passed to the Router class and handled there.
*
* If you want to use a closure, you will have to set it in the
* routes file by calling:
*
* $routes->set404Override(function() {
* // Do something here
* });
*
* Example:
* public $override404 = 'App\Errors::show404';
*/
public ?string $override404 = null;
/**
* If TRUE, the system will attempt to match the URI against
* Controllers by matching each segment against folders/files
* in APPPATH/Controllers, when a match wasn't found against
* defined routes.
*
* If FALSE, will stop searching and do NO automatic routing.
*/
public bool $autoRoute = false;
/**
* For Defined Routes.
* If TRUE, will enable the use of the 'prioritize' option
* when defining routes.
*
* Default: false
*/
public bool $prioritize = false;
/**
* For Defined Routes.
* If TRUE, matched multiple URI segments will be passed as one parameter.
*
* Default: false
*/
public bool $multipleSegmentsOneParam = false;
/**
* For Auto Routing (Improved).
* Map of URI segments and namespaces.
*
* The key is the first URI segment. The value is the controller namespace.
* E.g.,
* [
* 'blog' => 'Acme\Blog\Controllers',
* ]
*
* @var array<string, string>
*/
public array $moduleRoutes = [];
/**
* For Auto Routing (Improved).
* Whether to translate dashes in URIs for controller/method to CamelCase.
* E.g., blog-controller -> BlogController
*
* If you enable this, $translateURIDashes is ignored.
*
* Default: false
*/
public bool $translateUriToCamelCase = true;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/ForeignCharacters.php | app/Config/ForeignCharacters.php | <?php
namespace Config;
use CodeIgniter\Config\ForeignCharacters as BaseForeignCharacters;
/**
* @immutable
*/
class ForeignCharacters extends BaseForeignCharacters
{
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Database.php | app/Config/Database.php | <?php
namespace Config;
use CodeIgniter\Database\Config;
/**
* Database Configuration
*/
class Database extends Config
{
/**
* The directory that holds the Migrations and Seeds directories.
*/
public string $filesPath = APPPATH . 'Database' . DIRECTORY_SEPARATOR;
/**
* Lets you choose which connection group to use if no other is specified.
*/
public string $defaultGroup = 'default';
/**
* The default database connection.
*
* @var array<string, mixed>
*/
public array $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8mb4',
'DBCollat' => 'utf8mb4_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'numberNative' => false,
'foundRows' => false,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
// /**
// * Sample database connection for SQLite3.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'database' => 'database.db',
// 'DBDriver' => 'SQLite3',
// 'DBPrefix' => '',
// 'DBDebug' => true,
// 'swapPre' => '',
// 'failover' => [],
// 'foreignKeys' => true,
// 'busyTimeout' => 1000,
// 'synchronous' => null,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for Postgre.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'public',
// 'DBDriver' => 'Postgre',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'failover' => [],
// 'port' => 5432,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for SQLSRV.
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => '',
// 'hostname' => 'localhost',
// 'username' => 'root',
// 'password' => 'root',
// 'database' => 'ci4',
// 'schema' => 'dbo',
// 'DBDriver' => 'SQLSRV',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'utf8',
// 'swapPre' => '',
// 'encrypt' => false,
// 'failover' => [],
// 'port' => 1433,
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
// /**
// * Sample database connection for OCI8.
// *
// * You may need the following environment variables:
// * NLS_LANG = 'AMERICAN_AMERICA.UTF8'
// * NLS_DATE_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// * NLS_TIMESTAMP_TZ_FORMAT = 'YYYY-MM-DD HH24:MI:SS'
// *
// * @var array<string, mixed>
// */
// public array $default = [
// 'DSN' => 'localhost:1521/XEPDB1',
// 'username' => 'root',
// 'password' => 'root',
// 'DBDriver' => 'OCI8',
// 'DBPrefix' => '',
// 'pConnect' => false,
// 'DBDebug' => true,
// 'charset' => 'AL32UTF8',
// 'swapPre' => '',
// 'failover' => [],
// 'dateFormat' => [
// 'date' => 'Y-m-d',
// 'datetime' => 'Y-m-d H:i:s',
// 'time' => 'H:i:s',
// ],
// ];
/**
* This database connection is used when running PHPUnit database tests.
*
* @var array<string, mixed>
*/
public array $tests = [
'DSN' => '',
'hostname' => '127.0.0.1',
'username' => '',
'password' => '',
'database' => ':memory:',
'DBDriver' => 'SQLite3',
'DBPrefix' => 'db_', // Needed to ensure we're working correctly with prefixes live. DO NOT REMOVE FOR CI DEVS
'pConnect' => false,
'DBDebug' => true,
'charset' => 'utf8',
'DBCollat' => '',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
'foreignKeys' => true,
'busyTimeout' => 1000,
'dateFormat' => [
'date' => 'Y-m-d',
'datetime' => 'Y-m-d H:i:s',
'time' => 'H:i:s',
],
];
public function __construct()
{
parent::__construct();
// Ensure that we always set the database group to 'tests' if
// we are currently running an automated test suite, so that
// we don't overwrite live data on accident.
if (ENVIRONMENT === 'testing') {
$this->defaultGroup = 'tests';
}
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Paths.php | app/Config/Paths.php | <?php
namespace Config;
/**
* Paths
*
* Holds the paths that are used by the system to
* locate the main directories, app, system, etc.
*
* Modifying these allows you to restructure your application,
* share a system folder between multiple applications, and more.
*
* All paths are relative to the project's root folder.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Paths
{
/**
* ---------------------------------------------------------------
* SYSTEM FOLDER NAME
* ---------------------------------------------------------------
*
* This must contain the name of your "system" folder. Include
* the path if the folder is not in the same directory as this file.
*/
public string $systemDirectory = __DIR__ . '/../../system';
/**
* ---------------------------------------------------------------
* APPLICATION FOLDER NAME
* ---------------------------------------------------------------
*
* If you want this front controller to use a different "app"
* folder than the default one you can set its name here. The folder
* can also be renamed or relocated anywhere on your server. If
* you do, use a full server path.
*
* @see http://codeigniter.com/user_guide/general/managing_apps.html
*/
public string $appDirectory = __DIR__ . '/..';
/**
* ---------------------------------------------------------------
* WRITABLE DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "writable" directory.
* The writable directory allows you to group all directories that
* need write permission to a single place that can be tucked away
* for maximum security, keeping it out of the app and/or
* system directories.
*/
public string $writableDirectory = __DIR__ . '/../../writable';
/**
* ---------------------------------------------------------------
* TESTS DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of your "tests" directory.
*/
public string $testsDirectory = __DIR__ . '/../../tests';
/**
* ---------------------------------------------------------------
* VIEW DIRECTORY NAME
* ---------------------------------------------------------------
*
* This variable must contain the name of the directory that
* contains the view files used by your application. By
* default this is in `app/Views`. This value
* is used when no value is provided to `Services::renderer()`.
*/
public string $viewDirectory = __DIR__ . '/../Views';
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Events.php | app/Config/Events.php | <?php
namespace Config;
use CodeIgniter\Events\Events;
use CodeIgniter\Exceptions\FrameworkException;
use CodeIgniter\HotReloader\HotReloader;
/*
* --------------------------------------------------------------------
* Application Events
* --------------------------------------------------------------------
* Events allow you to tap into the execution of the program without
* modifying or extending core files. This file provides a central
* location to define your events, though they can always be added
* at run-time, also, if needed.
*
* You create code that can execute by subscribing to events with
* the 'on()' method. This accepts any form of callable, including
* Closures, that will be executed when the event is triggered.
*
* Example:
* Events::on('create', [$myInstance, 'myMethod']);
*/
Events::on('pre_system', static function (): void {
if (ENVIRONMENT !== 'testing') {
if (ini_get('zlib.output_compression')) {
throw FrameworkException::forEnabledZlibOutputCompression();
}
while (ob_get_level() > 0) {
ob_end_flush();
}
ob_start(static fn ($buffer) => $buffer);
}
/*
* --------------------------------------------------------------------
* Debug Toolbar Listeners.
* --------------------------------------------------------------------
* If you delete, they will no longer be collected.
*/
if (CI_DEBUG && ! is_cli()) {
Events::on('DBQuery', 'CodeIgniter\Debug\Toolbar\Collectors\Database::collect');
service('toolbar')->respond();
// Hot Reload route - for framework use on the hot reloader.
if (ENVIRONMENT === 'development') {
service('routes')->get('__hot-reload', static function (): void {
(new HotReloader())->run();
});
}
}
});
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Autoload.php | app/Config/Autoload.php | <?php
namespace Config;
use CodeIgniter\Config\AutoloadConfig;
/**
* -------------------------------------------------------------------
* AUTOLOADER CONFIGURATION
* -------------------------------------------------------------------
*
* This file defines the namespaces and class maps so the Autoloader
* can find the files as needed.
*
* NOTE: If you use an identical key in $psr4 or $classmap, then
* the values in this file will overwrite the framework's values.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Autoload extends AutoloadConfig
{
/**
* -------------------------------------------------------------------
* Namespaces
* -------------------------------------------------------------------
* This maps the locations of any namespaces in your application to
* their location on the file system. These are used by the autoloader
* to locate files the first time they have been instantiated.
*
* The 'Config' (APPPATH . 'Config') and 'CodeIgniter' (SYSTEMPATH) are
* already mapped for you.
*
* You may change the name of the 'App' namespace if you wish,
* but this should be done prior to creating any namespaced classes,
* else you will need to modify all of those classes for this to work.
*
* @var array<string, list<string>|string>
*/
public $psr4 = [
'Jobe' => APPPATH . 'Libraries', // For custom app namespace
APP_NAMESPACE => APPPATH,
];
/**
* -------------------------------------------------------------------
* Class Map
* -------------------------------------------------------------------
* The class map provides a map of class names and their exact
* location on the drive. Classes loaded in this manner will have
* slightly faster performance because they will not have to be
* searched for within one or more directories as they would if they
* were being autoloaded through a namespace.
*
* Prototype:
* $classmap = [
* 'MyClass' => '/path/to/class/file.php'
* ];
*
* @var array<string, string>
*/
public $classmap = [];
/**
* -------------------------------------------------------------------
* Files
* -------------------------------------------------------------------
* The files array provides a list of paths to __non-class__ files
* that will be autoloaded. This can be useful for bootstrap operations
* or for loading functions.
*
* Prototype:
* $files = [
* '/path/to/my/file.php',
* ];
*
* @var list<string>
*/
public $files = [];
/**
* -------------------------------------------------------------------
* Helpers
* -------------------------------------------------------------------
* Prototype:
* $helpers = [
* 'form',
* ];
*
* @var list<string>
*/
public $helpers = [];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Mimes.php | app/Config/Mimes.php | <?php
namespace Config;
/**
* This file contains an array of mime types. It is used by the
* Upload class to help identify allowed file types.
*
* When more than one variation for an extension exist (like jpg, jpeg, etc)
* the most common one should be first in the array to aid the guess*
* methods. The same applies when more than one mime-type exists for a
* single extension.
*
* When working with mime types, please make sure you have the ´fileinfo´
* extension enabled to reliably detect the media types.
*/
class Mimes
{
/**
* Map of extensions to mime types.
*
* @var array<string, list<string>|string>
*/
public static array $mimes = [
'hqx' => [
'application/mac-binhex40',
'application/mac-binhex',
'application/x-binhex40',
'application/x-mac-binhex40',
],
'cpt' => 'application/mac-compactpro',
'csv' => [
'text/csv',
'text/x-comma-separated-values',
'text/comma-separated-values',
'application/vnd.ms-excel',
'application/x-csv',
'text/x-csv',
'application/csv',
'application/excel',
'application/vnd.msexcel',
'text/plain',
],
'bin' => [
'application/macbinary',
'application/mac-binary',
'application/octet-stream',
'application/x-binary',
'application/x-macbinary',
],
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => [
'application/octet-stream',
'application/vnd.microsoft.portable-executable',
'application/x-dosexec',
'application/x-msdownload',
],
'class' => 'application/octet-stream',
'psd' => [
'application/x-photoshop',
'image/vnd.adobe.photoshop',
],
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => [
'application/pdf',
'application/force-download',
'application/x-download',
],
'ai' => [
'application/pdf',
'application/postscript',
],
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => [
'application/vnd.ms-excel',
'application/msexcel',
'application/x-msexcel',
'application/x-ms-excel',
'application/x-excel',
'application/x-dos_ms_excel',
'application/xls',
'application/x-xls',
'application/excel',
'application/download',
'application/vnd.ms-office',
'application/msword',
],
'ppt' => [
'application/vnd.ms-powerpoint',
'application/powerpoint',
'application/vnd.ms-office',
'application/msword',
],
'pptx' => [
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
],
'wbxml' => 'application/wbxml',
'wmlc' => 'application/wmlc',
'dcr' => 'application/x-director',
'dir' => 'application/x-director',
'dxr' => 'application/x-director',
'dvi' => 'application/x-dvi',
'gtar' => 'application/x-gtar',
'gz' => 'application/x-gzip',
'gzip' => 'application/x-gzip',
'php' => [
'application/x-php',
'application/x-httpd-php',
'application/php',
'text/php',
'text/x-php',
'application/x-httpd-php-source',
],
'php4' => 'application/x-httpd-php',
'php3' => 'application/x-httpd-php',
'phtml' => 'application/x-httpd-php',
'phps' => 'application/x-httpd-php-source',
'js' => [
'application/x-javascript',
'text/plain',
],
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => [
'application/x-tar',
'application/x-gzip-compressed',
],
'z' => 'application/x-compress',
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => [
'application/x-zip',
'application/zip',
'application/x-zip-compressed',
'application/s-compressed',
'multipart/x-zip',
],
'rar' => [
'application/vnd.rar',
'application/x-rar',
'application/rar',
'application/x-rar-compressed',
],
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => [
'audio/mpeg',
'audio/mpg',
'audio/mpeg3',
'audio/mp3',
],
'aif' => [
'audio/x-aiff',
'audio/aiff',
],
'aiff' => [
'audio/x-aiff',
'audio/aiff',
],
'aifc' => 'audio/x-aiff',
'ram' => 'audio/x-pn-realaudio',
'rm' => 'audio/x-pn-realaudio',
'rpm' => 'audio/x-pn-realaudio-plugin',
'ra' => 'audio/x-realaudio',
'rv' => 'video/vnd.rn-realvideo',
'wav' => [
'audio/x-wav',
'audio/wave',
'audio/wav',
],
'bmp' => [
'image/bmp',
'image/x-bmp',
'image/x-bitmap',
'image/x-xbitmap',
'image/x-win-bitmap',
'image/x-windows-bmp',
'image/ms-bmp',
'image/x-ms-bmp',
'application/bmp',
'application/x-bmp',
'application/x-win-bitmap',
],
'gif' => 'image/gif',
'jpg' => [
'image/jpeg',
'image/pjpeg',
],
'jpeg' => [
'image/jpeg',
'image/pjpeg',
],
'jpe' => [
'image/jpeg',
'image/pjpeg',
],
'jp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'j2k' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpf' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpg2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpx' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'jpm' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mj2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'mjp2' => [
'image/jp2',
'video/mj2',
'image/jpx',
'image/jpm',
],
'png' => [
'image/png',
'image/x-png',
],
'webp' => 'image/webp',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'css' => [
'text/css',
'text/plain',
],
'html' => [
'text/html',
'text/plain',
],
'htm' => [
'text/html',
'text/plain',
],
'shtml' => [
'text/html',
'text/plain',
],
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => [
'text/plain',
'text/x-log',
],
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => [
'application/xml',
'text/xml',
'text/plain',
],
'xsl' => [
'application/xml',
'text/xsl',
'text/xml',
],
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => [
'video/x-msvideo',
'video/msvideo',
'video/avi',
'application/x-troff-msvideo',
],
'movie' => 'video/x-sgi-movie',
'doc' => [
'application/msword',
'application/vnd.ms-office',
],
'docx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
'application/x-zip',
],
'dot' => [
'application/msword',
'application/vnd.ms-office',
],
'dotx' => [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/zip',
'application/msword',
],
'xlsx' => [
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/zip',
'application/vnd.ms-excel',
'application/msword',
'application/x-zip',
],
'xlsb' => 'application/vnd.ms-excel.sheet.binary.macroEnabled.12',
'xlsm' => 'application/vnd.ms-excel.sheet.macroEnabled.12',
'word' => [
'application/msword',
'application/octet-stream',
],
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => [
'application/json',
'text/json',
],
'pem' => [
'application/x-x509-user-cert',
'application/x-pem-file',
'application/octet-stream',
],
'p10' => [
'application/x-pkcs10',
'application/pkcs10',
],
'p12' => 'application/x-pkcs12',
'p7a' => 'application/x-pkcs7-signature',
'p7c' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7m' => [
'application/pkcs7-mime',
'application/x-pkcs7-mime',
],
'p7r' => 'application/x-pkcs7-certreqresp',
'p7s' => 'application/pkcs7-signature',
'crt' => [
'application/x-x509-ca-cert',
'application/x-x509-user-cert',
'application/pkix-cert',
],
'crl' => [
'application/pkix-crl',
'application/pkcs-crl',
],
'der' => 'application/x-x509-ca-cert',
'kdb' => 'application/octet-stream',
'pgp' => 'application/pgp',
'gpg' => 'application/gpg-keys',
'sst' => 'application/octet-stream',
'csr' => 'application/octet-stream',
'rsa' => 'application/x-pkcs7',
'cer' => [
'application/pkix-cert',
'application/x-x509-ca-cert',
],
'3g2' => 'video/3gpp2',
'3gp' => [
'video/3gp',
'video/3gpp',
],
'mp4' => 'video/mp4',
'm4a' => 'audio/x-m4a',
'f4v' => [
'video/mp4',
'video/x-f4v',
],
'flv' => 'video/x-flv',
'webm' => 'video/webm',
'aac' => 'audio/x-acc',
'm4u' => 'application/vnd.mpegurl',
'm3u' => 'text/plain',
'xspf' => 'application/xspf+xml',
'vlc' => 'application/videolan',
'wmv' => [
'video/x-ms-wmv',
'video/x-ms-asf',
],
'au' => 'audio/x-au',
'ac3' => 'audio/ac3',
'flac' => 'audio/x-flac',
'ogg' => [
'audio/ogg',
'video/ogg',
'application/ogg',
],
'kmz' => [
'application/vnd.google-earth.kmz',
'application/zip',
'application/x-zip',
],
'kml' => [
'application/vnd.google-earth.kml+xml',
'application/xml',
'text/xml',
],
'ics' => 'text/calendar',
'ical' => 'text/calendar',
'zsh' => 'text/x-scriptzsh',
'7zip' => [
'application/x-compressed',
'application/x-zip-compressed',
'application/zip',
'multipart/x-zip',
],
'cdr' => [
'application/cdr',
'application/coreldraw',
'application/x-cdr',
'application/x-coreldraw',
'image/cdr',
'image/x-cdr',
'zz-application/zz-winassoc-cdr',
],
'wma' => [
'audio/x-ms-wma',
'video/x-ms-asf',
],
'jar' => [
'application/java-archive',
'application/x-java-application',
'application/x-jar',
'application/x-compressed',
],
'svg' => [
'image/svg+xml',
'image/svg',
'application/xml',
'text/xml',
],
'vcf' => 'text/x-vcard',
'srt' => [
'text/srt',
'text/plain',
],
'vtt' => [
'text/vtt',
'text/plain',
],
'ico' => [
'image/x-icon',
'image/x-ico',
'image/vnd.microsoft.icon',
],
'stl' => [
'application/sla',
'application/vnd.ms-pki.stl',
'application/x-navistyle',
'model/stl',
'application/octet-stream',
],
];
/**
* Attempts to determine the best mime type for the given file extension.
*
* @return string|null The mime type found, or none if unable to determine.
*/
public static function guessTypeFromExtension(string $extension)
{
$extension = trim(strtolower($extension), '. ');
if (! array_key_exists($extension, static::$mimes)) {
return null;
}
return is_array(static::$mimes[$extension]) ? static::$mimes[$extension][0] : static::$mimes[$extension];
}
/**
* Attempts to determine the best file extension for a given mime type.
*
* @param string|null $proposedExtension - default extension (in case there is more than one with the same mime type)
*
* @return string|null The extension determined, or null if unable to match.
*/
public static function guessExtensionFromType(string $type, ?string $proposedExtension = null)
{
$type = trim(strtolower($type), '. ');
$proposedExtension = trim(strtolower($proposedExtension ?? ''));
if (
$proposedExtension !== ''
&& array_key_exists($proposedExtension, static::$mimes)
&& in_array($type, (array) static::$mimes[$proposedExtension], true)
) {
// The detected mime type matches with the proposed extension.
return $proposedExtension;
}
// Reverse check the mime type list if no extension was proposed.
// This search is order sensitive!
foreach (static::$mimes as $ext => $types) {
if (in_array($type, (array) $types, true)) {
return $ext;
}
}
return null;
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/ContentSecurityPolicy.php | app/Config/ContentSecurityPolicy.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Stores the default settings for the ContentSecurityPolicy, if you
* choose to use it. The values here will be read in and set as defaults
* for the site. If needed, they can be overridden on a page-by-page basis.
*
* Suggested reference for explanations:
*
* @see https://www.html5rocks.com/en/tutorials/security/content-security-policy/
*/
class ContentSecurityPolicy extends BaseConfig
{
// -------------------------------------------------------------------------
// Broadbrush CSP management
// -------------------------------------------------------------------------
/**
* Default CSP report context
*/
public bool $reportOnly = false;
/**
* Specifies a URL where a browser will send reports
* when a content security policy is violated.
*/
public ?string $reportURI = null;
/**
* Instructs user agents to rewrite URL schemes, changing
* HTTP to HTTPS. This directive is for websites with
* large numbers of old URLs that need to be rewritten.
*/
public bool $upgradeInsecureRequests = false;
// -------------------------------------------------------------------------
// Sources allowed
// NOTE: once you set a policy to 'none', it cannot be further restricted
// -------------------------------------------------------------------------
/**
* Will default to self if not overridden
*
* @var list<string>|string|null
*/
public $defaultSrc;
/**
* Lists allowed scripts' URLs.
*
* @var list<string>|string
*/
public $scriptSrc = 'self';
/**
* Lists allowed stylesheets' URLs.
*
* @var list<string>|string
*/
public $styleSrc = 'self';
/**
* Defines the origins from which images can be loaded.
*
* @var list<string>|string
*/
public $imageSrc = 'self';
/**
* Restricts the URLs that can appear in a page's `<base>` element.
*
* Will default to self if not overridden
*
* @var list<string>|string|null
*/
public $baseURI;
/**
* Lists the URLs for workers and embedded frame contents
*
* @var list<string>|string
*/
public $childSrc = 'self';
/**
* Limits the origins that you can connect to (via XHR,
* WebSockets, and EventSource).
*
* @var list<string>|string
*/
public $connectSrc = 'self';
/**
* Specifies the origins that can serve web fonts.
*
* @var list<string>|string
*/
public $fontSrc;
/**
* Lists valid endpoints for submission from `<form>` tags.
*
* @var list<string>|string
*/
public $formAction = 'self';
/**
* Specifies the sources that can embed the current page.
* This directive applies to `<frame>`, `<iframe>`, `<embed>`,
* and `<applet>` tags. This directive can't be used in
* `<meta>` tags and applies only to non-HTML resources.
*
* @var list<string>|string|null
*/
public $frameAncestors;
/**
* The frame-src directive restricts the URLs which may
* be loaded into nested browsing contexts.
*
* @var list<string>|string|null
*/
public $frameSrc;
/**
* Restricts the origins allowed to deliver video and audio.
*
* @var list<string>|string|null
*/
public $mediaSrc;
/**
* Allows control over Flash and other plugins.
*
* @var list<string>|string
*/
public $objectSrc = 'self';
/**
* @var list<string>|string|null
*/
public $manifestSrc;
/**
* Limits the kinds of plugins a page may invoke.
*
* @var list<string>|string|null
*/
public $pluginTypes;
/**
* List of actions allowed.
*
* @var list<string>|string|null
*/
public $sandbox;
/**
* Nonce tag for style
*/
public string $styleNonceTag = '{csp-style-nonce}';
/**
* Nonce tag for script
*/
public string $scriptNonceTag = '{csp-script-nonce}';
/**
* Replace nonce tag automatically
*/
public bool $autoNonce = true;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/CURLRequest.php | app/Config/CURLRequest.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class CURLRequest extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CURLRequest Share Options
* --------------------------------------------------------------------------
*
* Whether share options between requests or not.
*
* If true, all the options won't be reset between requests.
* It may cause an error request with unnecessary headers.
*/
public bool $shareOptions = false;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/DocTypes.php | app/Config/DocTypes.php | <?php
namespace Config;
class DocTypes
{
/**
* List of valid document types.
*
* @var array<string, string>
*/
public array $list = [
'xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'xhtml-basic11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">',
'mathml1' => '<!DOCTYPE math SYSTEM "http://www.w3.org/Math/DTD/mathml1/mathml.dtd">',
'mathml2' => '<!DOCTYPE math PUBLIC "-//W3C//DTD MathML 2.0//EN" "http://www.w3.org/Math/DTD/mathml2/mathml2.dtd">',
'svg10' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.0//EN" "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">',
'svg11' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">',
'svg11-basic' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Basic//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd">',
'svg11-tiny' => '<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1 Tiny//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd">',
'xhtml-math-svg-xh' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-math-svg-sh' => '<!DOCTYPE svg:svg PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">',
'xhtml-rdfa-1' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">',
'xhtml-rdfa-2' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.1//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd">',
];
/**
* Whether to remove the solidus (`/`) character for void HTML elements (e.g. `<input>`)
* for HTML5 compatibility.
*
* Set to:
* `true` - to be HTML5 compatible
* `false` - to be XHTML compatible
*/
public bool $html5 = true;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Exceptions.php | app/Config/Exceptions.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Debug\ExceptionHandler;
use CodeIgniter\Debug\ExceptionHandlerInterface;
use Psr\Log\LogLevel;
use Throwable;
/**
* Setup how the exception handler works.
*/
class Exceptions extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* LOG EXCEPTIONS?
* --------------------------------------------------------------------------
* If true, then exceptions will be logged
* through Services::Log.
*
* Default: true
*/
public bool $log = true;
/**
* --------------------------------------------------------------------------
* DO NOT LOG STATUS CODES
* --------------------------------------------------------------------------
* Any status codes here will NOT be logged if logging is turned on.
* By default, only 404 (Page Not Found) exceptions are ignored.
*
* @var list<int>
*/
public array $ignoreCodes = [404];
/**
* --------------------------------------------------------------------------
* Error Views Path
* --------------------------------------------------------------------------
* This is the path to the directory that contains the 'cli' and 'html'
* directories that hold the views used to generate errors.
*
* Default: APPPATH.'Views/errors'
*/
public string $errorViewPath = APPPATH . 'Views/errors';
/**
* --------------------------------------------------------------------------
* HIDE FROM DEBUG TRACE
* --------------------------------------------------------------------------
* Any data that you would like to hide from the debug trace.
* In order to specify 2 levels, use "/" to separate.
* ex. ['server', 'setup/password', 'secret_token']
*
* @var list<string>
*/
public array $sensitiveDataInTrace = [];
/**
* --------------------------------------------------------------------------
* WHETHER TO THROW AN EXCEPTION ON DEPRECATED ERRORS
* --------------------------------------------------------------------------
* If set to `true`, DEPRECATED errors are only logged and no exceptions are
* thrown. This option also works for user deprecations.
*/
public bool $logDeprecations = true;
/**
* --------------------------------------------------------------------------
* LOG LEVEL THRESHOLD FOR DEPRECATIONS
* --------------------------------------------------------------------------
* If `$logDeprecations` is set to `true`, this sets the log level
* to which the deprecation will be logged. This should be one of the log
* levels recognized by PSR-3.
*
* The related `Config\Logger::$threshold` should be adjusted, if needed,
* to capture logging the deprecations.
*/
public string $deprecationLogLevel = LogLevel::WARNING;
/*
* DEFINE THE HANDLERS USED
* --------------------------------------------------------------------------
* Given the HTTP status code, returns exception handler that
* should be used to deal with this error. By default, it will run CodeIgniter's
* default handler and display the error information in the expected format
* for CLI, HTTP, or AJAX requests, as determined by is_cli() and the expected
* response format.
*
* Custom handlers can be returned if you want to handle one or more specific
* error codes yourself like:
*
* if (in_array($statusCode, [400, 404, 500])) {
* return new \App\Libraries\MyExceptionHandler();
* }
* if ($exception instanceOf PageNotFoundException) {
* return new \App\Libraries\MyExceptionHandler();
* }
*/
public function handler(int $statusCode, Throwable $exception): ExceptionHandlerInterface
{
return new ExceptionHandler($this);
}
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Images.php | app/Config/Images.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Images\Handlers\GDHandler;
use CodeIgniter\Images\Handlers\ImageMagickHandler;
class Images extends BaseConfig
{
/**
* Default handler used if no other handler is specified.
*/
public string $defaultHandler = 'gd';
/**
* The path to the image library.
* Required for ImageMagick, GraphicsMagick, or NetPBM.
*/
public string $libraryPath = '/usr/local/bin/convert';
/**
* The available handler classes.
*
* @var array<string, string>
*/
public array $handlers = [
'gd' => GDHandler::class,
'imagick' => ImageMagickHandler::class,
];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Generators.php | app/Config/Generators.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Generators extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Generator Commands' Views
* --------------------------------------------------------------------------
*
* This array defines the mapping of generator commands to the view files
* they are using. If you need to customize them for your own, copy these
* view files in your own folder and indicate the location here.
*
* You will notice that the views have special placeholders enclosed in
* curly braces `{...}`. These placeholders are used internally by the
* generator commands in processing replacements, thus you are warned
* not to delete them or modify the names. If you will do so, you may
* end up disrupting the scaffolding process and throw errors.
*
* YOU HAVE BEEN WARNED!
*
* @var array<string, array<string, string>|string>
*/
public array $views = [
'make:cell' => [
'class' => 'CodeIgniter\Commands\Generators\Views\cell.tpl.php',
'view' => 'CodeIgniter\Commands\Generators\Views\cell_view.tpl.php',
],
'make:command' => 'CodeIgniter\Commands\Generators\Views\command.tpl.php',
'make:config' => 'CodeIgniter\Commands\Generators\Views\config.tpl.php',
'make:controller' => 'CodeIgniter\Commands\Generators\Views\controller.tpl.php',
'make:entity' => 'CodeIgniter\Commands\Generators\Views\entity.tpl.php',
'make:filter' => 'CodeIgniter\Commands\Generators\Views\filter.tpl.php',
'make:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
'make:model' => 'CodeIgniter\Commands\Generators\Views\model.tpl.php',
'make:seeder' => 'CodeIgniter\Commands\Generators\Views\seeder.tpl.php',
'make:validation' => 'CodeIgniter\Commands\Generators\Views\validation.tpl.php',
'session:migration' => 'CodeIgniter\Commands\Generators\Views\migration.tpl.php',
];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Filters.php | app/Config/Filters.php | <?php
namespace Config;
use CodeIgniter\Config\Filters as BaseFilters;
use CodeIgniter\Filters\Cors;
use CodeIgniter\Filters\CSRF;
use CodeIgniter\Filters\DebugToolbar;
use CodeIgniter\Filters\ForceHTTPS;
use CodeIgniter\Filters\Honeypot;
use CodeIgniter\Filters\InvalidChars;
use CodeIgniter\Filters\PageCache;
use CodeIgniter\Filters\PerformanceMetrics;
use CodeIgniter\Filters\SecureHeaders;
class Filters extends BaseFilters
{
/**
* Configures aliases for Filter classes to
* make reading things nicer and simpler.
*
* @var array<string, class-string|list<class-string>>
*
* [filter_name => classname]
* or [filter_name => [classname1, classname2, ...]]
*/
public array $aliases = [
'csrf' => CSRF::class,
'toolbar' => DebugToolbar::class,
'honeypot' => Honeypot::class,
'invalidchars' => InvalidChars::class,
'secureheaders' => SecureHeaders::class,
'cors' => Cors::class,
'forcehttps' => ForceHTTPS::class,
'pagecache' => PageCache::class,
'performance' => PerformanceMetrics::class,
];
/**
* List of special required filters.
*
* The filters listed here are special. They are applied before and after
* other kinds of filters, and always applied even if a route does not exist.
*
* Filters set by default provide framework functionality. If removed,
* those functions will no longer work.
*
* @see https://codeigniter.com/user_guide/incoming/filters.html#provided-filters
*
* @var array{before: list<string>, after: list<string>}
*/
public array $required = [
'before' => [
'forcehttps', // Force Global Secure Requests
'pagecache', // Web Page Caching
],
'after' => [
'pagecache', // Web Page Caching
'performance', // Performance Metrics
'toolbar', // Debug Toolbar
],
];
/**
* List of filter aliases that are always
* applied before and after every request.
*
* @var array{
* before: array<string, array{except: list<string>|string}>|list<string>,
* after: array<string, array{except: list<string>|string}>|list<string>
* }
*/
public array $globals = [
'before' => [
// 'honeypot',
// 'csrf',
// 'invalidchars',
],
'after' => [
// 'honeypot',
// 'secureheaders',
],
];
/**
* List of filter aliases that works on a
* particular HTTP method (GET, POST, etc.).
*
* Example:
* 'POST' => ['foo', 'bar']
*
* If you use this, you should disable auto-routing because auto-routing
* permits any HTTP method to access a controller. Accessing the controller
* with a method you don't expect could bypass the filter.
*
* @var array<string, list<string>>
*/
public array $methods = [];
/**
* List of filter aliases that should run on any
* before or after URI patterns.
*
* Example:
* 'isLoggedIn' => ['before' => ['account/*', 'profiles/*']]
*
* @var array<string, array<string, list<string>>>
*/
public array $filters = [];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Optimize.php | app/Config/Optimize.php | <?php
namespace Config;
/**
* Optimization Configuration.
*
* NOTE: This class does not extend BaseConfig for performance reasons.
* So you cannot replace the property values with Environment Variables.
*/
class Optimize
{
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/factories.html#config-caching
*/
public bool $configCacheEnabled = false;
/**
* --------------------------------------------------------------------------
* Config Caching
* --------------------------------------------------------------------------
*
* @see https://codeigniter.com/user_guide/concepts/autoloader.html#file-locator-caching
*/
public bool $locatorCacheEnabled = false;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/UserAgents.php | app/Config/UserAgents.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* -------------------------------------------------------------------
* User Agents
* -------------------------------------------------------------------
*
* This file contains four arrays of user agent data. It is used by the
* User Agent Class to help identify browser, platform, robot, and
* mobile device data. The array keys are used to identify the device
* and the array values are used to set the actual name of the item.
*/
class UserAgents extends BaseConfig
{
/**
* -------------------------------------------------------------------
* OS Platforms
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $platforms = [
'windows nt 10.0' => 'Windows 10',
'windows nt 6.3' => 'Windows 8.1',
'windows nt 6.2' => 'Windows 8',
'windows nt 6.1' => 'Windows 7',
'windows nt 6.0' => 'Windows Vista',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.1' => 'Windows XP',
'windows nt 5.0' => 'Windows 2000',
'windows nt 4.0' => 'Windows NT 4.0',
'winnt4.0' => 'Windows NT 4.0',
'winnt 4.0' => 'Windows NT',
'winnt' => 'Windows NT',
'windows 98' => 'Windows 98',
'win98' => 'Windows 98',
'windows 95' => 'Windows 95',
'win95' => 'Windows 95',
'windows phone' => 'Windows Phone',
'windows' => 'Unknown Windows OS',
'android' => 'Android',
'blackberry' => 'BlackBerry',
'iphone' => 'iOS',
'ipad' => 'iOS',
'ipod' => 'iOS',
'os x' => 'Mac OS X',
'ppc mac' => 'Power PC Mac',
'freebsd' => 'FreeBSD',
'ppc' => 'Macintosh',
'linux' => 'Linux',
'debian' => 'Debian',
'sunos' => 'Sun Solaris',
'beos' => 'BeOS',
'apachebench' => 'ApacheBench',
'aix' => 'AIX',
'irix' => 'Irix',
'osf' => 'DEC OSF',
'hp-ux' => 'HP-UX',
'netbsd' => 'NetBSD',
'bsdi' => 'BSDi',
'openbsd' => 'OpenBSD',
'gnu' => 'GNU/Linux',
'unix' => 'Unknown Unix OS',
'symbian' => 'Symbian OS',
];
/**
* -------------------------------------------------------------------
* Browsers
* -------------------------------------------------------------------
*
* The order of this array should NOT be changed. Many browsers return
* multiple browser types so we want to identify the subtype first.
*
* @var array<string, string>
*/
public array $browsers = [
'OPR' => 'Opera',
'Flock' => 'Flock',
'Edge' => 'Spartan',
'Edg' => 'Edge',
'Chrome' => 'Chrome',
// Opera 10+ always reports Opera/9.80 and appends Version/<real version> to the user agent string
'Opera.*?Version' => 'Opera',
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => 'Internet Explorer',
'Trident.* rv' => 'Internet Explorer',
'Shiira' => 'Shiira',
'Firefox' => 'Firefox',
'Chimera' => 'Chimera',
'Phoenix' => 'Phoenix',
'Firebird' => 'Firebird',
'Camino' => 'Camino',
'Netscape' => 'Netscape',
'OmniWeb' => 'OmniWeb',
'Safari' => 'Safari',
'Mozilla' => 'Mozilla',
'Konqueror' => 'Konqueror',
'icab' => 'iCab',
'Lynx' => 'Lynx',
'Links' => 'Links',
'hotjava' => 'HotJava',
'amaya' => 'Amaya',
'IBrowse' => 'IBrowse',
'Maxthon' => 'Maxthon',
'Ubuntu' => 'Ubuntu Web Browser',
'Vivaldi' => 'Vivaldi',
];
/**
* -------------------------------------------------------------------
* Mobiles
* -------------------------------------------------------------------
*
* @var array<string, string>
*/
public array $mobiles = [
// legacy array, old values commented out
'mobileexplorer' => 'Mobile Explorer',
// 'openwave' => 'Open Wave',
// 'opera mini' => 'Opera Mini',
// 'operamini' => 'Opera Mini',
// 'elaine' => 'Palm',
'palmsource' => 'Palm',
// 'digital paths' => 'Palm',
// 'avantgo' => 'Avantgo',
// 'xiino' => 'Xiino',
'palmscape' => 'Palmscape',
// 'nokia' => 'Nokia',
// 'ericsson' => 'Ericsson',
// 'blackberry' => 'BlackBerry',
// 'motorola' => 'Motorola'
// Phones and Manufacturers
'motorola' => 'Motorola',
'nokia' => 'Nokia',
'palm' => 'Palm',
'iphone' => 'Apple iPhone',
'ipad' => 'iPad',
'ipod' => 'Apple iPod Touch',
'sony' => 'Sony Ericsson',
'ericsson' => 'Sony Ericsson',
'blackberry' => 'BlackBerry',
'cocoon' => 'O2 Cocoon',
'blazer' => 'Treo',
'lg' => 'LG',
'amoi' => 'Amoi',
'xda' => 'XDA',
'mda' => 'MDA',
'vario' => 'Vario',
'htc' => 'HTC',
'samsung' => 'Samsung',
'sharp' => 'Sharp',
'sie-' => 'Siemens',
'alcatel' => 'Alcatel',
'benq' => 'BenQ',
'ipaq' => 'HP iPaq',
'mot-' => 'Motorola',
'playstation portable' => 'PlayStation Portable',
'playstation 3' => 'PlayStation 3',
'playstation vita' => 'PlayStation Vita',
'hiptop' => 'Danger Hiptop',
'nec-' => 'NEC',
'panasonic' => 'Panasonic',
'philips' => 'Philips',
'sagem' => 'Sagem',
'sanyo' => 'Sanyo',
'spv' => 'SPV',
'zte' => 'ZTE',
'sendo' => 'Sendo',
'nintendo dsi' => 'Nintendo DSi',
'nintendo ds' => 'Nintendo DS',
'nintendo 3ds' => 'Nintendo 3DS',
'wii' => 'Nintendo Wii',
'open web' => 'Open Web',
'openweb' => 'OpenWeb',
// Operating Systems
'android' => 'Android',
'symbian' => 'Symbian',
'SymbianOS' => 'SymbianOS',
'elaine' => 'Palm',
'series60' => 'Symbian S60',
'windows ce' => 'Windows CE',
// Browsers
'obigo' => 'Obigo',
'netfront' => 'Netfront Browser',
'openwave' => 'Openwave Browser',
'mobilexplorer' => 'Mobile Explorer',
'operamini' => 'Opera Mini',
'opera mini' => 'Opera Mini',
'opera mobi' => 'Opera Mobile',
'fennec' => 'Firefox Mobile',
// Other
'digital paths' => 'Digital Paths',
'avantgo' => 'AvantGo',
'xiino' => 'Xiino',
'novarra' => 'Novarra Transcoder',
'vodafone' => 'Vodafone',
'docomo' => 'NTT DoCoMo',
'o2' => 'O2',
// Fallback
'mobile' => 'Generic Mobile',
'wireless' => 'Generic Mobile',
'j2me' => 'Generic Mobile',
'midp' => 'Generic Mobile',
'cldc' => 'Generic Mobile',
'up.link' => 'Generic Mobile',
'up.browser' => 'Generic Mobile',
'smartphone' => 'Generic Mobile',
'cellphone' => 'Generic Mobile',
];
/**
* -------------------------------------------------------------------
* Robots
* -------------------------------------------------------------------
*
* There are hundred of bots but these are the most common.
*
* @var array<string, string>
*/
public array $robots = [
'googlebot' => 'Googlebot',
'msnbot' => 'MSNBot',
'baiduspider' => 'Baiduspider',
'bingbot' => 'Bing',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'ask jeeves' => 'Ask Jeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos',
'yandex' => 'YandexBot',
'mediapartners-google' => 'MediaPartners Google',
'CRAZYWEBCRAWLER' => 'Crazy Webcrawler',
'adsbot-google' => 'AdsBot Google',
'feedfetcher-google' => 'Feedfetcher Google',
'curious george' => 'Curious George',
'ia_archiver' => 'Alexa Crawler',
'MJ12bot' => 'Majestic-12',
'Uptimebot' => 'Uptimebot',
];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Email.php | app/Config/Email.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Email extends BaseConfig
{
public string $fromEmail = '';
public string $fromName = '';
public string $recipients = '';
/**
* The "user agent"
*/
public string $userAgent = 'CodeIgniter';
/**
* The mail sending protocol: mail, sendmail, smtp
*/
public string $protocol = 'mail';
/**
* The server path to Sendmail.
*/
public string $mailPath = '/usr/sbin/sendmail';
/**
* SMTP Server Hostname
*/
public string $SMTPHost = '';
/**
* SMTP Username
*/
public string $SMTPUser = '';
/**
* SMTP Password
*/
public string $SMTPPass = '';
/**
* SMTP Port
*/
public int $SMTPPort = 25;
/**
* SMTP Timeout (in seconds)
*/
public int $SMTPTimeout = 5;
/**
* Enable persistent SMTP connections
*/
public bool $SMTPKeepAlive = false;
/**
* SMTP Encryption.
*
* @var string '', 'tls' or 'ssl'. 'tls' will issue a STARTTLS command
* to the server. 'ssl' means implicit SSL. Connection on port
* 465 should set this to ''.
*/
public string $SMTPCrypto = 'tls';
/**
* Enable word-wrap
*/
public bool $wordWrap = true;
/**
* Character count to wrap at
*/
public int $wrapChars = 76;
/**
* Type of mail, either 'text' or 'html'
*/
public string $mailType = 'text';
/**
* Character set (utf-8, iso-8859-1, etc.)
*/
public string $charset = 'UTF-8';
/**
* Whether to validate the email address
*/
public bool $validate = false;
/**
* Email Priority. 1 = highest. 5 = lowest. 3 = normal
*/
public int $priority = 3;
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $CRLF = "\r\n";
/**
* Newline character. (Use “\r\n” to comply with RFC 822)
*/
public string $newline = "\r\n";
/**
* Enable BCC Batch Mode.
*/
public bool $BCCBatchMode = false;
/**
* Number of emails in each BCC batch
*/
public int $BCCBatchSize = 200;
/**
* Enable notify message from server
*/
public bool $DSN = false;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/App.php | app/Config/App.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class App extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Base Site URL
* --------------------------------------------------------------------------
*
* URL to your CodeIgniter root. Typically, this will be your base URL,
* WITH a trailing slash:
*
* E.g., http://example.com/
*/
public string $baseURL = 'http://localhost/jobe/';
/**
* Allowed Hostnames in the Site URL other than the hostname in the baseURL.
* If you want to accept multiple Hostnames, set this.
*
* E.g.,
* When your site URL ($baseURL) is 'http://example.com/', and your site
* also accepts 'http://media.example.com/' and 'http://accounts.example.com/':
* ['media.example.com', 'accounts.example.com']
*
* @var list<string>
*/
public array $allowedHostnames = [];
/**
* --------------------------------------------------------------------------
* Index File
* --------------------------------------------------------------------------
*
* Typically, this will be your `index.php` file, unless you've renamed it to
* something else. If you have configured your web server to remove this file
* from your site URIs, set this variable to an empty string.
*/
public string $indexPage = '';
/**
* --------------------------------------------------------------------------
* URI PROTOCOL
* --------------------------------------------------------------------------
*
* This item determines which server global should be used to retrieve the
* URI string. The default setting of 'REQUEST_URI' works for most servers.
* If your links do not seem to work, try one of the other delicious flavors:
*
* 'REQUEST_URI': Uses $_SERVER['REQUEST_URI']
* 'QUERY_STRING': Uses $_SERVER['QUERY_STRING']
* 'PATH_INFO': Uses $_SERVER['PATH_INFO']
*
* WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
public string $uriProtocol = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible.
|
| By default, only these are allowed: `a-z 0-9~%.:_-`
|
| Set an empty string to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be used as: '/\A[<permittedURIChars>]+\z/iu'
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
public string $permittedURIChars = 'a-z 0-9~%.:_\-';
/**
* --------------------------------------------------------------------------
* Default Locale
* --------------------------------------------------------------------------
*
* The Locale roughly represents the language and location that your visitor
* is viewing the site from. It affects the language strings and other
* strings (like currency markers, numbers, etc), that your program
* should run under for this request.
*/
public string $defaultLocale = 'en';
/**
* --------------------------------------------------------------------------
* Negotiate Locale
* --------------------------------------------------------------------------
*
* If true, the current Request object will automatically determine the
* language to use based on the value of the Accept-Language header.
*
* If false, no automatic detection will be performed.
*/
public bool $negotiateLocale = false;
/**
* --------------------------------------------------------------------------
* Supported Locales
* --------------------------------------------------------------------------
*
* If $negotiateLocale is true, this array lists the locales supported
* by the application in descending order of priority. If no match is
* found, the first locale will be used.
*
* IncomingRequest::setLocale() also uses this list.
*
* @var list<string>
*/
public array $supportedLocales = ['en'];
/**
* --------------------------------------------------------------------------
* Application Timezone
* --------------------------------------------------------------------------
*
* The default timezone that will be used in your application to display
* dates with the date helper, and can be retrieved through app_timezone()
*
* @see https://www.php.net/manual/en/timezones.php for list of timezones
* supported by PHP.
*/
public string $appTimezone = 'UTC';
/**
* --------------------------------------------------------------------------
* Default Character Set
* --------------------------------------------------------------------------
*
* This determines which character set is used by default in various methods
* that require a character set to be provided.
*
* @see http://php.net/htmlspecialchars for a list of supported charsets.
*/
public string $charset = 'UTF-8';
/**
* --------------------------------------------------------------------------
* Force Global Secure Requests
* --------------------------------------------------------------------------
*
* If true, this will force every request made to this application to be
* made via a secure connection (HTTPS). If the incoming request is not
* secure, the user will be redirected to a secure version of the page
* and the HTTP Strict Transport Security (HSTS) header will be set.
*/
public bool $forceGlobalSecureRequests = false;
/**
* --------------------------------------------------------------------------
* Reverse Proxy IPs
* --------------------------------------------------------------------------
*
* If your server is behind a reverse proxy, you must whitelist the proxy
* IP addresses from which CodeIgniter should trust headers such as
* X-Forwarded-For or Client-IP in order to properly identify
* the visitor's IP address.
*
* You need to set a proxy IP address or IP address with subnets and
* the HTTP header for the client IP address.
*
* Here are some examples:
* [
* '10.0.1.200' => 'X-Forwarded-For',
* '192.168.5.0/24' => 'X-Real-IP',
* ]
*
* @var array<string, string>
*/
public array $proxyIPs = [];
/**
* --------------------------------------------------------------------------
* Content Security Policy
* --------------------------------------------------------------------------
*
* Enables the Response's Content Secure Policy to restrict the sources that
* can be used for images, scripts, CSS files, audio, video, etc. If enabled,
* the Response object will populate default values for the policy from the
* `ContentSecurityPolicy.php` file. Controllers can always add to those
* restrictions at run time.
*
* For a better understanding of CSP, see these documents:
*
* @see http://www.html5rocks.com/en/tutorials/security/content-security-policy/
* @see http://www.w3.org/TR/CSP/
*/
public bool $CSPEnabled = false;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Kint.php | app/Config/Kint.php | <?php
namespace Config;
use Kint\Parser\ConstructablePluginInterface;
use Kint\Renderer\Rich\TabPluginInterface;
use Kint\Renderer\Rich\ValuePluginInterface;
/**
* --------------------------------------------------------------------------
* Kint
* --------------------------------------------------------------------------
*
* We use Kint's `RichRenderer` and `CLIRenderer`. This area contains options
* that you can set to customize how Kint works for you.
*
* @see https://kint-php.github.io/kint/ for details on these settings.
*/
class Kint
{
/*
|--------------------------------------------------------------------------
| Global Settings
|--------------------------------------------------------------------------
*/
/**
* @var list<class-string<ConstructablePluginInterface>|ConstructablePluginInterface>|null
*/
public $plugins;
public int $maxDepth = 6;
public bool $displayCalledFrom = true;
public bool $expanded = false;
/*
|--------------------------------------------------------------------------
| RichRenderer Settings
|--------------------------------------------------------------------------
*/
public string $richTheme = 'aante-light.css';
public bool $richFolder = false;
/**
* @var array<string, class-string<ValuePluginInterface>>|null
*/
public $richObjectPlugins;
/**
* @var array<string, class-string<TabPluginInterface>>|null
*/
public $richTabPlugins;
/*
|--------------------------------------------------------------------------
| CLI Settings
|--------------------------------------------------------------------------
*/
public bool $cliColors = true;
public bool $cliForceUTF8 = false;
public bool $cliDetectWidth = true;
public int $cliMinWidth = 40;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Constants.php | app/Config/Constants.php | <?php
/*
| --------------------------------------------------------------------
| App Namespace
| --------------------------------------------------------------------
|
| This defines the default Namespace that is used throughout
| CodeIgniter to refer to the Application directory. Change
| this constant to change the namespace that all application
| classes should use.
|
| NOTE: changing this will require manually modifying the
| existing namespaces of App\* namespaced-classes.
*/
defined('APP_NAMESPACE') || define('APP_NAMESPACE', 'App');
/*
| --------------------------------------------------------------------------
| Composer Path
| --------------------------------------------------------------------------
|
| The path that Composer's autoload file is expected to live. By default,
| the vendor folder is in the Root directory, but you can customize that here.
*/
defined('COMPOSER_PATH') || define('COMPOSER_PATH', ROOTPATH . 'vendor/autoload.php');
/*
|--------------------------------------------------------------------------
| Timing Constants
|--------------------------------------------------------------------------
|
| Provide simple ways to work with the myriad of PHP functions that
| require information to be in seconds.
*/
defined('SECOND') || define('SECOND', 1);
defined('MINUTE') || define('MINUTE', 60);
defined('HOUR') || define('HOUR', 3600);
defined('DAY') || define('DAY', 86400);
defined('WEEK') || define('WEEK', 604800);
defined('MONTH') || define('MONTH', 2_592_000);
defined('YEAR') || define('YEAR', 31_536_000);
defined('DECADE') || define('DECADE', 315_360_000);
/*
| --------------------------------------------------------------------------
| Exit Status Codes
| --------------------------------------------------------------------------
|
| Used to indicate the conditions under which the script is exit()ing.
| While there is no universal standard for error codes, there are some
| broad conventions. Three such conventions are mentioned below, for
| those who wish to make use of them. The CodeIgniter defaults were
| chosen for the least overlap with these conventions, while still
| leaving room for others to be defined in future versions and user
| applications.
|
| The three main conventions used for determining exit status codes
| are as follows:
|
| Standard C/C++ Library (stdlibc):
| http://www.gnu.org/software/libc/manual/html_node/Exit-Status.html
| (This link also contains other GNU-specific conventions)
| BSD sysexits.h:
| http://www.gsp.com/cgi-bin/man.cgi?section=3&topic=sysexits
| Bash scripting:
| http://tldp.org/LDP/abs/html/exitcodes.html
|
*/
defined('EXIT_SUCCESS') || define('EXIT_SUCCESS', 0); // no errors
defined('EXIT_ERROR') || define('EXIT_ERROR', 1); // generic error
defined('EXIT_CONFIG') || define('EXIT_CONFIG', 3); // configuration error
defined('EXIT_UNKNOWN_FILE') || define('EXIT_UNKNOWN_FILE', 4); // file not found
defined('EXIT_UNKNOWN_CLASS') || define('EXIT_UNKNOWN_CLASS', 5); // unknown class
defined('EXIT_UNKNOWN_METHOD') || define('EXIT_UNKNOWN_METHOD', 6); // unknown class member
defined('EXIT_USER_INPUT') || define('EXIT_USER_INPUT', 7); // invalid user input
defined('EXIT_DATABASE') || define('EXIT_DATABASE', 8); // database error
defined('EXIT__AUTO_MIN') || define('EXIT__AUTO_MIN', 9); // lowest automatically-assigned error code
defined('EXIT__AUTO_MAX') || define('EXIT__AUTO_MAX', 125); // highest automatically-assigned error code
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Honeypot.php | app/Config/Honeypot.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Honeypot extends BaseConfig
{
/**
* Makes Honeypot visible or not to human
*/
public bool $hidden = true;
/**
* Honeypot Label Content
*/
public string $label = 'Fill This Field';
/**
* Honeypot Field Name
*/
public string $name = 'honeypot';
/**
* Honeypot HTML Template
*/
public string $template = '<label>{label}</label><input type="text" name="{name}" value="">';
/**
* Honeypot container
*
* If you enabled CSP, you can remove `style="display:none"`.
*/
public string $container = '<div style="display:none">{template}</div>';
/**
* The id attribute for Honeypot container tag
*
* Used when CSP is enabled.
*/
public string $containerId = 'hpc';
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Security.php | app/Config/Security.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Security extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* CSRF Protection Method
* --------------------------------------------------------------------------
*
* Protection Method for Cross Site Request Forgery protection.
*
* @var string 'cookie' or 'session'
*/
public string $csrfProtection = 'cookie';
/**
* --------------------------------------------------------------------------
* CSRF Token Randomization
* --------------------------------------------------------------------------
*
* Randomize the CSRF Token for added security.
*/
public bool $tokenRandomize = false;
/**
* --------------------------------------------------------------------------
* CSRF Token Name
* --------------------------------------------------------------------------
*
* Token name for Cross Site Request Forgery protection.
*/
public string $tokenName = 'csrf_test_name';
/**
* --------------------------------------------------------------------------
* CSRF Header Name
* --------------------------------------------------------------------------
*
* Header name for Cross Site Request Forgery protection.
*/
public string $headerName = 'X-CSRF-TOKEN';
/**
* --------------------------------------------------------------------------
* CSRF Cookie Name
* --------------------------------------------------------------------------
*
* Cookie name for Cross Site Request Forgery protection.
*/
public string $cookieName = 'csrf_cookie_name';
/**
* --------------------------------------------------------------------------
* CSRF Expires
* --------------------------------------------------------------------------
*
* Expiration time for Cross Site Request Forgery protection cookie.
*
* Defaults to two hours (in seconds).
*/
public int $expires = 7200;
/**
* --------------------------------------------------------------------------
* CSRF Regenerate
* --------------------------------------------------------------------------
*
* Regenerate CSRF Token on every submission.
*/
public bool $regenerate = true;
/**
* --------------------------------------------------------------------------
* CSRF Redirect
* --------------------------------------------------------------------------
*
* Redirect to previous page with error on failure.
*
* @see https://codeigniter4.github.io/userguide/libraries/security.html#redirection-on-failure
*/
public bool $redirect = (ENVIRONMENT === 'production');
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Modules.php | app/Config/Modules.php | <?php
namespace Config;
use CodeIgniter\Modules\Modules as BaseModules;
/**
* Modules Configuration.
*
* NOTE: This class is required prior to Autoloader instantiation,
* and does not extend BaseConfig.
*/
class Modules extends BaseModules
{
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all elements listed in
* $aliases below. If false, no auto-discovery will happen at all,
* giving a slight performance boost.
*
* @var bool
*/
public $enabled = true;
/**
* --------------------------------------------------------------------------
* Enable Auto-Discovery Within Composer Packages?
* --------------------------------------------------------------------------
*
* If true, then auto-discovery will happen across all namespaces loaded
* by Composer, as well as the namespaces configured locally.
*
* @var bool
*/
public $discoverInComposer = true;
/**
* The Composer package list for Auto-Discovery
* This setting is optional.
*
* E.g.:
* [
* 'only' => [
* // List up all packages to auto-discover
* 'codeigniter4/shield',
* ],
* ]
* or
* [
* 'exclude' => [
* // List up packages to exclude.
* 'pestphp/pest',
* ],
* ]
*
* @var array{only?: list<string>, exclude?: list<string>}
*/
public $composerPackages = [];
/**
* --------------------------------------------------------------------------
* Auto-Discovery Rules
* --------------------------------------------------------------------------
*
* Aliases list of all discovery classes that will be active and used during
* the current application request.
*
* If it is not listed, only the base application elements will be used.
*
* @var list<string>
*/
public $aliases = [
'events',
'filters',
'registrars',
'routes',
'services',
];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Routes.php | app/Config/Routes.php | <?php
use CodeIgniter\Router\RouteCollection;
/**
* @var RouteCollection $routes
*
$routes->get('jobe/languages/', 'Languages::get');
$routes->get('jobe/languages', 'Languages::get');
$routes->post('jobe/runs', 'Runs::post');
$routes->put('jobe/files/(:alphanum)', 'Files::put/$1');
$routes->head('jobe/files/(:alphanum)', 'Files::head/$1');
*/
/*
Support legacy URIs
*/
$routes->get('/restapi/languages/', 'Languages::get');
$routes->get('/restapi/languages', 'Languages::get');
$routes->post('/restapi/runs', 'Runs::post');
$routes->put('/restapi/files/(:alphanum)', 'Files::put/$1');
$routes->head('/restapi/files/(:alphanum)', 'Files::head/$1');
$routes->options('(:any)', '', ['filter' => 'cors']);
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Publisher.php | app/Config/Publisher.php | <?php
namespace Config;
use CodeIgniter\Config\Publisher as BasePublisher;
/**
* Publisher Configuration
*
* Defines basic security restrictions for the Publisher class
* to prevent abuse by injecting malicious files into a project.
*/
class Publisher extends BasePublisher
{
/**
* A list of allowed destinations with a (pseudo-)regex
* of allowed files for each destination.
* Attempts to publish to directories not in this list will
* result in a PublisherException. Files that do no fit the
* pattern will cause copy/merge to fail.
*
* @var array<string, string>
*/
public $restrictions = [
ROOTPATH => '*',
FCPATH => '#\.(s?css|js|map|html?|xml|json|webmanifest|ttf|eot|woff2?|gif|jpe?g|tiff?|png|webp|bmp|ico|svg)$#i',
];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Format.php | app/Config/Format.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Format\JSONFormatter;
use CodeIgniter\Format\XMLFormatter;
class Format extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Available Response Formats
* --------------------------------------------------------------------------
*
* When you perform content negotiation with the request, these are the
* available formats that your application supports. This is currently
* only used with the API\ResponseTrait. A valid Formatter must exist
* for the specified format.
*
* These formats are only checked when the data passed to the respond()
* method is an array.
*
* @var list<string>
*/
public array $supportedResponseFormats = [
'application/json',
'application/xml', // machine-readable XML
'text/xml', // human-readable XML
];
/**
* --------------------------------------------------------------------------
* Formatters
* --------------------------------------------------------------------------
*
* Lists the class to use to format responses with of a particular type.
* For each mime type, list the class that should be used. Formatters
* can be retrieved through the getFormatter() method.
*
* @var array<string, string>
*/
public array $formatters = [
'application/json' => JSONFormatter::class,
'application/xml' => XMLFormatter::class,
'text/xml' => XMLFormatter::class,
];
/**
* --------------------------------------------------------------------------
* Formatters Options
* --------------------------------------------------------------------------
*
* Additional Options to adjust default formatters behaviour.
* For each mime type, list the additional options that should be used.
*
* @var array<string, int>
*/
public array $formatterOptions = [
'application/json' => JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES,
'application/xml' => 0,
'text/xml' => 0,
];
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Cookie.php | app/Config/Cookie.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use DateTimeInterface;
class Cookie extends BaseConfig
{
/**
* --------------------------------------------------------------------------
* Cookie Prefix
* --------------------------------------------------------------------------
*
* Set a cookie name prefix if you need to avoid collisions.
*/
public string $prefix = '';
/**
* --------------------------------------------------------------------------
* Cookie Expires Timestamp
* --------------------------------------------------------------------------
*
* Default expires timestamp for cookies. Setting this to `0` will mean the
* cookie will not have the `Expires` attribute and will behave as a session
* cookie.
*
* @var DateTimeInterface|int|string
*/
public $expires = 0;
/**
* --------------------------------------------------------------------------
* Cookie Path
* --------------------------------------------------------------------------
*
* Typically will be a forward slash.
*/
public string $path = '/';
/**
* --------------------------------------------------------------------------
* Cookie Domain
* --------------------------------------------------------------------------
*
* Set to `.your-domain.com` for site-wide cookies.
*/
public string $domain = '';
/**
* --------------------------------------------------------------------------
* Cookie Secure
* --------------------------------------------------------------------------
*
* Cookie will only be set if a secure HTTPS connection exists.
*/
public bool $secure = false;
/**
* --------------------------------------------------------------------------
* Cookie HTTPOnly
* --------------------------------------------------------------------------
*
* Cookie will only be accessible via HTTP(S) (no JavaScript).
*/
public bool $httponly = true;
/**
* --------------------------------------------------------------------------
* Cookie SameSite
* --------------------------------------------------------------------------
*
* Configure cookie SameSite setting. Allowed values are:
* - None
* - Lax
* - Strict
* - ''
*
* Alternatively, you can use the constant names:
* - `Cookie::SAMESITE_NONE`
* - `Cookie::SAMESITE_LAX`
* - `Cookie::SAMESITE_STRICT`
*
* Defaults to `Lax` for compatibility with modern browsers. Setting `''`
* (empty string) means default SameSite attribute set by browsers (`Lax`)
* will be set on cookies. If set to `None`, `$secure` must also be set.
*
* @var ''|'Lax'|'None'|'Strict'
*/
public string $samesite = 'Lax';
/**
* --------------------------------------------------------------------------
* Cookie Raw
* --------------------------------------------------------------------------
*
* This flag allows setting a "raw" cookie, i.e., its name and value are
* not URL encoded using `rawurlencode()`.
*
* If this is set to `true`, cookie names should be compliant of RFC 2616's
* list of allowed characters.
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#attributes
* @see https://tools.ietf.org/html/rfc2616#section-2.2
*/
public bool $raw = false;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Feature.php | app/Config/Feature.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
/**
* Enable/disable backward compatibility breaking features.
*/
class Feature extends BaseConfig
{
/**
* Use improved new auto routing instead of the legacy version.
*/
public bool $autoRoutesImproved = true;
/**
* Use filter execution order in 4.4 or before.
*/
public bool $oldFilterOrder = false;
/**
* The behavior of `limit(0)` in Query Builder.
*
* If true, `limit(0)` returns all records. (the behavior of 4.4.x or before in version 4.x.)
* If false, `limit(0)` returns no records. (the behavior of 3.1.9 or later in version 3.x.)
*/
public bool $limitZeroAsAll = true;
/**
* Use strict location negotiation.
*
* By default, the locale is selected based on a loose comparison of the language code (ISO 639-1)
* Enabling strict comparison will also consider the region code (ISO 3166-1 alpha-2).
*/
public bool $strictLocaleNegotiation = false;
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
trampgeek/jobe | https://github.com/trampgeek/jobe/blob/cffff99685a78a2e13b47a5288e6fa87a1abe40a/app/Config/Jobe.php | app/Config/Jobe.php | <?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
class Jobe extends BaseConfig
{
/*
|--------------------------------------------------------------------------
| Jobe parameters
|--------------------------------------------------------------------------
|
| This config file contains Jobe-server specific constants.
*/
/**
* API keys.
* If $require_api_keys is true, the array $api_keys is a map from api
* key to allowed rate of requests per hour. A value of 0 means unlimited.
*/
public bool $require_api_keys = false;
public array $api_keys = [
'2AAA7A5415B4A9B394B54BF1D2E9D'=> 60 // 60 runs per hour for Jobe2.
];
/*
| jobe_max_users controls how many jobs can be run by the server at any
| one time. It *must* agree with the number of users with names jobe01,
| jobe02, jobe03 etc (which is how the install script will set things up).
*/
public int $jobe_max_users = 16;
public int $jobe_wait_timeout = 10; // Max number of secs to wait for a free Jobe user.
public int $cputime_upper_limit_secs = 120;
/*
| Clean up path is a semicolon-separated list of directories that are
| writable by all, to be cleaned on completion of a job.
|
*/
public string $clean_up_path = '/tmp;/var/tmp;/var/crash;/run/lock;/var/lock';
public bool $debugging = false; // If True, the workspace folder for a run is not deleted.
/*
| $python3_version is either a full path to the required python interpreter
| or a single token. In the latter case the token is prefixed by /usr/bin/ when
| running Python tasks.
| Warning: if you modify the python3_version configuration you will also need to
| reboot the server or delete the file /tmp/jobe_language_cache_file (which
| might be hidden away in a systemd-private directory, depending on your Linux
| version)
*/
public string $python3_version = 'python3';
/*
|--------------------------------------------------------------------------
| CPU pinning for jobs [Thanks Marcus Klang
|--------------------------------------------------------------------------
|
| This section of the config file controls processor affinity, i.e. pinning
| runguard tasks to a particular CPU core.
|
| The way task are pinned is to use the jobe user id modulo the number of
| cores. Under a load which requires more compute than is available
| this yields linear slowdown for each job. Assigning jobs to a specific
| core yields more predictable behaviour during extreme overallocation.
| This is more significant with machines that have multi-socket CPUs
| which can have larger memory/cache penalites when tasks are transferred
| between cores.
|
| Consider setting jobe_max_users to be a multiple of num_cores, otherwise
| there will be imbalance under 100% job allocation.
|
| Enabling this option restricts each job to a singular core, regardless
| of number of spawned threads. Multiple threads will work fine but they
| cannot run perfectly concurrent, a context switch must occur.
*/
public bool $cpu_pinning_enabled = false;
public int $cpu_pinning_num_cores = 8; // Update to number of server cores
/*
|--------------------------------------------------------------------------
| Extra Java/Javac arguments [Thanks Marcus Klang
|--------------------------------------------------------------------------
|
| This section of the config file adds extra flags to java and javac
|
| Provided examples tells java/javac that there is only 1 core, which
| reduces the number of spawned threads when compiling. This option can be
| used to provide a better experience when many users are using jobe.
*/
public string $javac_extraflags = ''; //'-J-XX:ActiveProcessorCount=1';
public string $java_extraflags = ''; //'-XX:ActiveProcessorCount=1';
}
| php | MIT | cffff99685a78a2e13b47a5288e6fa87a1abe40a | 2026-01-05T05:19:26.518100Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.