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 |
|---|---|---|---|---|---|---|---|---|
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/test/install_test.php | tools/test/install_test.php | <?php
class Install_test extends Spark_test_case {
function test_install_with_version()
{
$clines = $this->capture_buffer_lines(function($cli) {
$cli->execute('install', array('-v1.0', 'example-spark'));
});
$success = (bool) (strpos(end($clines), chr(27) . '[1;36m[ SPARK ]' .
chr(27) . '[0m Spark installed') === 0);
Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark');
$this->assertEquals(true, $success);
}
function test_install_without_version()
{
$clines = $this->capture_buffer_lines(function($cli) {
$cli->execute('install', array('example-spark'));
});
$success = (bool) (strpos(end($clines), chr(27) . '[1;36m[ SPARK ]' .
chr(27) . '[0m Spark installed') === 0);
Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark');
$this->assertEquals(true, $success);
}
function test_install_with_invalid_spark()
{
$clines = $this->capture_buffer_lines(function($cli) {
$cli->execute('install', array('jjks7878erHjhsjdkksj'));
});
$success = (bool) (strpos(end($clines), chr(27) . '[1;31m[ ERROR ]' .
chr(27) . '[0m Unable to find spark') === 0);
Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark');
$this->assertEquals(true, $success);
}
function test_install_with_invalid_spark_version()
{
$clines = $this->capture_buffer_lines(function($cli) {
$cli->execute('install', array('v9.4', 'example-spark'));
});
$success = (bool) (strpos(reset($clines), chr(27) . '[1;31m[ ERROR ]' .
chr(27) . '[0m Uh-oh!') === 0);
Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark');
$this->assertEquals(true, $success);
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/test/search_test.php | tools/test/search_test.php | <?php
class Search_test extends Spark_test_case {
function test_search()
{
$clines = $this->capture_buffer_lines(function($cli) {
$cli->execute('search', array('markdown'));
});
// Less than ideal, I know
$this->assertEquals(array("\033[33mmarkdown\033[0m - A markdown helper for easy parsing of markdown"), $clines);
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/test/remove_test.php | tools/test/remove_test.php | <?php
class Remove_test extends Spark_test_case {
function test_remove_with_version()
{
// Test install with a version specified
$clines = $this->capture_buffer_lines(function($cli) {
$cli->execute('install', array('-v1.0', 'example-spark')); // Spark needs installed first
$cli->execute('remove', array('-v1.0', 'example-spark'));
});
$success = (bool) (strpos(end($clines), chr(27) . '[1;36m[ SPARK ]' . chr(27) . '[0m Spark removed') === 0 && ! is_dir(SPARK_PATH.'/example-spark'));
$this->assertEquals(true, $success);
Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark');
}
function test_remove_without_flags()
{
$clines = $this->capture_buffer_lines(function($cli) {
$cli->execute('install', array('-v1.0', 'example-spark')); // Spark needs installed first
$cli->execute('remove', array('example-spark'));
});
$success = (bool) (strpos(end($clines), chr(27) . '[1;31m[ ERROR ]' . chr(27) . '[0m Please specify') === 0 && is_dir(SPARK_PATH.'/example-spark'));
$this->assertEquals(true, $success);
Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark');
}
function test_remove_with_f_flag()
{
$clines = $this->capture_buffer_lines(function($cli) {
$cli->execute('install', array('-v1.0', 'example-spark')); // Spark needs installed first
$cli->execute('remove', array('-f', 'example-spark'));
});
$success = (bool) (strpos(end($clines), chr(27) . '[1;36m[ SPARK ]' . chr(27) . '[0m Spark removed') === 0 && ! is_dir(SPARK_PATH.'/example-spark'));
$this->assertEquals(true, $success);
Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark');
}
function test_remove_with_invalid_version()
{
$clines = $this->capture_buffer_lines(function($cli) {
$cli->execute('install', array('-v1.0', 'example-spark')); // Spark needs installed first
$cli->execute('remove', array('-v9.4', 'example-spark'));
});
$success = (bool) (strpos(end($clines), chr(27) . '[1;36m[ SPARK ]' . chr(27) . '[0m Looks like that spark isn\'t installed') === 0 && is_dir(SPARK_PATH.'/example-spark'));
$this->assertEquals(true, $success);
Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark');
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/test/lib/bootstrap.php | tools/test/lib/bootstrap.php | <?php
define('SPARK_PATH', __DIR__ . '/test-sparks');
require __DIR__ . '/../../lib/spark/spark_cli.php';
class Spark_test_case extends PHPUnit_Framework_TestCase {
function setUp()
{
$this->source_names[] = 'getsparks.org';
$this->sources = array_map(function($n) {
return new Spark_source($n);
}, $this->source_names);
$this->cli = new Spark_CLI($this->sources);
}
function tearDown()
{
if (is_dir(SPARK_PATH . '/example-spark'))
{
Spark_utils::remove_full_directory(SPARK_PATH . '/example-spark');
}
}
protected function capture_buffer_lines($func) {
ob_start();
$func($this->cli);
$t = ob_get_contents();
ob_end_clean();
if ($t == '') return array(); // empty
return explode("\n", substr($t, 0, count($t) - 2));
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/lib/spark/spark_exception.php | tools/lib/spark/spark_exception.php | <?php
class Spark_exception extends Exception {
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/lib/spark/spark_cli.php | tools/lib/spark/spark_cli.php | <?php
require_once dirname(__FILE__) . '/spark_utils.php';
require_once dirname(__FILE__) . '/spark_exception.php';
require_once dirname(__FILE__) . '/spark_source.php';
define('SPARK_VERSION', '0.0.9');
! defined('SPARK_PATH') AND define('SPARK_PATH', './sparks');
class Spark_CLI {
private static $commands = array(
'help' => 'help',
'install' => 'install',
'list' => 'lister',
'reinstall' => 'reinstall',
'remove' => 'remove',
'search' => 'search',
'sources' => 'sources',
'upgrade-system' => 'upgrade_system',
'version' => 'version',
'' => 'index' // default action
);
function __construct($spark_sources)
{
$this->spark_sources = $spark_sources;
}
function execute($command, $args = array())
{
if (!array_key_exists($command, self::$commands))
{
$this->failtown("Unknown action: $command");
return;
}
try
{
$method = self::$commands[$command];
$this->$method($args);
}
catch (Exception $ex)
{
return $this->failtown($ex->getMessage());
}
}
private function index($args)
{
Spark_utils::line('Spark (v' . SPARK_VERSION . ')');
Spark_utils::line('For help: `php tools/spark help`');
}
private function upgrade_system() {
$tool_dir = dirname(__FILE__) . '/../../';
$tool_dir = realpath($tool_dir);
// Get version data
$source = $this->spark_sources[0];
if (!$source) throw new Spark_exception('No sources listed - unsure how to upgrade');
if (!$source->outdated()) // We have an acceptable version
{
Spark_utils::warning('Spark manager is already up to date');
return;
}
// Build a spark and download it
$data = null;
$data->name = 'Spark Manager';
$data->archive_url = $source->version_data->spark_manager_download_url;
$zip_spark = new Zip_spark($data);
$zip_spark->retrieve();
// Download the new version
// Remove the lib directory and the spark
unlink($tool_dir . '/spark');
Spark_utils::remove_full_directory($tool_dir . '/lib');
// Link up the new version
Spark_utils::full_move($zip_spark->temp_path . '/lib', $tool_dir . '/lib');
@rename($zip_spark->temp_path . '/spark', $tool_dir . '/spark');
@`chmod u+x {$tool_dir}/spark`;
// Tell the user the story of what just happened
Spark_utils::notice('Spark manager has been upgraded to ' . $source->version . '!');
}
// list the installed sparks
private function lister()
{
if (!is_dir(SPARK_PATH)) return; // no directory yet
foreach(scandir(SPARK_PATH) as $item)
{
if (!is_dir(SPARK_PATH . "/$item") || $item[0] == '.') continue;
foreach (scandir(SPARK_PATH . "/$item") as $ver)
{
if (!is_dir(SPARK_PATH . "/$item/$ver") || $ver[0] == '.') continue;
Spark_utils::line("$item ($ver)");
}
}
}
private function version()
{
Spark_utils::line(SPARK_VERSION);
}
private function help()
{
Spark_utils::line('install # Install a spark');
Spark_utils::line('reinstall # Reinstall a spark');
Spark_utils::line('remove # Remove a spark');
Spark_utils::line('list # List installed sparks');
Spark_utils::line('search # Search for a spark');
Spark_utils::line('sources # Display the spark source URL(s)');
Spark_utils::line('upgrade-system # Update Sparks Manager to latest version (does not upgrade any of your installed sparks)');
Spark_utils::line('version # Display the installed spark version');
Spark_utils::line('help # Print This message');
}
private function search($args)
{
$term = implode($args, ' ');
foreach($this->spark_sources as $source)
{
$results = $source->search($term);
foreach ($results as $result)
{
$result_line = "\033[33m$result->name\033[0m - $result->summary";
// only show the source information if there are multiple sources
if (count($this->spark_sources) > 1) $result_line .= " (source: $source->url)";
Spark_utils::line($result_line);
}
}
}
private function sources()
{
foreach($this->spark_sources as $source)
{
Spark_utils::line($source->get_url());
}
}
private function failtown($error_message)
{
Spark_utils::error('Uh-oh!');
Spark_utils::error($error_message);
}
private function remove($args)
{
list($flats, $flags) = $this->prep_args($args);
if (count($flats) != 1)
{
return $this->failtown('Which spark do you want to remove?');
}
$spark_name = $flats[0];
$version = array_key_exists('v', $flags) ? $flags['v'] : null;
// figure out what to remove and make sure its isntalled
$dir_to_remove = SPARK_PATH . ($version == null ? "/$spark_name" : "/$spark_name/$version");
if (!file_exists($dir_to_remove))
{
return Spark_utils::warning('Looks like that spark isn\'t installed');
}
if ($version == null && !array_key_exists('f', $flags))
{
throw new Spark_exception("Please specify a version (spark remove -v1.0.0 foo) or remove all with -f");
}
Spark_utils::notice("Removing $spark_name (" . ($version ? $version : 'ALL') . ") from $dir_to_remove");
if (Spark_utils::remove_full_directory($dir_to_remove, true))
{
Spark_utils::notice('Spark removed successfully!');
}
else
{
Spark_utils::warning('Looks like that spark isn\'t installed');
}
// attempt to clean up - will not remove unless empty
@rmdir(SPARK_PATH . "/$spark_name");
}
private function install($args)
{
list($flats, $flags) = $this->prep_args($args);
if (count($flats) != 1)
{
return $this->failtown('format: `spark install -v1.0.0 name`');
}
$spark_name = $flats[0];
$version = array_key_exists('v', $flags) ? $flags['v'] : 'HEAD';
// retrieve the spark details
foreach ($this->spark_sources as $source)
{
Spark_utils::notice("Retrieving spark detail from " . $source->get_url());
$spark = $source->get_spark_detail($spark_name, $version);
if ($spark != null) break;
}
// did we find the details?
if ($spark == null)
{
throw new Spark_exception("Unable to find spark: $spark_name ($version) in any sources");
}
// verify the spark, and put out warnings if needed
$spark->verify();
// retrieve the spark
Spark_utils::notice("From Downtown! Retrieving spark from " . $spark->location_detail());
$spark->retrieve();
// Install it
$spark->install();
Spark_utils::notice('Spark installed to ' . $spark->installed_path() . ' - You\'re on fire!');
}
private function reinstall($args)
{
list($flats, $flags) = $this->prep_args($args);
if (count($flats) != 1)
{
return $this->failtown('format: `spark reinstall -v1.0.0 name`');
}
$spark_name = $flats[0];
$version = array_key_exists('v', $flags) ? $flags['v'] : null;
if ($version == null && !array_key_exists('f', $flags))
{
throw new Spark_exception("Please specify a version to reinstall, or use -f to remove all versions and install latest.");
}
$this->remove($args);
$this->install($args);
}
/**
* Prepares the command line arguments for use.
*
* Usage:
* list($flats, $flags) = $this->prep_args($args);
*
* @param array the arguments array
* @return array the flats and flags
*/
private function prep_args($args)
{
$flats = array();
$flags = array();
foreach($args as $arg)
{
preg_match('/^(\-?[a-zA-Z])([^\s]*)$/', $arg, $matches);
if (count($matches) != 3) continue;
$matches[0][0] == '-' ? $flags[$matches[1][1]] = $matches[2] : $flats[] = $matches[0];
}
return array($flats, $flags);
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/lib/spark/spark_source.php | tools/lib/spark/spark_source.php | <?php
require_once 'spark_type.php';
require_once 'spark_types/git_spark.php';
require_once 'spark_types/hg_spark.php';
require_once 'spark_types/zip_spark.php';
class Spark_source {
public $url;
public $version_data;
public $version;
function __construct($url)
{
$this->url = $url;
$this->version_data = json_decode(@file_get_contents("http://$this->url/api/system/latest"));
$this->version = $this->version_data->spark_manager;
$this->warn_if_outdated();
}
function get_url()
{
return $this->url;
}
// get details on an individual spark
function get_spark_detail($spark_name, $version = 'HEAD')
{
$json_data = @file_get_contents("http://$this->url/api/packages/$spark_name/versions/$version/spec");
if (!$json_data) return null; // no such spark here
$data = json_decode($json_data);
// if we don't succeed - throw an error
if ($data == null || !$data->success)
{
$message = "Error retrieving spark detail from source: $this->url";
if ($data != null) $message .= " ($data->message)";
throw new Spark_exception($message);
}
// Get the detail for this spark
return $this->get_spark($data->spec);
}
// get details on multiple sparks by search term
function search($term)
{
$json_data = @file_get_contents("http://$this->url/api/packages/search?q=" . urlencode($term));
$data = json_decode($json_data);
// if the data isn't around of success is false, return a warning for this source
if ($data == null || !$data->success)
{
$message = "Error searching source: $this->url";
if ($data != null) $message .= " ($data->message)";
Spark_utils::warning($message);
return array();
}
// Get sparks for each one
$results = array();
foreach($data->results as $data)
{
$results[] = $this->get_spark($data);
}
return $results;
}
private function warn_if_outdated()
{
if ($this->outdated())
{
Spark_utils::warning("Your installed version of spark is outdated (current version: " . $this->outdated() . " / latest: " . $this->version . ")");
Spark_utils::warning("To upgrade now, use `php tools/spark upgrade-system`");
}
}
function outdated() {
// Get the version for this source
if (!$this->version) return; // no version found
// Split versions
list($self_major, $self_minor, $self_patch) = explode('.', SPARK_VERSION);
list($source_major, $source_minor, $source_patch) = explode('.', $this->version);
// Compare
if ($self_major < $source_major ||
$self_major == $source_major && $self_minor < $source_minor ||
$self_major == $source_major && $self_minor == $source_minor && $self_patch < $source_patch)
{
return SPARK_VERSION;
}
}
private function get_spark($data)
{
if ($data->repository_type == 'hg') return Mercurial_spark::get_spark($data);
else if ($data->repository_type == 'git') return Git_spark::get_spark($data);
else if ($data->repository_type == 'zip') return new Zip_spark($data);
else throw new Exception('Unknown repository type: ' . $data->repository_type);
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/lib/spark/spark_type.php | tools/lib/spark/spark_type.php | <?php
class Spark_type {
function __construct($data)
{
$this->data = $data;
$this->name = $this->data->name;
$this->spark_id = property_exists($this->data, 'id') ? $this->data->id : null;
$this->version = property_exists($this->data, 'version') ? $this->data->version : null;
$this->tag = property_exists($this->data, 'tag') ? $this->data->tag : $this->version;
$this->base_location = property_exists($this->data, 'base_location') ? $this->data->base_location : null;
// Load the dependencies
$this->dependencies = property_exists($this->data, 'dependencies') ? $this->data->dependencies : array();
// Assign other data we don't have
foreach ($this->data as $k=>$v)
{
if (!property_exists($this, $k)) $this->$k = $v;
}
// used internally
$this->temp_token = 'spark-' . $this->spark_id . '-' . time();
$this->temp_path = sys_get_temp_dir() . '/' . $this->temp_token;
}
final function installed_path()
{
return $this->installed_path;
}
function location_detail() { }
function retrieve() { }
function install()
{
foreach ($this->dependencies as $dependency)
{
if ($dependency->is_direct)
{
$this->install_dependency($dependency);
}
}
@mkdir(SPARK_PATH); // Two steps for windows
@mkdir(SPARK_PATH . "/$this->name");
Spark_utils::full_move($this->temp_path, $this->installation_path);
Spark_utils::remove_full_directory($this->temp_path);
$this->installed_path = $this->installation_path;
}
private function recurseMove($src,$dst)
{
$dir = opendir($src);
@mkdir($dst);
while(false !== ( $file = readdir($dir)) ) {
if (( $file != '.' ) && ( $file != '..' )) {
if ( is_dir($src . '/' . $file) ) {
$this->recurseMove($src . '/' . $file,$dst . '/' . $file);
}
else {
rename($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
private function rrmdir($dir)
{
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != "." && $file != "..") {
if (is_dir($dir . "/" . $file)) {
$this->rrmdir($dir . "/" . $file);
}
else {
unlink($dir . "/" . $file);
}
}
}
reset($files);
rmdir($dir);
}
}
function install_dependency($dependency_data) {
// Get the spark object
$spark = null;
if ($dependency_data->repository_type == 'hg') $spark = Mercurial_spark::get_spark($dependency_data);
else if ($dependency_data->repository_type == 'git') $spark = Git_spark::get_spark($dependency_data);
else if ($dependency_data->repository_type == 'zip') $spark = new Zip_spark($dependency_data);
else throw new Exception('Unknown repository type: ' . $dependency_data->repository_type);
// Install the spark
if ($spark->verify(false)) { // if not installed, install
$spark->retrieve();
$spark->install();
Spark_utils::notice("Installed dependency: $spark->name to " . $spark->installed_path());
}
else {
Spark_utils::warning("Dependency $spark->name is already installed.");
}
}
function verify($break_on_already_installed = true)
{
// see if this is deactivated
if ($this->data->is_deactivated)
{
$msg = 'Woah there - it seems the spark you want has been deactivated';
if ($this->data->spark_home) $msg .= "\nLook for different versions at: " . $this->data->spark_home;
throw new Spark_exception($msg);
}
// see if this is unsupported
if ($this->data->is_unsupported)
{
Spark_utils::warning('This spark is no longer supported.');
Spark_utils::warning('You can keep using it, or look for an alternate');
}
// tell the user if its already installed and throw an error
$this->installation_path = SPARK_PATH . "/$this->name/$this->version";
if (is_dir($this->installation_path))
{
if ($break_on_already_installed)
{
throw new Spark_exception("Already installed. Try `php tools/spark reinstall $this->name`");
}
return false;
}
else
{
return true;
}
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/lib/spark/spark_utils.php | tools/lib/spark/spark_utils.php | <?php
// backward compatibility
if ( !function_exists('sys_get_temp_dir'))
{
function sys_get_temp_dir()
{
if ($temp = getenv('TMP')) return $temp;
if ($temp = getenv('TEMP')) return $temp;
if ($temp = getenv('TMPDIR')) return $temp;
$temp = tempnam(__FILE__, '');
if (file_exists($temp))
{
unlink($temp);
return dirname($temp);
}
return '/tmp'; // the best we can do
}
}
class Spark_utils {
private static $buffer = false;
private static $lines = array();
static function get_lines()
{
return self::$lines;
}
static function buffer()
{
self::$buffer = true;
}
static function full_move($src, $dst)
{
$dir = opendir($src);
@mkdir($dst);
while(false !== ($file = readdir($dir))) {
if (($file != '.') && ($file != '..')) {
if (is_dir($src . '/' . $file)) {
self::full_move($src . '/' . $file,$dst . '/' . $file);
}
else {
rename($src . '/' . $file,$dst . '/' . $file);
}
}
}
closedir($dir);
}
static function remove_full_directory($dir, $vocally = false)
{
if (is_dir($dir))
{
$objects = scandir($dir);
foreach ($objects as $object)
{
if ($object != '.' && $object != '..')
{
if (filetype($dir . '/' . $object) == "dir")
{
self::remove_full_directory($dir . '/' . $object, $vocally);
}
else
{
if ($vocally) self::notice("Removing $dir/$object");
unlink($dir . '/' . $object);
}
}
}
reset($objects);
return rmdir($dir);
}
}
static function notice($msg)
{
self::line($msg, 'SPARK', '[1;36m');
}
static function error($msg)
{
self::line($msg, 'ERROR', '[1;31m');
}
static function warning($msg)
{
self::line($msg, 'WARNING', '[1;33m');
}
static function line($msg = '', $s = null, $color = null)
{
foreach(explode("\n", $msg) as $line)
{
if (self::$buffer)
{
self::$lines[] = $line;
}
else
{
echo !$s ? "$line\n" : chr(27) . $color . "[ $s ]" . chr(27) . "[0m" . " $line\n";
}
}
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/lib/spark/spark_types/zip_spark.php | tools/lib/spark/spark_types/zip_spark.php | <?php
class Zip_spark extends Spark_type {
function __construct($data)
{
parent::__construct($data);
$this->temp_file = $this->temp_path . '.zip';
$this->archive_url = property_exists($this->data, 'archive_url') ? $this->data->archive_url : null;
}
function location_detail()
{
return "ZIP archive at $this->archive_url";
}
private static function unzip_installed()
{
return !!`unzip`;
}
function retrieve()
{
file_put_contents($this->temp_file, file_get_contents($this->archive_url));
// Try a few ways to unzip
if (class_exists('ZipArchive'))
{
$zip = new ZipArchive;
$zip->open($this->temp_file);
$zip->extractTo($this->temp_path);
$zip->close();
}
else
{
if (!self::unzip_installed())
{
throw new Spark_exception('You have to install PECL ZipArchive or `unzip` to install this spark.');
}
`unzip $this->temp_file -d $this->temp_path`;
}
if (!file_exists($this->temp_path))
{
throw new Spark_exception('Failed to retrieve the spark ;(');
}
return true;
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/lib/spark/spark_types/git_spark.php | tools/lib/spark/spark_types/git_spark.php | <?php
class Git_spark extends Spark_type {
function __construct($data)
{
if (!self::git_installed())
{
throw new Spark_exception('You have to have git to install this spark.');
}
parent::__construct($data);
$this->tag = $this->tag;
}
static function get_spark($data)
{
if (self::git_installed())
{
return new Git_spark($data);
}
else
{
Spark_utils::warning('Git not found - reverting to archived copy');
return new Zip_spark($data);
}
}
private static function git_installed()
{
return !!`git`;
}
function location_detail()
{
return "Git repository at $this->base_location";
}
function retrieve()
{
// check out the right tag
`git clone --recursive $this->base_location $this->temp_path`;
`cd $this->temp_path; git checkout $this->tag -b $this->temp_token`;
// remove the git directory
Spark_utils::remove_full_directory("$this->temp_path/.git");
if (!file_exists($this->temp_path))
{
throw new Spark_exception('Failed to retrieve the spark ;(');
}
return true;
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/tools/lib/spark/spark_types/hg_spark.php | tools/lib/spark/spark_types/hg_spark.php | <?php
class Mercurial_spark extends Spark_type {
function __construct($data)
{
parent::__construct($data);
$this->tag = $this->tag;
}
static function get_spark($data)
{
if (self::hg_installed())
{
return new Mercurial_spark($data);
}
else
{
Spark_utils::warning('Mercurial not found - reverting to archived copy');
return new Zip_spark($data);
}
}
private static function hg_installed()
{
return !!`hg`;
}
function location_detail()
{
return "Mercurial repository at $this->base_location";
}
function retrieve()
{
`hg clone -r$this->tag $this->base_location $this->temp_path`;
// remove the mercurial directory
Spark_utils::remove_full_directory("$this->temp_path/.hg");
if (!file_exists($this->temp_path))
{
throw new Spark_exception('Failed to retrieve the spark ;(');
}
return true;
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/sparks/curl/1.2.1/libraries/Curl.php | sparks/curl/1.2.1/libraries/Curl.php | <?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
* CodeIgniter Curl Class
*
* Work with remote servers via cURL much easier than using the native PHP bindings.
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
* @author Philip Sturgeon
* @license http://philsturgeon.co.uk/code/dbad-license
* @link http://philsturgeon.co.uk/code/codeigniter-curl
*/
class Curl {
protected $_ci; // CodeIgniter instance
protected $response = ''; // Contains the cURL response for debug
protected $session; // Contains the cURL handler for a session
protected $url; // URL of the session
protected $options = array(); // Populates curl_setopt_array
protected $headers = array(); // Populates extra HTTP headers
public $error_code; // Error code returned as an int
public $error_string; // Error message returned as a string
public $info; // Returned after request (elapsed time, etc)
function __construct($url = '')
{
$this->_ci = & get_instance();
log_message('debug', 'cURL Class Initialized');
if ( ! $this->is_enabled())
{
log_message('error', 'cURL Class - PHP was not built with cURL enabled. Rebuild PHP with --with-curl to use cURL.');
}
$url AND $this->create($url);
}
public function __call($method, $arguments)
{
if (in_array($method, array('simple_get', 'simple_post', 'simple_put', 'simple_delete')))
{
// Take off the "simple_" and past get/post/put/delete to _simple_call
$verb = str_replace('simple_', '', $method);
array_unshift($arguments, $verb);
return call_user_func_array(array($this, '_simple_call'), $arguments);
}
}
/* =================================================================================
* SIMPLE METHODS
* Using these methods you can make a quick and easy cURL call with one line.
* ================================================================================= */
public function _simple_call($method, $url, $params = array(), $options = array())
{
// Get acts differently, as it doesnt accept parameters in the same way
if ($method === 'get')
{
// If a URL is provided, create new session
$this->create($url.($params ? '?'.http_build_query($params, NULL, '&') : ''));
}
else
{
// If a URL is provided, create new session
$this->create($url);
$this->{$method}($params);
}
// Add in the specific options provided
$this->options($options);
return $this->execute();
}
public function simple_ftp_get($url, $file_path, $username = '', $password = '')
{
// If there is no ftp:// or any protocol entered, add ftp://
if ( ! preg_match('!^(ftp|sftp)://! i', $url))
{
$url = 'ftp://' . $url;
}
// Use an FTP login
if ($username != '')
{
$auth_string = $username;
if ($password != '')
{
$auth_string .= ':' . $password;
}
// Add the user auth string after the protocol
$url = str_replace('://', '://' . $auth_string . '@', $url);
}
// Add the filepath
$url .= $file_path;
$this->option(CURLOPT_BINARYTRANSFER, TRUE);
$this->option(CURLOPT_VERBOSE, TRUE);
return $this->execute();
}
/* =================================================================================
* ADVANCED METHODS
* Use these methods to build up more complex queries
* ================================================================================= */
public function post($params = array(), $options = array())
{
// If its an array (instead of a query string) then format it correctly
if (is_array($params))
{
$params = http_build_query($params, NULL, '&');
}
// Add in the specific options provided
$this->options($options);
$this->http_method('post');
$this->option(CURLOPT_POST, TRUE);
$this->option(CURLOPT_POSTFIELDS, $params);
}
public function put($params = array(), $options = array())
{
// If its an array (instead of a query string) then format it correctly
if (is_array($params))
{
$params = http_build_query($params, NULL, '&');
}
// Add in the specific options provided
$this->options($options);
$this->http_method('put');
$this->option(CURLOPT_POSTFIELDS, $params);
// Override method, I think this overrides $_POST with PUT data but... we'll see eh?
$this->option(CURLOPT_HTTPHEADER, array('X-HTTP-Method-Override: PUT'));
}
public function delete($params, $options = array())
{
// If its an array (instead of a query string) then format it correctly
if (is_array($params))
{
$params = http_build_query($params, NULL, '&');
}
// Add in the specific options provided
$this->options($options);
$this->http_method('delete');
$this->option(CURLOPT_POSTFIELDS, $params);
}
public function set_cookies($params = array())
{
if (is_array($params))
{
$params = http_build_query($params, NULL, '&');
}
$this->option(CURLOPT_COOKIE, $params);
return $this;
}
public function http_header($header, $content = NULL)
{
$this->headers[] = $content ? $header . ': ' . $content : $header;
}
public function http_method($method)
{
$this->options[CURLOPT_CUSTOMREQUEST] = strtoupper($method);
return $this;
}
public function http_login($username = '', $password = '', $type = 'any')
{
$this->option(CURLOPT_HTTPAUTH, constant('CURLAUTH_' . strtoupper($type)));
$this->option(CURLOPT_USERPWD, $username . ':' . $password);
return $this;
}
public function proxy($url = '', $port = 80)
{
$this->option(CURLOPT_HTTPPROXYTUNNEL, TRUE);
$this->option(CURLOPT_PROXY, $url . ':' . $port);
return $this;
}
public function proxy_login($username = '', $password = '')
{
$this->option(CURLOPT_PROXYUSERPWD, $username . ':' . $password);
return $this;
}
public function ssl($verify_peer = TRUE, $verify_host = 2, $path_to_cert = NULL)
{
if ($verify_peer)
{
$this->option(CURLOPT_SSL_VERIFYPEER, TRUE);
$this->option(CURLOPT_SSL_VERIFYHOST, $verify_host);
$this->option(CURLOPT_CAINFO, $path_to_cert);
}
else
{
$this->option(CURLOPT_SSL_VERIFYPEER, FALSE);
}
return $this;
}
public function options($options = array())
{
// Merge options in with the rest - done as array_merge() does not overwrite numeric keys
foreach ($options as $option_code => $option_value)
{
$this->option($option_code, $option_value);
}
// Set all options provided
curl_setopt_array($this->session, $this->options);
return $this;
}
public function option($code, $value)
{
if (is_string($code) && !is_numeric($code))
{
$code = constant('CURLOPT_' . strtoupper($code));
}
$this->options[$code] = $value;
return $this;
}
// Start a session from a URL
public function create($url)
{
// If no a protocol in URL, assume its a CI link
if ( ! preg_match('!^\w+://! i', $url))
{
$this->_ci->load->helper('url');
$url = site_url($url);
}
$this->url = $url;
$this->session = curl_init($this->url);
return $this;
}
// End a session and return the results
public function execute()
{
// Set two default options, and merge any extra ones in
if ( ! isset($this->options[CURLOPT_TIMEOUT]))
{
$this->options[CURLOPT_TIMEOUT] = 30;
}
if ( ! isset($this->options[CURLOPT_RETURNTRANSFER]))
{
$this->options[CURLOPT_RETURNTRANSFER] = TRUE;
}
if ( ! isset($this->options[CURLOPT_FAILONERROR]))
{
$this->options[CURLOPT_FAILONERROR] = TRUE;
}
// Only set follow location if not running securely
if ( ! ini_get('safe_mode') && ! ini_get('open_basedir'))
{
// Ok, follow location is not set already so lets set it to true
if ( ! isset($this->options[CURLOPT_FOLLOWLOCATION]))
{
$this->options[CURLOPT_FOLLOWLOCATION] = TRUE;
}
}
if ( ! empty($this->headers))
{
$this->option(CURLOPT_HTTPHEADER, $this->headers);
}
$this->options();
// Execute the request & and hide all output
$this->response = curl_exec($this->session);
$this->info = curl_getinfo($this->session);
// Request failed
if ($this->response === FALSE)
{
$errno = curl_errno($this->session);
$error = curl_error($this->session);
curl_close($this->session);
$this->set_defaults();
$this->error_code = $errno;
$this->error_string = $error;
return FALSE;
}
// Request successful
else
{
curl_close($this->session);
$this->last_response = $this->response;
$this->set_defaults();
return $this->last_response;
}
}
public function is_enabled()
{
return function_exists('curl_init');
}
public function debug()
{
echo "=============================================<br/>\n";
echo "<h2>CURL Test</h2>\n";
echo "=============================================<br/>\n";
echo "<h3>Response</h3>\n";
echo "<code>" . nl2br(htmlentities($this->last_response)) . "</code><br/>\n\n";
if ($this->error_string)
{
echo "=============================================<br/>\n";
echo "<h3>Errors</h3>";
echo "<strong>Code:</strong> " . $this->error_code . "<br/>\n";
echo "<strong>Message:</strong> " . $this->error_string . "<br/>\n";
}
echo "=============================================<br/>\n";
echo "<h3>Info</h3>";
echo "<pre>";
print_r($this->info);
echo "</pre>";
}
public function debug_request()
{
return array(
'url' => $this->url
);
}
public function set_defaults()
{
$this->response = '';
$this->headers = array();
$this->options = array();
$this->error_code = NULL;
$this->error_string = '';
$this->session = NULL;
}
}
/* End of file Curl.php */
/* Location: ./application/libraries/Curl.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/sparks/curl/1.2.1/config/autoload.php | sparks/curl/1.2.1/config/autoload.php | <?php
# Load the template library when the spark is loaded
$autoload['libraries'] = array('curl'); | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/sparks/template/1.9.0/libraries/Template.php | sparks/template/1.9.0/libraries/Template.php | <?php defined('BASEPATH') OR exit('No direct script access allowed');
/**
* CodeIgniter Template Class
*
* Build your CodeIgniter pages much easier with partials, breadcrumbs, layouts and themes
*
* @package CodeIgniter
* @subpackage Libraries
* @category Libraries
* @author Philip Sturgeon
* @license http://philsturgeon.co.uk/code/dbad-license
* @link http://getsparks.org/packages/template/show
*/
class Template
{
private $_module = '';
private $_controller = '';
private $_method = '';
private $_theme = NULL;
private $_theme_path = NULL;
private $_layout = FALSE; // By default, dont wrap the view with anything
private $_layout_subdir = ''; // Layouts and partials will exist in views/layouts
// but can be set to views/foo/layouts with a subdirectory
private $_title = '';
private $_metadata = array();
private $_partials = array();
private $_breadcrumbs = array();
private $_title_separator = ' | ';
private $_parser_enabled = TRUE;
private $_parser_body_enabled = TRUE;
private $_theme_locations = array();
private $_is_mobile = FALSE;
// Minutes that cache will be alive for
private $cache_lifetime = 0;
private $_ci;
private $_data = array();
/**
* Constructor - Sets Preferences
*
* The constructor can be passed an array of config values
*/
function __construct($config = array())
{
$this->_ci =& get_instance();
if ( ! empty($config))
{
$this->initialize($config);
}
log_message('debug', 'Template class Initialized');
}
// --------------------------------------------------------------------
/**
* Initialize preferences
*
* @access public
* @param array
* @return void
*/
function initialize($config = array())
{
foreach ($config as $key => $val)
{
if ($key == 'theme' AND $val != '')
{
$this->set_theme($val);
continue;
}
$this->{'_'.$key} = $val;
}
// No locations set in config?
if ($this->_theme_locations === array())
{
// Let's use this obvious default
$this->_theme_locations = array(APPPATH . 'themes/');
}
// Theme was set
if ($this->_theme)
{
$this->set_theme($this->_theme);
}
// If the parse is going to be used, best make sure it's loaded
if ($this->_parser_enabled === TRUE)
{
class_exists('CI_Parser') OR $this->_ci->load->library('parser');
}
// Modular Separation / Modular Extensions has been detected
if (method_exists( $this->_ci->router, 'fetch_module' ))
{
$this->_module = $this->_ci->router->fetch_module();
}
// What controllers or methods are in use
$this->_controller = $this->_ci->router->fetch_class();
$this->_method = $this->_ci->router->fetch_method();
// Load user agent library if not loaded
class_exists('CI_User_agent') OR $this->_ci->load->library('user_agent');
// We'll want to know this later
$this->_is_mobile = $this->_ci->agent->is_mobile();
}
// --------------------------------------------------------------------
/**
* Magic Get function to get data
*
* @access public
* @param string
* @return mixed
*/
public function __get($name)
{
return isset($this->_data[$name]) ? $this->_data[$name] : NULL;
}
// --------------------------------------------------------------------
/**
* Magic Set function to set data
*
* @access public
* @param string
* @return mixed
*/
public function __set($name, $value)
{
$this->_data[$name] = $value;
}
// --------------------------------------------------------------------
/**
* Set data using a chainable metod. Provide two strings or an array of data.
*
* @access public
* @param string
* @return mixed
*/
public function set($name, $value = NULL)
{
// Lots of things! Set them all
if (is_array($name) OR is_object($name))
{
foreach ($name as $item => $value)
{
$this->_data[$item] = $value;
}
}
// Just one thing, set that
else
{
$this->_data[$name] = $value;
}
return $this;
}
// --------------------------------------------------------------------
/**
* Build the entire HTML output combining partials, layouts and views.
*
* @access public
* @param string
* @return void
*/
public function build($view, $data = array(), $return = FALSE)
{
// Set whatever values are given. These will be available to all view files
is_array($data) OR $data = (array) $data;
// Merge in what we already have with the specific data
$this->_data = array_merge($this->_data, $data);
// We don't need you any more buddy
unset($data);
if (empty($this->_title))
{
$this->_title = $this->_guess_title();
}
// Output template variables to the template
$template['title'] = $this->_title;
$template['breadcrumbs'] = $this->_breadcrumbs;
$template['metadata'] = implode("\n\t\t", $this->_metadata);
$template['partials'] = array();
// Assign by reference, as all loaded views will need access to partials
$this->_data['template'] =& $template;
foreach ($this->_partials as $name => $partial)
{
// We can only work with data arrays
is_array($partial['data']) OR $partial['data'] = (array) $partial['data'];
// If it uses a view, load it
if (isset($partial['view']))
{
$template['partials'][$name] = $this->_find_view($partial['view'], $partial['data']);
}
// Otherwise the partial must be a string
else
{
if ($this->_parser_enabled === TRUE)
{
$partial['string'] = $this->_ci->parser->parse_string($partial['string'], $this->_data + $partial['data'], TRUE, TRUE);
}
$template['partials'][$name] = $partial['string'];
}
}
// Disable sodding IE7's constant cacheing!!
$this->_ci->output->set_header('Expires: Sat, 01 Jan 2000 00:00:01 GMT');
$this->_ci->output->set_header('Cache-Control: no-store, no-cache, must-revalidate');
$this->_ci->output->set_header('Cache-Control: post-check=0, pre-check=0, max-age=0');
$this->_ci->output->set_header('Last-Modified: ' . gmdate( 'D, d M Y H:i:s' ) . ' GMT' );
$this->_ci->output->set_header('Pragma: no-cache');
// Let CI do the caching instead of the browser
$this->_ci->output->cache($this->cache_lifetime);
// Test to see if this file
$this->_body = $this->_find_view($view, array(), $this->_parser_body_enabled);
// Want this file wrapped with a layout file?
if ($this->_layout)
{
// Added to $this->_data['template'] by refference
$template['body'] = $this->_body;
// Find the main body and 3rd param means parse if its a theme view (only if parser is enabled)
$this->_body = self::_load_view('layouts/'.$this->_layout, $this->_data, TRUE, self::_find_view_folder());
}
// Want it returned or output to browser?
if ( ! $return)
{
$this->_ci->output->set_output($this->_body);
}
return $this->_body;
}
/**
* Set the title of the page
*
* @access public
* @param string
* @return void
*/
public function title()
{
// If we have some segments passed
if ($title_segments =& func_get_args())
{
$this->_title = implode($this->_title_separator, $title_segments);
}
return $this;
}
/**
* Put extra javascipt, css, meta tags, etc before all other head data
*
* @access public
* @param string $line The line being added to head
* @return void
*/
public function prepend_metadata($line)
{
array_unshift($this->_metadata, $line);
return $this;
}
/**
* Put extra javascipt, css, meta tags, etc after other head data
*
* @access public
* @param string $line The line being added to head
* @return void
*/
public function append_metadata($line)
{
$this->_metadata[] = $line;
return $this;
}
/**
* Set metadata for output later
*
* @access public
* @param string $name keywords, description, etc
* @param string $content The content of meta data
* @param string $type Meta-data comes in a few types, links for example
* @return void
*/
public function set_metadata($name, $content, $type = 'meta')
{
$name = htmlspecialchars(strip_tags($name));
$content = htmlspecialchars(strip_tags($content));
// Keywords with no comments? ARG! comment them
if ($name == 'keywords' AND ! strpos($content, ','))
{
$content = preg_replace('/[\s]+/', ', ', trim($content));
}
switch($type)
{
case 'meta':
$this->_metadata[$name] = '<meta name="'.$name.'" content="'.$content.'" />';
break;
case 'link':
$this->_metadata[$content] = '<link rel="'.$name.'" href="'.$content.'" />';
break;
}
return $this;
}
/**
* Which theme are we using here?
*
* @access public
* @param string $theme Set a theme for the template library to use
* @return void
*/
public function set_theme($theme = NULL)
{
$this->_theme = $theme;
foreach ($this->_theme_locations as $location)
{
if ($this->_theme AND file_exists($location.$this->_theme))
{
$this->_theme_path = rtrim($location.$this->_theme.'/');
break;
}
}
return $this;
}
/**
* Get the current theme path
*
* @access public
* @return string The current theme path
*/
public function get_theme_path()
{
return $this->_theme_path;
}
/**
* Which theme layout should we using here?
*
* @access public
* @param string $view
* @return void
*/
public function set_layout($view, $_layout_subdir = '')
{
$this->_layout = $view;
$_layout_subdir AND $this->_layout_subdir = $_layout_subdir;
return $this;
}
/**
* Set a view partial
*
* @access public
* @param string
* @param string
* @param boolean
* @return void
*/
public function set_partial($name, $view, $data = array())
{
$this->_partials[$name] = array('view' => $view, 'data' => $data);
return $this;
}
/**
* Set a view partial
*
* @access public
* @param string
* @param string
* @param boolean
* @return void
*/
public function inject_partial($name, $string, $data = array())
{
$this->_partials[$name] = array('string' => $string, 'data' => $data);
return $this;
}
/**
* Helps build custom breadcrumb trails
*
* @access public
* @param string $name What will appear as the link text
* @param string $url_ref The URL segment
* @return void
*/
public function set_breadcrumb($name, $uri = '')
{
$this->_breadcrumbs[] = array('name' => $name, 'uri' => $uri );
return $this;
}
/**
* Set a the cache lifetime
*
* @access public
* @param string
* @param string
* @param boolean
* @return void
*/
public function set_cache($minutes = 0)
{
$this->cache_lifetime = $minutes;
return $this;
}
/**
* enable_parser
* Should be parser be used or the view files just loaded normally?
*
* @access public
* @param string $view
* @return void
*/
public function enable_parser($bool)
{
$this->_parser_enabled = $bool;
return $this;
}
/**
* enable_parser_body
* Should be parser be used or the body view files just loaded normally?
*
* @access public
* @param string $view
* @return void
*/
public function enable_parser_body($bool)
{
$this->_parser_body_enabled = $bool;
return $this;
}
/**
* theme_locations
* List the locations where themes may be stored
*
* @access public
* @param string $view
* @return array
*/
public function theme_locations()
{
return $this->_theme_locations;
}
/**
* add_theme_location
* Set another location for themes to be looked in
*
* @access public
* @param string $view
* @return array
*/
public function add_theme_location($location)
{
$this->_theme_locations[] = $location;
}
/**
* theme_exists
* Check if a theme exists
*
* @access public
* @param string $view
* @return array
*/
public function theme_exists($theme = NULL)
{
$theme OR $theme = $this->_theme;
foreach ($this->_theme_locations as $location)
{
if (is_dir($location.$theme))
{
return TRUE;
}
}
return FALSE;
}
/**
* get_layouts
* Get all current layouts (if using a theme you'll get a list of theme layouts)
*
* @access public
* @param string $view
* @return array
*/
public function get_layouts()
{
$layouts = array();
foreach(glob(self::_find_view_folder().'layouts/*.*') as $layout)
{
$layouts[] = pathinfo($layout, PATHINFO_BASENAME);
}
return $layouts;
}
/**
* get_layouts
* Get all current layouts (if using a theme you'll get a list of theme layouts)
*
* @access public
* @param string $view
* @return array
*/
public function get_theme_layouts($theme = NULL)
{
$theme OR $theme = $this->_theme;
$layouts = array();
foreach ($this->_theme_locations as $location)
{
// Get special web layouts
if( is_dir($location.$theme.'/views/web/layouts/') )
{
foreach(glob($location.$theme . '/views/web/layouts/*.*') as $layout)
{
$layouts[] = pathinfo($layout, PATHINFO_BASENAME);
}
break;
}
// So there are no web layouts, assume all layouts are web layouts
if(is_dir($location.$theme.'/views/layouts/'))
{
foreach(glob($location.$theme . '/views/layouts/*.*') as $layout)
{
$layouts[] = pathinfo($layout, PATHINFO_BASENAME);
}
break;
}
}
return $layouts;
}
/**
* layout_exists
* Check if a theme layout exists
*
* @access public
* @param string $view
* @return array
*/
public function layout_exists($layout)
{
// If there is a theme, check it exists in there
if ( ! empty($this->_theme) AND in_array($layout, self::get_theme_layouts()))
{
return TRUE;
}
// Otherwise look in the normal places
return file_exists(self::_find_view_folder().'layouts/' . $layout . self::_ext($layout));
}
// find layout files, they could be mobile or web
private function _find_view_folder()
{
if ($this->_ci->load->get_var('template_views'))
{
return $this->_ci->load->get_var('template_views');
}
// Base view folder
$view_folder = APPPATH.'views/';
// Using a theme? Put the theme path in before the view folder
if ( ! empty($this->_theme))
{
$view_folder = $this->_theme_path.'views/';
}
// Would they like the mobile version?
if ($this->_is_mobile === TRUE AND is_dir($view_folder.'mobile/'))
{
// Use mobile as the base location for views
$view_folder .= 'mobile/';
}
// Use the web version
else if (is_dir($view_folder.'web/'))
{
$view_folder .= 'web/';
}
// Things like views/admin/web/view admin = subdir
if ($this->_layout_subdir)
{
$view_folder .= $this->_layout_subdir.'/';
}
// If using themes store this for later, available to all views
$this->_ci->load->vars('template_views', $view_folder);
return $view_folder;
}
// A module view file can be overriden in a theme
private function _find_view($view, array $data, $parse_view = TRUE)
{
// Only bother looking in themes if there is a theme
if ( ! empty($this->_theme))
{
foreach ($this->_theme_locations as $location)
{
$theme_views = array(
$this->_theme . '/views/modules/' . $this->_module . '/' . $view,
$this->_theme . '/views/' . $view
);
foreach ($theme_views as $theme_view)
{
if (file_exists($location . $theme_view . self::_ext($theme_view)))
{
return self::_load_view($theme_view, $this->_data + $data, $parse_view, $location);
}
}
}
}
// Not found it yet? Just load, its either in the module or root view
return self::_load_view($view, $this->_data + $data, $parse_view);
}
private function _load_view($view, array $data, $parse_view = TRUE, $override_view_path = NULL)
{
// Sevear hackery to load views from custom places AND maintain compatibility with Modular Extensions
if ($override_view_path !== NULL)
{
if ($this->_parser_enabled === TRUE AND $parse_view === TRUE)
{
// Load content and pass through the parser
$content = $this->_ci->parser->parse_string($this->_ci->load->file(
$override_view_path.$view.self::_ext($view),
TRUE
), $data);
}
else
{
$this->_ci->load->vars($data);
// Load it directly, bypassing $this->load->view() as ME resets _ci_view
$content = $this->_ci->load->file(
$override_view_path.$view.self::_ext($view),
TRUE
);
}
}
// Can just run as usual
else
{
// Grab the content of the view (parsed or loaded)
$content = ($this->_parser_enabled === TRUE AND $parse_view === TRUE)
// Parse that bad boy
? $this->_ci->parser->parse($view, $data, TRUE)
// None of that fancy stuff for me!
: $this->_ci->load->view($view, $data, TRUE);
}
return $content;
}
private function _guess_title()
{
$this->_ci->load->helper('inflector');
// Obviously no title, lets get making one
$title_parts = array();
// If the method is something other than index, use that
if ($this->_method != 'index')
{
$title_parts[] = $this->_method;
}
// Make sure controller name is not the same as the method name
if ( ! in_array($this->_controller, $title_parts))
{
$title_parts[] = $this->_controller;
}
// Is there a module? Make sure it is not named the same as the method or controller
if ( ! empty($this->_module) AND ! in_array($this->_module, $title_parts))
{
$title_parts[] = $this->_module;
}
// Glue the title pieces together using the title separator setting
$title = humanize(implode($this->_title_separator, $title_parts));
return $title;
}
private function _ext($file)
{
return pathinfo($file, PATHINFO_EXTENSION) ? '' : '.php';
}
}
// END Template class | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/sparks/template/1.9.0/config/autoload.php | sparks/template/1.9.0/config/autoload.php | <?php
# Load the template library when the spark is loaded
$autoload['libraries'] = array('template'); | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/sparks/template/1.9.0/config/template.php | sparks/template/1.9.0/config/template.php | <?php defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Parser Enabled
|--------------------------------------------------------------------------
|
| Should the Parser library be used for the entire page?
|
| Can be overridden with $this->template->enable_parser(TRUE/FALSE);
|
| Default: TRUE
|
*/
$config['parser_enabled'] = TRUE;
/*
|--------------------------------------------------------------------------
| Parser Enabled for Body
|--------------------------------------------------------------------------
|
| If the parser is enabled, do you want it to parse the body or not?
|
| Can be overridden with $this->template->enable_parser(TRUE/FALSE);
|
| Default: FALSE
|
*/
$config['parser_body_enabled'] = FALSE;
/*
|--------------------------------------------------------------------------
| Title Separator
|--------------------------------------------------------------------------
|
| What string should be used to separate title segments sent via $this->template->title('Foo', 'Bar');
|
| Default: ' | '
|
*/
$config['title_separator'] = ' | ';
/*
|--------------------------------------------------------------------------
| Theme
|--------------------------------------------------------------------------
|
| Which layout file should be used? When combined with theme it will be a layout file in that theme
|
| Change to 'main' to get /application/views/main.php
|
| Default: FALSE
|
*/
$config['layout'] = FALSE;
/*
|--------------------------------------------------------------------------
| Theme
|--------------------------------------------------------------------------
|
| Which theme to use by default?
|
| Can be overriden with $this->template->set_theme('foo');
|
| Default: ''
|
*/
$config['theme'] = '';
/*
|--------------------------------------------------------------------------
| Theme
|--------------------------------------------------------------------------
|
| Where should we expect to see themes?
|
| Default: array(APPPATH.'themes/' => '../themes/')
|
*/
$config['theme_locations'] = array(
APPPATH.'themes/'
); | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/errors/error_general.php | application/errors/error_general.php | <!DOCTYPE html>
<html lang="en">
<head>
<title>Error</title>
<style type="text/css">
::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }
::webkit-selection{ background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
-webkit-box-shadow: 0 0 8px #D0D0D0;
}
p {
margin: 12px 15px 12px 15px;
}
</style>
</head>
<body>
<div id="container">
<h1><?php echo $heading; ?></h1>
<?php echo $message; ?>
</div>
</body>
</html> | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/errors/error_404.php | application/errors/error_404.php | <!DOCTYPE html>
<html lang="en">
<head>
<title>404 Page Not Found</title>
<style type="text/css">
::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }
::webkit-selection{ background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
-webkit-box-shadow: 0 0 8px #D0D0D0;
}
p {
margin: 12px 15px 12px 15px;
}
</style>
</head>
<body>
<div id="container">
<h1><?php echo $heading; ?></h1>
<?php echo $message; ?>
</div>
</body>
</html> | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/errors/error_php.php | application/errors/error_php.php | <div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
<h4>A PHP Error was encountered</h4>
<p>Severity: <?php echo $severity; ?></p>
<p>Message: <?php echo $message; ?></p>
<p>Filename: <?php echo $filepath; ?></p>
<p>Line Number: <?php echo $line; ?></p>
</div> | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/errors/error_db.php | application/errors/error_db.php | <!DOCTYPE html>
<html lang="en">
<head>
<title>Database Error</title>
<style type="text/css">
::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }
::webkit-selection{ background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#container {
margin: 10px;
border: 1px solid #D0D0D0;
-webkit-box-shadow: 0 0 8px #D0D0D0;
}
p {
margin: 12px 15px 12px 15px;
}
</style>
</head>
<body>
<div id="container">
<h1><?php echo $heading; ?></h1>
<?php echo $message; ?>
</div>
</body>
</html> | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/controllers/home.php | application/controllers/home.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Home extends MY_Controller {
public function index() {
$this->template->build("editor");
}
public function sentiment($poem){
$url = "http://api.lymbix.com/tonalize_detailed";
$headers = array('Content-Type: application/json', 'ACCEPT: application/json', 'VERSION: 2.2', 'AUTHENTICATION: 6c89f5919d00b2aa292c2bb30c71f1900fcec95f');
$dataz = array("article: please fucking work", "return_fields: []");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $dataz);
$reply = curl_exec($ch);
curl_close($ch);
$ar = json_decode($reply,true);
echo $ar['dominant_emotion'];
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/controllers/about.php | application/controllers/about.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class About extends MY_Controller {
public function index() {
$this->template->build("about");
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/controllers/rhyme.php | application/controllers/rhyme.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Rhyme extends MY_Controller {
public function getRhyme($word) {
echo json_encode($word);
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/controllers/welcome.php | application/controllers/welcome.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends MY_Controller {
/**
* Index Page for this controller.
*
* Maps to the following URL
* http://example.com/index.php/welcome
* - or -
* http://example.com/index.php/welcome/index
* - or -
* Since this controller is set as the default controller in
* config/routes.php, it's displayed at http://example.com/
*
* So any other public methods not prefixed with an underscore will
* map to /index.php/welcome/<method_name>
* @see http://codeigniter.com/user_guide/general/urls.html
*/
public function index()
{
$this->template->build('welcome_message');
}
}
/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/views/about.php | application/views/about.php | <div class="about row">
<div class="twelve columns">
<div class="row">
<div class="one columns">
</div>
<div class="eleven columns">
<h1>About</h1>
<p>This is a text editor built with poets in mind. Everything is finely tuned to assist with the creative process. </p>
<p>Your soul, an inkwell -<br />
A web app to help you create<br />
Of Hack N Jill borne</p>
<h1>Features</h1>
<p>Its features include those below:<br />
Rhyme helper, Syllable count;<br />
Let your inner Creative grow:<br />
Your thoughts, the fount.</p>
<h1>Technology at Work</h1>
<p class="about-poem">
<a href="http://foundation.zurb.com/">Foundation</a> for a responsive interface,<br />
<a href="http://codeigniter.com/">Code Igniter</a> to keep order in haste,<br />
<a href="http://rhymebrain.com">RhymeBrain</a> to turn out rhyming words;<br />
Proud tools, these, of tech nerds.
</p>
</div>
</div>
</div>
</div>
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/views/editor.php | application/views/editor.php | <div class="row">
<div class="one columns">
</div>
<div class="eleven columns">
<div class="row">
<div class="twelve columns">
<form>
<input type="text" name="title" id="title" placeholder="Title" autocomplete="off"/>
</form>
</div>
</div>
<div class="row">
<div class="one columns syllable_counts linked">
</div>
<div class="seven columns">
<div class="cushion">
<textarea class="poetry-text linked" placeholder="Your poem goes here,
no more need you fear."></textarea>
</div>
</div>
<div class="four columns side">
<div class="scheme_line">Rhyme Scheme<input id="scheme" name="scheme" value="AABB"></input></div>
<div class="sidebar">
</div>
</div>
</div>
</div>
<div class="push"></div>
</div>
<div class="row">
<div class="centered six columns">
<div class="footer">
<p>
Copyright©2012 Bilal Quadri, Josh Greenman, Gene Demo, Grant Kot, Sharon Li
</p>
</div>
</div>
</div>
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/views/welcome_message.php | application/views/welcome_message.php | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Welcome to CodeIgniter</title>
<style type="text/css">
::selection{ background-color: #E13300; color: white; }
::moz-selection{ background-color: #E13300; color: white; }
::webkit-selection{ background-color: #E13300; color: white; }
body {
background-color: #fff;
margin: 40px;
font: 13px/20px normal Helvetica, Arial, sans-serif;
color: #4F5155;
}
a {
color: #003399;
background-color: transparent;
font-weight: normal;
}
h1 {
color: #444;
background-color: transparent;
border-bottom: 1px solid #D0D0D0;
font-size: 19px;
font-weight: normal;
margin: 0 0 14px 0;
padding: 14px 15px 10px 15px;
}
code {
font-family: Consolas, Monaco, Courier New, Courier, monospace;
font-size: 12px;
background-color: #f9f9f9;
border: 1px solid #D0D0D0;
color: #002166;
display: block;
margin: 14px 0 14px 0;
padding: 12px 10px 12px 10px;
}
#body{
margin: 0 15px 0 15px;
}
p.footer{
text-align: right;
font-size: 11px;
border-top: 1px solid #D0D0D0;
line-height: 32px;
padding: 0 10px 0 10px;
margin: 20px 0 0 0;
}
#container{
margin: 10px;
border: 1px solid #D0D0D0;
-webkit-box-shadow: 0 0 8px #D0D0D0;
}
</style>
</head>
<body>
<div id="container">
<h1>Welcome to CodeIgniter!</h1>
<div id="body">
<p>The page you are looking at is being generated dynamically by CodeIgniter.</p>
<p>If you would like to edit this page you'll find it located at:</p>
<code>application/views/welcome_message.php</code>
<p>The corresponding controller for this page is found at:</p>
<code>application/controllers/welcome.php</code>
<p>If you are exploring CodeIgniter for the very first time, you should start by reading the <a href="user_guide/">User Guide</a>.</p>
</div>
<p class="footer">Page rendered in <strong>{elapsed_time}</strong> seconds</p>
</div>
</body>
</html> | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/views/layouts/default.php | application/views/layouts/default.php | <!DOCTYPE HTML>
<!-- paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/ -->
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8" lang="en"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9" lang="en"> <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Tranquillity</title>
<!-- Responsive and mobile friendly stuff -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Grid System & Reset -->
<link rel="stylesheet" href="public/css/foundation.css" media="all">
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Alex+Brush' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="public/css/main.css" media="all">
<!-- All JavaScript at the bottom, except for Modernizr which enables HTML5 elements and feature detects -->
<script src="public/js/modernizr-2.5.3-min.js"></script>
<!-- IE Fix for HTML5 Tags -->
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36284960-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<!-- <div class="section group">
<div class="col span_1_of_12"></div>
<div class="col span_11_of_12">
<h1>Tranquillity</h1>
</div>
</div> -->
<div class="topBar"></div>
<div class="wrapper">
<div class="row">
<div class="eight columns">
<a href="/"><img src="public/img/tranquillity.png" id="logo" /></a>
</div>
<div class="four columns">
<div id="nav">
<ul>
<li><a href="/about">About </a></li>
<li> | </li>
<li><a href="https://github.com/bilalq/Tranquillity-Editor">Source</a></li>
</ul>
</div>
</div>
</div>
<?= $template['body'] ?>
<!--<div class="blackbar"> </div>-->
</div>
<!-- Source JS files -->
<script src="public/js/jquery-1.7.2.min.js"></script>
<script src="public/js/rhyme.js"></script>
<script src="public/js/TextStatistics.js"></script>
</body>
</html>
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/libraries/Lymbix.php | application/libraries/Lymbix.php | <?php
class Lymbix {
const API_BASE = 'https://gyrus.lymbix.com/';
const TONALIZE_MULTIPLE = 'tonalize_multiple';
const TONALIZE_DETAILED = 'tonalize_detailed';
const TONALIZE = 'tonalize';
const FLAG_RESPONSE = 'flag_response';
private $authenticationKey = null;
/**
* @param string $authenticationKey your Lymbix authentication key
*/
public function Lymbix($authenticationKey) {
if (empty($authenticationKey)) {
throw new Exception('You must include your authentication key');
}
$this->authenticationKey = $authenticationKey;
}
/* utility functions */
private static function Post($url, $data, $headers)
{
$dataString = http_build_query($data);
$headerString = '';
foreach ($headers as $headerKey => $headerValue) {
$headerString .= "$headerKey: $headerValue\n";
}
$opts = array('http' =>
array(
'method' => 'POST',
'header' => $headerString,
'content' => $dataString
)
);
$context = stream_context_create($opts);
return file_get_contents($url, false, $context);
}
private function getHeaders()
{
$headers = array();
$headers['Authentication'] = $this->authenticationKey;
$headers['Accept'] = 'application/json';
$headers['Version'] = '2.2';
return $headers;
}
/* api methods */
/**
* tonalize multiple articles
*
* @param array $articles articles to tonalize
* @param array $options additional parameters (reference_ids and return_fields)
* @return object see the api documentation for the format of this object
*/
public function TonalizeMultiple($articles, $options = null) {
if (empty($articles)) {
throw new Exception('You must include articles to tonalize');
}
$url = self::API_BASE . self::TONALIZE_MULTIPLE;
$articles = json_encode($articles);
$data = array('articles' => $articles);
if (isset($options)) {
// return_fields & reference_ids
foreach ($options as $key => $value) {
$options[$key] = json_encode($value);
}
$data = array_merge($data, $options);
}
$headers = $this->getHeaders();
$response = self::Post($url, $data, $headers);
if (!$response) return false;
return json_decode($response);
}
/**
* tonalize an article
*
* @param string $article article to tonalize
* @param array $options additional parameters (reference_id and return_fields)
* @return object see the api documentation for the format of this object
*/
public function TonalizeDetailed($article, $options = null) {
if (empty($article)) {
throw new Exception('You must include an article to tonalize');
}
$url = self::API_BASE . self::TONALIZE_DETAILED;
$data = array('article' => $article);
if (isset($options)) {
// return_fields & reference_id
foreach ($options as $key => $value) {
$options[$key] = json_encode($value);
}
$data = array_merge($data, $options);
}
$headers = $this->getHeaders();
$response = self::Post($url, $data, $headers);
if (!$response) return false;
return json_decode($response);
}
/**
* tonalize an article
*
* @param string $article article to tonalize
* @param array $options additional parameters (reference_id and return_fields)
* @return object see the api documentation for the format of this object
*/
public function Tonalize($article, $options = null) {
if (empty($article)) {
throw new Exception('You must include an article to tonalize');
}
$url = self::API_BASE . self::TONALIZE;
$data = array('article' => $article);
if (isset($options)) {
// return_fields & reference_id
foreach ($options as $key => $value) {
$options[$key] = json_encode($value);
}
$data = array_merge($data, $options);
}
$headers = $this->getHeaders();
$response = self::Post($url, $data, $headers);
if (!$response) return false;
return json_decode($response);
}
/**
* flag a response as inaccurate
*
* @param string $phrase the phrase that returns an inaccurate response
* @param string $apiMethod the method that returns an inaccurate response
* @param string $apiVersion the version that returns an inaccurate response
* @param string $callbackUrl a url to call when the phrase has been re-rated
* @param array $options additional parameters (reference_id)
* @return string see the api documentation for this method's response
*/
public function FlagResponse($phrase, $apiMethod = null, $apiVersion = '2.2', $callbackUrl = null, $options = null) {
if (empty($phrase)) {
throw new Exception('You must include a phrase to flag');
}
$url = self::API_BASE . self::FLAG_RESPONSE;
$data = array('phrase' => $phrase);
if (isset($apiMethod)) $data['apiMethod'] = $apiMethod;
if (isset($apiVersion)) $data['apiVersion'] = $apiVersion;
if (isset($callbackUrl)) $data['callbackUrl'] = $callbackUrl;
if (isset($options)) {
// reference_id
foreach ($options as $key => $value) {
$options[$key] = json_encode($value);
}
$data = array_merge($data, $options);
}
$headers = $this->getHeaders();
$response = self::Post($url, $data, $headers);
return $response;
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/core/MY_Loader.php | application/core/MY_Loader.php | <?php if (! defined('BASEPATH')) exit('No direct script access allowed');
/**
* Sparks
*
* An open source application development framework for PHP 5.1.6 or newer
*
* @package CodeIgniter
* @author CodeIgniter Reactor Dev Team
* @author Kenny Katzgrau <katzgrau@gmail.com>
* @since CodeIgniter Version 1.0
* @filesource
*/
/**
* Loader Class
*
* Loads views and files
*
* @package CodeIgniter
* @subpackage Libraries
* @author CodeIgniter Reactor Dev Team
* @author Kenny Katzgrau <katzgrau@gmail.com>
* @category Loader
* @link http://codeigniter.com/user_guide/libraries/loader.html
*/
class MY_Loader extends CI_Loader
{
/**
* Keep track of which sparks are loaded. This will come in handy for being
* speedy about loading files later.
*
* @var array
*/
var $_ci_loaded_sparks = array();
/**
* Is this version less than CI 2.1.0? If so, accomodate
* @bubbafoley's world-destroying change at: http://bit.ly/sIqR7H
* @var bool
*/
var $_is_lt_210 = false;
/**
* Constructor. Define SPARKPATH if it doesn't exist, initialize parent
*/
function __construct()
{
if(!defined('SPARKPATH'))
{
define('SPARKPATH', 'sparks/');
}
$this->_is_lt_210 = (is_callable(array('CI_Loader', 'ci_autoloader'))
|| is_callable(array('CI_Loader', '_ci_autoloader')));
parent::__construct();
}
/**
* To accomodate CI 2.1.0, we override the initialize() method instead of
* the ci_autoloader() method. Once sparks is integrated into CI, we
* can avoid the awkward version-specific logic.
* @return Loader
*/
function initialize()
{
parent::initialize();
if(!$this->_is_lt_210)
{
$this->ci_autoloader();
}
return $this;
}
/**
* Load a spark by it's path within the sparks directory defined by
* SPARKPATH, such as 'markdown/1.0'
* @param string $spark The spark path withint he sparks directory
* @param <type> $autoload An optional array of items to autoload
* in the format of:
* array (
* 'helper' => array('somehelper')
* )
* @return <type>
*/
function spark($spark, $autoload = array())
{
if(is_array($spark))
{
foreach($spark as $s)
{
$this->spark($s);
}
}
$spark = ltrim($spark, '/');
$spark = rtrim($spark, '/');
$spark_path = SPARKPATH . $spark . '/';
$parts = explode('/', $spark);
$spark_slug = strtolower($parts[0]);
# If we've already loaded this spark, bail
if(array_key_exists($spark_slug, $this->_ci_loaded_sparks))
{
return true;
}
# Check that it exists. CI Doesn't check package existence by itself
if(!file_exists($spark_path))
{
show_error("Cannot find spark path at $spark_path");
}
if(count($parts) == 2)
{
$this->_ci_loaded_sparks[$spark_slug] = $spark;
}
$this->add_package_path($spark_path);
foreach($autoload as $type => $read)
{
if($type == 'library')
$this->library($read);
elseif($type == 'model')
$this->model($read);
elseif($type == 'config')
$this->config($read);
elseif($type == 'helper')
$this->helper($read);
elseif($type == 'view')
$this->view($read);
else
show_error ("Could not autoload object of type '$type' ($read) for spark $spark");
}
// Looks for a spark's specific autoloader
$this->ci_autoloader($spark_path);
return true;
}
/**
* Pre-CI 2.0.3 method for backward compatility.
*
* @param null $basepath
* @return void
*/
function _ci_autoloader($basepath = NULL)
{
$this->ci_autoloader($basepath);
}
/**
* Specific Autoloader (99% ripped from the parent)
*
* The config/autoload.php file contains an array that permits sub-systems,
* libraries, and helpers to be loaded automatically.
*
* @param array|null $basepath
* @return void
*/
function ci_autoloader($basepath = NULL)
{
if($basepath !== NULL)
{
$autoload_path = $basepath.'config/autoload'.EXT;
}
else
{
$autoload_path = APPPATH.'config/autoload'.EXT;
}
if(! file_exists($autoload_path))
{
return FALSE;
}
include($autoload_path);
if ( ! isset($autoload))
{
return FALSE;
}
if($this->_is_lt_210 || $basepath !== NULL)
{
// Autoload packages
if (isset($autoload['packages']))
{
foreach ($autoload['packages'] as $package_path)
{
$this->add_package_path($package_path);
}
}
}
// Autoload sparks
if (isset($autoload['sparks']))
{
foreach ($autoload['sparks'] as $spark)
{
$this->spark($spark);
}
}
if($this->_is_lt_210 || $basepath !== NULL)
{
if (isset($autoload['config']))
{
// Load any custom config file
if (count($autoload['config']) > 0)
{
$CI =& get_instance();
foreach ($autoload['config'] as $key => $val)
{
$CI->config->load($val);
}
}
}
// Autoload helpers and languages
foreach (array('helper', 'language') as $type)
{
if (isset($autoload[$type]) AND count($autoload[$type]) > 0)
{
$this->$type($autoload[$type]);
}
}
// A little tweak to remain backward compatible
// The $autoload['core'] item was deprecated
if ( ! isset($autoload['libraries']) AND isset($autoload['core']))
{
$autoload['libraries'] = $autoload['core'];
}
// Load libraries
if (isset($autoload['libraries']) AND count($autoload['libraries']) > 0)
{
// Load the database driver.
if (in_array('database', $autoload['libraries']))
{
$this->database();
$autoload['libraries'] = array_diff($autoload['libraries'], array('database'));
}
// Load all other libraries
foreach ($autoload['libraries'] as $item)
{
$this->library($item);
}
}
// Autoload models
if (isset($autoload['model']))
{
$this->model($autoload['model']);
}
}
}
} | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/core/MY_Controller.php | application/core/MY_Controller.php | <?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->template->set_layout('default');
}
}
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/doctypes.php | application/config/doctypes.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
$_doctypes = array(
'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">',
'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">'
);
/* End of file doctypes.php */
/* Location: ./application/config/doctypes.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/smileys.php | application/config/smileys.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| SMILEYS
| -------------------------------------------------------------------
| This file contains an array of smileys for use with the emoticon helper.
| Individual images can be used to replace multiple simileys. For example:
| :-) and :) use the same image replacement.
|
| Please see user guide for more info:
| http://codeigniter.com/user_guide/helpers/smiley_helper.html
|
*/
$smileys = array(
// smiley image name width height alt
':-)' => array('grin.gif', '19', '19', 'grin'),
':lol:' => array('lol.gif', '19', '19', 'LOL'),
':cheese:' => array('cheese.gif', '19', '19', 'cheese'),
':)' => array('smile.gif', '19', '19', 'smile'),
';-)' => array('wink.gif', '19', '19', 'wink'),
';)' => array('wink.gif', '19', '19', 'wink'),
':smirk:' => array('smirk.gif', '19', '19', 'smirk'),
':roll:' => array('rolleyes.gif', '19', '19', 'rolleyes'),
':-S' => array('confused.gif', '19', '19', 'confused'),
':wow:' => array('surprise.gif', '19', '19', 'surprised'),
':bug:' => array('bigsurprise.gif', '19', '19', 'big surprise'),
':-P' => array('tongue_laugh.gif', '19', '19', 'tongue laugh'),
'%-P' => array('tongue_rolleye.gif', '19', '19', 'tongue rolleye'),
';-P' => array('tongue_wink.gif', '19', '19', 'tongue wink'),
':P' => array('raspberry.gif', '19', '19', 'raspberry'),
':blank:' => array('blank.gif', '19', '19', 'blank stare'),
':long:' => array('longface.gif', '19', '19', 'long face'),
':ohh:' => array('ohh.gif', '19', '19', 'ohh'),
':grrr:' => array('grrr.gif', '19', '19', 'grrr'),
':gulp:' => array('gulp.gif', '19', '19', 'gulp'),
'8-/' => array('ohoh.gif', '19', '19', 'oh oh'),
':down:' => array('downer.gif', '19', '19', 'downer'),
':red:' => array('embarrassed.gif', '19', '19', 'red face'),
':sick:' => array('sick.gif', '19', '19', 'sick'),
':shut:' => array('shuteye.gif', '19', '19', 'shut eye'),
':-/' => array('hmm.gif', '19', '19', 'hmmm'),
'>:(' => array('mad.gif', '19', '19', 'mad'),
':mad:' => array('mad.gif', '19', '19', 'mad'),
'>:-(' => array('angry.gif', '19', '19', 'angry'),
':angry:' => array('angry.gif', '19', '19', 'angry'),
':zip:' => array('zip.gif', '19', '19', 'zipper'),
':kiss:' => array('kiss.gif', '19', '19', 'kiss'),
':ahhh:' => array('shock.gif', '19', '19', 'shock'),
':coolsmile:' => array('shade_smile.gif', '19', '19', 'cool smile'),
':coolsmirk:' => array('shade_smirk.gif', '19', '19', 'cool smirk'),
':coolgrin:' => array('shade_grin.gif', '19', '19', 'cool grin'),
':coolhmm:' => array('shade_hmm.gif', '19', '19', 'cool hmm'),
':coolmad:' => array('shade_mad.gif', '19', '19', 'cool mad'),
':coolcheese:' => array('shade_cheese.gif', '19', '19', 'cool cheese'),
':vampire:' => array('vampire.gif', '19', '19', 'vampire'),
':snake:' => array('snake.gif', '19', '19', 'snake'),
':exclaim:' => array('exclaim.gif', '19', '19', 'excaim'),
':question:' => array('question.gif', '19', '19', 'question') // no comma after last item
);
/* End of file smileys.php */
/* Location: ./application/config/smileys.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/profiler.php | application/config/profiler.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Profiler Sections
| -------------------------------------------------------------------------
| This file lets you determine whether or not various sections of Profiler
| data are displayed when the Profiler is enabled.
| Please see the user guide for info:
|
| http://codeigniter.com/user_guide/general/profiling.html
|
*/
/* End of file profiler.php */
/* Location: ./application/config/profiler.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/mimes.php | application/config/mimes.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| MIME TYPES
| -------------------------------------------------------------------
| This file contains an array of mime types. It is used by the
| Upload class to help identify allowed file types.
|
*/
$mimes = array( 'hqx' => 'application/mac-binhex40',
'cpt' => 'application/mac-compactpro',
'csv' => array('text/x-comma-separated-values', 'text/comma-separated-values', 'application/octet-stream', 'application/vnd.ms-excel', 'application/x-csv', 'text/x-csv', 'text/csv', 'application/csv', 'application/excel', 'application/vnd.msexcel'),
'bin' => 'application/macbinary',
'dms' => 'application/octet-stream',
'lha' => 'application/octet-stream',
'lzh' => 'application/octet-stream',
'exe' => array('application/octet-stream', 'application/x-msdownload'),
'class' => 'application/octet-stream',
'psd' => 'application/x-photoshop',
'so' => 'application/octet-stream',
'sea' => 'application/octet-stream',
'dll' => 'application/octet-stream',
'oda' => 'application/oda',
'pdf' => array('application/pdf', 'application/x-download'),
'ai' => 'application/postscript',
'eps' => 'application/postscript',
'ps' => 'application/postscript',
'smi' => 'application/smil',
'smil' => 'application/smil',
'mif' => 'application/vnd.mif',
'xls' => array('application/excel', 'application/vnd.ms-excel', 'application/msexcel'),
'ppt' => array('application/powerpoint', 'application/vnd.ms-powerpoint'),
'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',
'php' => 'application/x-httpd-php',
'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',
'swf' => 'application/x-shockwave-flash',
'sit' => 'application/x-stuffit',
'tar' => 'application/x-tar',
'tgz' => array('application/x-tar', 'application/x-gzip-compressed'),
'xhtml' => 'application/xhtml+xml',
'xht' => 'application/xhtml+xml',
'zip' => array('application/x-zip', 'application/zip', 'application/x-zip-compressed'),
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mpga' => 'audio/mpeg',
'mp2' => 'audio/mpeg',
'mp3' => array('audio/mpeg', 'audio/mpg', 'audio/mpeg3', 'audio/mp3'),
'aif' => 'audio/x-aiff',
'aiff' => 'audio/x-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' => array('audio/x-wav', 'audio/wave', 'audio/wav'),
'bmp' => array('image/bmp', 'image/x-windows-bmp'),
'gif' => 'image/gif',
'jpeg' => array('image/jpeg', 'image/pjpeg'),
'jpg' => array('image/jpeg', 'image/pjpeg'),
'jpe' => array('image/jpeg', 'image/pjpeg'),
'png' => array('image/png', 'image/x-png'),
'tiff' => 'image/tiff',
'tif' => 'image/tiff',
'css' => 'text/css',
'html' => 'text/html',
'htm' => 'text/html',
'shtml' => 'text/html',
'txt' => 'text/plain',
'text' => 'text/plain',
'log' => array('text/plain', 'text/x-log'),
'rtx' => 'text/richtext',
'rtf' => 'text/rtf',
'xml' => 'text/xml',
'xsl' => 'text/xml',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'mpe' => 'video/mpeg',
'qt' => 'video/quicktime',
'mov' => 'video/quicktime',
'avi' => 'video/x-msvideo',
'movie' => 'video/x-sgi-movie',
'doc' => 'application/msword',
'docx' => array('application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/zip'),
'xlsx' => array('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/zip'),
'word' => array('application/msword', 'application/octet-stream'),
'xl' => 'application/excel',
'eml' => 'message/rfc822',
'json' => array('application/json', 'text/json')
);
/* End of file mimes.php */
/* Location: ./application/config/mimes.php */
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/hooks.php | application/config/hooks.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| Hooks
| -------------------------------------------------------------------------
| This file lets you define "hooks" to extend CI without hacking the core
| files. Please see the user guide for info:
|
| http://codeigniter.com/user_guide/general/hooks.html
|
*/
/* End of file hooks.php */
/* Location: ./application/config/hooks.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/migration.php | application/config/migration.php | <?php defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Enable/Disable Migrations
|--------------------------------------------------------------------------
|
| Migrations are disabled by default but should be enabled
| whenever you intend to do a schema migration.
|
*/
$config['migration_enabled'] = FALSE;
/*
|--------------------------------------------------------------------------
| Migrations version
|--------------------------------------------------------------------------
|
| This is used to set migration version that the file system should be on.
| If you run $this->migration->latest() this is the version that schema will
| be upgraded / downgraded to.
|
*/
$config['migration_version'] = 0;
/*
|--------------------------------------------------------------------------
| Migrations Path
|--------------------------------------------------------------------------
|
| Path to your migrations folder.
| Typically, it will be within your application path.
| Also, writing permission is required within the migrations path.
|
*/
$config['migration_path'] = APPPATH . 'migrations/';
/* End of file migration.php */
/* Location: ./application/config/migration.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/autoload.php | application/config/autoload.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| AUTO-LOADER
| -------------------------------------------------------------------
| This file specifies which systems should be loaded by default.
|
| In order to keep the framework as light-weight as possible only the
| absolute minimal resources are loaded by default. For example,
| the database is not connected to automatically since no assumption
| is made regarding whether you intend to use it. This file lets
| you globally define which systems you would like loaded with every
| request.
|
| -------------------------------------------------------------------
| Instructions
| -------------------------------------------------------------------
|
| These are the things you can load automatically:
|
| 1. Packages
| 2. Libraries
| 3. Helper files
| 4. Custom config files
| 5. Language files
| 6. Models
|
*/
/*
| -------------------------------------------------------------------
| Auto-load Packges
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared');
|
*/
$autoload['packages'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Libraries
| -------------------------------------------------------------------
| These are the classes located in the system/libraries folder
| or in your application/libraries folder.
|
| Prototype:
|
| $autoload['libraries'] = array('database', 'session', 'xmlrpc');
*/
$autoload['libraries'] = array(
'parser'
);
/*
| -------------------------------------------------------------------
| Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['helper'] = array('url', 'file');
*/
$autoload['helper'] = array(
'date'
);
/*
| -------------------------------------------------------------------
| Auto-load Config files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['config'] = array('config1', 'config2');
|
| NOTE: This item is intended for use ONLY if you have created custom
| config files. Otherwise, leave it blank.
|
*/
$autoload['config'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Language files
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['language'] = array('lang1', 'lang2');
|
| NOTE: Do not include the "_lang" part of your file. For example
| "codeigniter_lang.php" would be referenced as array('codeigniter');
|
*/
$autoload['language'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Models
| -------------------------------------------------------------------
| Prototype:
|
| $autoload['model'] = array('model1', 'model2');
|
*/
$autoload['model'] = array();
/*
| -------------------------------------------------------------------
| Auto-load Sparks
| -------------------------------------------------------------------
| Prototype:
|
|
*/
$autoload['sparks'] = array(
'template/1.9.0'
);
/* End of file autoload.php */
/* Location: ./application/config/autoload.php */
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/foreign_chars.php | application/config/foreign_chars.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| Foreign Characters
| -------------------------------------------------------------------
| This file contains an array of foreign characters for transliteration
| conversion used by the Text helper
|
*/
$foreign_characters = array(
'/ä|æ|ǽ/' => 'ae',
'/ö|œ/' => 'oe',
'/ü/' => 'ue',
'/Ä/' => 'Ae',
'/Ü/' => 'Ue',
'/Ö/' => 'Oe',
'/À|Á|Â|Ã|Ä|Å|Ǻ|Ā|Ă|Ą|Ǎ/' => 'A',
'/à|á|â|ã|å|ǻ|ā|ă|ą|ǎ|ª/' => 'a',
'/Ç|Ć|Ĉ|Ċ|Č/' => 'C',
'/ç|ć|ĉ|ċ|č/' => 'c',
'/Ð|Ď|Đ/' => 'D',
'/ð|ď|đ/' => 'd',
'/È|É|Ê|Ë|Ē|Ĕ|Ė|Ę|Ě/' => 'E',
'/è|é|ê|ë|ē|ĕ|ė|ę|ě/' => 'e',
'/Ĝ|Ğ|Ġ|Ģ/' => 'G',
'/ĝ|ğ|ġ|ģ/' => 'g',
'/Ĥ|Ħ/' => 'H',
'/ĥ|ħ/' => 'h',
'/Ì|Í|Î|Ï|Ĩ|Ī|Ĭ|Ǐ|Į|İ/' => 'I',
'/ì|í|î|ï|ĩ|ī|ĭ|ǐ|į|ı/' => 'i',
'/Ĵ/' => 'J',
'/ĵ/' => 'j',
'/Ķ/' => 'K',
'/ķ/' => 'k',
'/Ĺ|Ļ|Ľ|Ŀ|Ł/' => 'L',
'/ĺ|ļ|ľ|ŀ|ł/' => 'l',
'/Ñ|Ń|Ņ|Ň/' => 'N',
'/ñ|ń|ņ|ň|ʼn/' => 'n',
'/Ò|Ó|Ô|Õ|Ō|Ŏ|Ǒ|Ő|Ơ|Ø|Ǿ/' => 'O',
'/ò|ó|ô|õ|ō|ŏ|ǒ|ő|ơ|ø|ǿ|º/' => 'o',
'/Ŕ|Ŗ|Ř/' => 'R',
'/ŕ|ŗ|ř/' => 'r',
'/Ś|Ŝ|Ş|Š/' => 'S',
'/ś|ŝ|ş|š|ſ/' => 's',
'/Ţ|Ť|Ŧ/' => 'T',
'/ţ|ť|ŧ/' => 't',
'/Ù|Ú|Û|Ũ|Ū|Ŭ|Ů|Ű|Ų|Ư|Ǔ|Ǖ|Ǘ|Ǚ|Ǜ/' => 'U',
'/ù|ú|û|ũ|ū|ŭ|ů|ű|ų|ư|ǔ|ǖ|ǘ|ǚ|ǜ/' => 'u',
'/Ý|Ÿ|Ŷ/' => 'Y',
'/ý|ÿ|ŷ/' => 'y',
'/Ŵ/' => 'W',
'/ŵ/' => 'w',
'/Ź|Ż|Ž/' => 'Z',
'/ź|ż|ž/' => 'z',
'/Æ|Ǽ/' => 'AE',
'/ß/'=> 'ss',
'/IJ/' => 'IJ',
'/ij/' => 'ij',
'/Œ/' => 'OE',
'/ƒ/' => 'f'
);
/* End of file foreign_chars.php */
/* Location: ./application/config/foreign_chars.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/database.php | application/config/database.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| DATABASE CONNECTIVITY SETTINGS
| -------------------------------------------------------------------
| This file will contain the settings needed to access your database.
|
| For complete instructions please consult the 'Database Connection'
| page of the User Guide.
|
| -------------------------------------------------------------------
| EXPLANATION OF VARIABLES
| -------------------------------------------------------------------
|
| ['hostname'] The hostname of your database server.
| ['username'] The username used to connect to the database
| ['password'] The password used to connect to the database
| ['database'] The name of the database you want to connect to
| ['dbdriver'] The database type. ie: mysql. Currently supported:
mysql, mysqli, postgre, odbc, mssql, sqlite, oci8
| ['dbprefix'] You can add an optional prefix, which will be added
| to the table name when using the Active Record class
| ['pconnect'] TRUE/FALSE - Whether to use a persistent connection
| ['db_debug'] TRUE/FALSE - Whether database errors should be displayed.
| ['cache_on'] TRUE/FALSE - Enables/disables query caching
| ['cachedir'] The path to the folder where cache files should be stored
| ['char_set'] The character set used in communicating with the database
| ['dbcollat'] The character collation used in communicating with the database
| NOTE: For MySQL and MySQLi databases, this setting is only used
| as a backup if your server is running PHP < 5.2.3 or MySQL < 5.0.7
| (and in table creation queries made with DB Forge).
| There is an incompatibility in PHP with mysql_real_escape_string() which
| can make your site vulnerable to SQL injection if you are using a
| multi-byte character set and are running versions lower than these.
| Sites using Latin-1 or UTF-8 database character set and collation are unaffected.
| ['swap_pre'] A default table prefix that should be swapped with the dbprefix
| ['autoinit'] Whether or not to automatically initialize the database.
| ['stricton'] TRUE/FALSE - forces 'Strict Mode' connections
| - good for ensuring strict SQL while developing
|
| The $active_group variable lets you choose which connection group to
| make active. By default there is only one group (the 'default' group).
|
| The $active_record variables lets you determine whether or not to load
| the active record class
*/
$active_group = 'default';
$active_record = TRUE;
$db['default']['hostname'] = 'localhost';
$db['default']['username'] = '';
$db['default']['password'] = '';
$db['default']['database'] = '';
$db['default']['dbdriver'] = 'mysql';
$db['default']['dbprefix'] = '';
$db['default']['pconnect'] = TRUE;
$db['default']['db_debug'] = TRUE;
$db['default']['cache_on'] = FALSE;
$db['default']['cachedir'] = '';
$db['default']['char_set'] = 'utf8';
$db['default']['dbcollat'] = 'utf8_general_ci';
$db['default']['swap_pre'] = '';
$db['default']['autoinit'] = TRUE;
$db['default']['stricton'] = FALSE;
/* End of file database.php */
/* Location: ./application/config/database.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/config.php | application/config/config.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will guess the protocol, domain and
| path to your installation.
|
*/
$config['base_url'] = '';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = 'index.php';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'AUTO' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'AUTO' Default - auto detects
| 'PATH_INFO' Uses the PATH_INFO
| 'QUERY_STRING' Uses the QUERY_STRING
| 'REQUEST_URI' Uses the REQUEST_URI
| 'ORIG_PATH_INFO' Uses the ORIG_PATH_INFO
|
*/
$config['uri_protocol'] = 'AUTO';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify with a regular expression 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~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd'; // experimental not currently in use
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| If you have enabled error logging, you can set an error threshold to
| determine what gets logged. Threshold options are:
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 0;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ folder. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| system/cache/ folder. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class or the Session class you
| MUST set an encryption key. See the user guide for info.
|
*/
$config['encryption_key'] = '';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_cookie_name' = the name you want for the cookie
| 'sess_expiration' = the number of SECONDS you want the session to last.
| by default sessions last 7200 seconds (two hours). Set to zero for no expiration.
| 'sess_expire_on_close' = Whether to cause the session to expire automatically
| when the browser window is closed
| 'sess_encrypt_cookie' = Whether to encrypt the cookie
| 'sess_use_database' = Whether to save the session data to a database
| 'sess_table_name' = The name of the session database table
| 'sess_match_ip' = Whether to match the user's IP address when reading the session data
| 'sess_match_useragent' = Whether to match the User Agent when reading the session data
| 'sess_time_to_update' = how many seconds between CI refreshing Session Information
|
*/
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = FALSE;
$config['sess_table_name'] = 'ci_sessions';
$config['sess_match_ip'] = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookies will only be set if a secure HTTPS connection exists.
|
*/
$config['cookie_prefix'] = "";
$config['cookie_domain'] = "";
$config['cookie_path'] = "/";
$config['cookie_secure'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or 'gmt'. This pref tells the system whether to use
| your server's local time as the master 'now' reference, or convert it to
| GMT. See the 'date helper' page of the user guide for information
| regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
*/
$config['rewrite_short_tags'] = TRUE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy IP
| addresses from which CodeIgniter should trust the HTTP_X_FORWARDED_FOR
| header in order to properly identify the visitor's IP address.
| Comma-delimited, e.g. '10.0.1.200,10.0.1.201'
|
*/
$config['proxy_ips'] = '';
/* End of file config.php */
/* Location: ./application/config/config.php */
| php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/routes.php | application/config/routes.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| http://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There area two reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router what URI segments to use if those provided
| in the URL cannot be matched to a valid route.
|
*/
$route['default_controller'] = "home";
$route['404_override'] = '';
/* End of file routes.php */
/* Location: ./application/config/routes.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/user_agents.php | application/config/user_agents.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
| -------------------------------------------------------------------
| USER AGENT TYPES
| -------------------------------------------------------------------
| 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.
|
*/
$platforms = array (
'windows nt 6.0' => 'Windows Longhorn',
'windows nt 5.2' => 'Windows 2003',
'windows nt 5.0' => 'Windows 2000',
'windows nt 5.1' => 'Windows XP',
'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' => 'Unknown Windows OS',
'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'
);
// The order of this array should NOT be changed. Many browsers return
// multiple browser types so we want to identify the sub-type first.
$browsers = array(
'Flock' => 'Flock',
'Chrome' => 'Chrome',
'Opera' => 'Opera',
'MSIE' => 'Internet Explorer',
'Internet Explorer' => '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'
);
$mobiles = array(
// 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",
'hiptop' => "Danger Hiptop",
'nec-' => "NEC",
'panasonic' => "Panasonic",
'philips' => "Philips",
'sagem' => "Sagem",
'sanyo' => "Sanyo",
'spv' => "SPV",
'zte' => "ZTE",
'sendo' => "Sendo",
// Operating Systems
'symbian' => "Symbian",
'SymbianOS' => "SymbianOS",
'elaine' => "Palm",
'palm' => "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",
// 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"
);
// There are hundreds of bots but these are the most common.
$robots = array(
'googlebot' => 'Googlebot',
'msnbot' => 'MSNBot',
'slurp' => 'Inktomi Slurp',
'yahoo' => 'Yahoo',
'askjeeves' => 'AskJeeves',
'fastcrawler' => 'FastCrawler',
'infoseek' => 'InfoSeek Robot 1.0',
'lycos' => 'Lycos'
);
/* End of file user_agents.php */
/* Location: ./application/config/user_agents.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
bilalq/Tranquillity-Editor | https://github.com/bilalq/Tranquillity-Editor/blob/6e936d7bef75e50d0f056bf0c4bbdaef9210f340/application/config/constants.php | application/config/constants.php | <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| File and Directory Modes
|--------------------------------------------------------------------------
|
| These prefs are used when checking and setting modes when working
| with the file system. The defaults are fine on servers with proper
| security, but you may wish (or even need) to change the values in
| certain environments (Apache running a separate process for each
| user, PHP under CGI with Apache suEXEC, etc.). Octal values should
| always be used to set the mode correctly.
|
*/
define('FILE_READ_MODE', 0644);
define('FILE_WRITE_MODE', 0666);
define('DIR_READ_MODE', 0755);
define('DIR_WRITE_MODE', 0777);
/*
|--------------------------------------------------------------------------
| File Stream Modes
|--------------------------------------------------------------------------
|
| These modes are used when working with fopen()/popen()
|
*/
define('FOPEN_READ', 'rb');
define('FOPEN_READ_WRITE', 'r+b');
define('FOPEN_WRITE_CREATE_DESTRUCTIVE', 'wb'); // truncates existing file data, use with care
define('FOPEN_READ_WRITE_CREATE_DESTRUCTIVE', 'w+b'); // truncates existing file data, use with care
define('FOPEN_WRITE_CREATE', 'ab');
define('FOPEN_READ_WRITE_CREATE', 'a+b');
define('FOPEN_WRITE_CREATE_STRICT', 'xb');
define('FOPEN_READ_WRITE_CREATE_STRICT', 'x+b');
/* End of file constants.php */
/* Location: ./application/config/constants.php */ | php | MIT | 6e936d7bef75e50d0f056bf0c4bbdaef9210f340 | 2026-01-05T04:46:50.686838Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/EkoFeedBundle.php | EkoFeedBundle.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle;
use Eko\FeedBundle\DependencyInjection\Compiler\FeedDumpServicePass;
use Eko\FeedBundle\DependencyInjection\Compiler\FeedFormatterPass;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Bundle\Bundle;
/**
* EkoFeedBundle.
*
* This is the main bundle class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class EkoFeedBundle extends Bundle
{
/**
* {@inheritdoc}
*/
public function build(ContainerBuilder $container): void
{
parent::build($container);
$container->addCompilerPass(new FeedFormatterPass());
$container->addCompilerPass(new FeedDumpServicePass());
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Formatter/AtomFormatter.php | Formatter/AtomFormatter.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Formatter;
use Eko\FeedBundle\Feed\Feed;
use Eko\FeedBundle\Field\Item\ItemField;
use Eko\FeedBundle\Item\Writer\ItemInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Atom formatter.
*
* This class provides an Atom formatter
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class AtomFormatter extends Formatter implements FormatterInterface
{
/**
* Construct a formatter with given feed.
*
* @param TranslatorInterface $translator A Symfony translator service instance
* @param string|null $domain A Symfony translation domain
*
* @throws \InvalidArgumentException if author is not filled in bundle configuration
*/
public function __construct(TranslatorInterface $translator, $domain = null)
{
$this->itemFields = [
new ItemField('id', 'getFeedItemLink', ['cdata' => false]),
new ItemField('title', 'getFeedItemTitle', ['cdata' => true]),
new ItemField('summary', 'getFeedItemDescription', ['cdata' => true], ['type' => 'html']),
new ItemField('link', 'getFeedItemLink', ['attribute' => true, 'attribute_name' => 'href']),
new ItemField('updated', 'getFeedItemPubDate', ['date_format' => \DateTime::ATOM]),
];
parent::__construct($translator, $domain);
}
/**
* Sets feed instance.
*
* @param Feed $feed
*/
public function setFeed(Feed $feed)
{
$author = $feed->get('author');
if (empty($author)) {
throw new \InvalidArgumentException('Atom formatter requires an "author" parameter in configuration.');
}
$this->feed = $feed;
$this->initialize();
}
/**
* {@inheritdoc}
*/
public function initialize()
{
parent::initialize();
$encoding = $this->feed->get('encoding');
$this->dom = new \DOMDocument('1.0', $encoding);
$channel = $this->dom->createElement('feed');
$channel->setAttribute('xmlns', 'http://www.w3.org/2005/Atom');
$channel = $this->dom->appendChild($channel);
$identifier = $this->dom->createElement('id', $this->feed->get('link'));
$title = $this->translate($this->feed->get('title'));
$title = $this->dom->createElement('title', $title);
$description = $this->translate($this->feed->get('description'));
$subtitle = $this->dom->createElement('subtitle', $description);
$name = $this->dom->createElement('name', $this->feed->get('author'));
$link = $this->dom->createElement('link');
$link->setAttribute('href', $this->feed->get('link'));
$link->setAttribute('rel', 'self');
$link->setAttribute('type', 'application/rss+xml');
$date = new \DateTime();
$updated = $this->dom->createElement('updated', $date->format(\DateTime::ATOM));
$author = $this->dom->createElement('author');
$author->appendChild($name);
$channel->appendChild($title);
$channel->appendChild($subtitle);
$channel->appendChild($link);
$channel->appendChild($updated);
$channel->appendChild($identifier);
$channel->appendChild($author);
// Add custom channel fields
$this->addChannelFields($channel);
// Add field items
$items = $this->feed->getItems();
foreach ($items as $item) {
if (null === $item) {
continue;
}
$this->addItem($channel, $item);
}
}
/**
* {@inheritdoc}
*/
public function addItem(\DOMElement $channel, ItemInterface $item)
{
$node = $this->dom->createElement('entry');
$node = $channel->appendChild($node);
foreach ($this->itemFields as $field) {
$elements = $this->format($field, $item);
foreach ($elements as $element) {
$node->appendChild($element);
}
}
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'atom';
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Formatter/RssFormatter.php | Formatter/RssFormatter.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Formatter;
use Eko\FeedBundle\Feed\Feed;
use Eko\FeedBundle\Field\Item\ItemField;
use Eko\FeedBundle\Item\Writer\ItemInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* RSS formatter.
*
* This class provides an RSS formatter
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class RssFormatter extends Formatter implements FormatterInterface
{
/**
* Construct a formatter with given feed.
*
* @param TranslatorInterface $translator A Symfony translator service instance
* @param string|null $domain A Symfony translation domain
*/
public function __construct(TranslatorInterface $translator, $domain = null)
{
$this->itemFields = [
new ItemField('title', 'getFeedItemTitle', ['cdata' => true]),
new ItemField('description', 'getFeedItemDescription', ['cdata' => true]),
new ItemField('link', 'getFeedItemLink'),
new ItemField('pubDate', 'getFeedItemPubDate', ['date_format' => \DateTime::RSS]),
];
parent::__construct($translator, $domain);
}
/**
* Sets feed instance.
*
* @param Feed $feed
*/
public function setFeed(Feed $feed)
{
$this->feed = $feed;
$this->initialize();
}
/**
* {@inheritdoc}
*/
public function initialize()
{
parent::initialize();
$encoding = $this->feed->get('encoding');
$this->dom = new \DOMDocument('1.0', $encoding);
$root = $this->dom->createElement('rss');
$root->setAttribute('version', '2.0');
$root = $this->dom->appendChild($root);
$channel = $this->dom->createElement('channel');
$channel = $root->appendChild($channel);
$title = $this->translate($this->feed->get('title'));
$title = $this->dom->createElement('title', $title);
$channel->appendChild($title);
$description = $this->translate($this->feed->get('description'));
$description = $this->dom->createElement('description', $description);
$channel->appendChild($description);
$link = $this->dom->createElement('link', $this->feed->get('link'));
$channel->appendChild($link);
$date = new \DateTime();
$lastBuildDate = $this->dom->createElement('lastBuildDate', $date->format(\DateTime::RSS));
$channel->appendChild($lastBuildDate);
// Add custom channel fields
$this->addChannelFields($channel);
// Add feed items
$items = $this->feed->getItems();
foreach ($items as $item) {
$this->addItem($channel, $item);
}
}
/**
* {@inheritdoc}
*/
public function addItem(\DOMElement $channel, ItemInterface $item)
{
$node = $this->dom->createElement('item');
$node = $channel->appendChild($node);
foreach ($this->itemFields as $field) {
$elements = $this->format($field, $item);
foreach ($elements as $element) {
$node->appendChild($element);
}
}
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'rss';
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Formatter/Formatter.php | Formatter/Formatter.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Formatter;
use Eko\FeedBundle\Feed\Feed;
use Eko\FeedBundle\Field\Channel\GroupChannelField;
use Eko\FeedBundle\Field\Item\GroupItemField;
use Eko\FeedBundle\Field\Item\ItemField;
use Eko\FeedBundle\Field\Item\ItemFieldInterface;
use Eko\FeedBundle\Field\Item\MediaItemField;
use Eko\FeedBundle\Item\Writer\ItemInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* Formatter.
*
* This class provides formatter methods
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class Formatter
{
/**
* @var Feed A feed instance
*/
protected $feed;
/**
* @var TranslatorInterface
*/
protected $translator;
/**
* @var string|null
*/
protected $domain;
/**
* @var \DOMDocument XML DOMDocument
*/
protected $dom;
/**
* @var array Contain item Field instances for this formatter
*/
protected $itemFields = [];
/**
* Construct a formatter with given feed.
*
* @param TranslatorInterface $translator A Symfony translator service instance
* @param string|null $domain A Symfony translation domain
*/
public function __construct(TranslatorInterface $translator, $domain = null)
{
$this->translator = $translator;
$this->domain = $domain;
}
/**
* Initializes feed.
*/
public function initialize()
{
$this->itemFields = array_merge($this->itemFields, $this->feed->getItemFields());
}
/**
* This method render the given feed transforming the DOMDocument to XML.
*
* @return string
*/
public function render()
{
$this->dom->formatOutput = true;
return $this->dom->saveXml();
}
/**
* Adds channel fields to given channel.
*
* @param \DOMElement $channel
*/
protected function addChannelFields(\DOMElement $channel)
{
foreach ($this->feed->getChannelFields() as $field) {
if ($field instanceof GroupChannelField) {
$parent = $this->dom->createElement($field->getName());
foreach ($field->getItemFields() as $childField) {
$child = $this->dom->createElement($childField->getName(), $childField->getValue());
$this->addAttributes($child, $childField);
$parent->appendChild($child);
}
} else {
$parent = $this->dom->createElement($field->getName(), $field->getValue());
}
$this->addAttributes($parent, $field);
$channel->appendChild($parent);
}
}
/**
* Format items field.
*
* @param ItemFieldInterface $field A item field instance
* @param ItemInterface $item An entity instance
*
* @return string
*/
protected function format(ItemFieldInterface $field, ItemInterface $item)
{
$class = get_class($field);
switch ($class) {
case GroupItemField::class:
return $this->formatGroupItemField($field, $item);
break;
case MediaItemField::class:
return $this->formatMediaItemField($field, $item);
break;
case ItemField::class:
return $this->formatItemField($field, $item);
break;
}
}
/**
* Format a group item field.
*
* @param GroupItemField $field An item field instance
* @param ItemInterface $item An entity instance
*
* @return \DOMElement
*/
protected function formatGroupItemField(GroupItemField $field, ItemInterface $item)
{
$name = $field->getName();
$element = $this->dom->createElement($name);
$this->addAttributes($element, $field, $item);
$itemFields = $field->getItemFields();
foreach ($itemFields as $itemField) {
$class = get_class($itemField);
switch ($class) {
case GroupItemField::class:
$itemElements = $this->formatGroupItemField($itemField, $item);
break;
case MediaItemField::class:
$itemElements = $this->formatMediaItemField($itemField, $item);
break;
case ItemField::class:
$itemElements = $this->formatItemField($itemField, $item);
break;
}
foreach ($itemElements as $itemElement) {
$element->appendChild($itemElement);
}
}
return [$element];
}
/**
* Format a media item field.
*
* @param MediaItemField $field A media item field instance
* @param ItemInterface $item An entity instance
*
* @throws \InvalidArgumentException if media array format waiting to be returned is not well-formatted
*
* @return array|null|\DOMElement
*/
protected function formatMediaItemField(MediaItemField $field, ItemInterface $item)
{
$elements = [];
$method = $field->getMethod();
$values = $item->{$method}();
if (null === $values) {
return $elements;
}
if (!is_array($values) || (is_array($values) && isset($values['value']))) {
$values = [$values];
}
foreach ($values as $value) {
if (!isset($value['type']) || !isset($value['length']) || !isset($value['value'])) {
throw new \InvalidArgumentException('Item media method must returns an array with following keys: type, length & value.');
}
$elementName = $field->getName();
$elementName = $elementName[$this->getName()];
$element = $this->dom->createElement($elementName);
$this->addAttributes($element, $field, $item);
switch ($this->getName()) {
case 'rss':
$element->setAttribute('url', $value['value']);
break;
case 'atom':
$element->setAttribute('rel', 'enclosure');
$element->setAttribute('href', $value['value']);
break;
}
$element->setAttribute('type', $value['type']);
$element->setAttribute('length', $value['length']);
$elements[] = $element;
}
return $elements;
}
/**
* Format an item field.
*
* @param ItemFieldInterface $field An item field instance
* @param ItemInterface $item An entity instance
*
* @return array|\DOMElement
*/
protected function formatItemField(ItemFieldInterface $field, ItemInterface $item)
{
$elements = [];
$method = $field->getMethod();
$values = $item->{$method}();
if (null === $values) {
return $elements;
}
if (!is_array($values)) {
$values = [$values];
}
foreach ($values as $value) {
$elements[] = $this->formatWithOptions($field, $item, $value);
}
return $elements;
}
/**
* Format an item field.
*
* @param ItemFieldInterface $field An item field instance
* @param ItemInterface $item An entity instance
* @param string $value A field value
*
* @throws \InvalidArgumentException
*
* @return \DOMElement
*/
protected function formatWithOptions(ItemFieldInterface $field, ItemInterface $item, $value)
{
$element = null;
$name = $field->getName();
if ($field->get('translatable')) {
$value = $this->translate($value);
}
if ($field->get('cdata')) {
$value = $this->dom->createCDATASection($value);
$element = $this->dom->createElement($name);
$element->appendChild($value);
} elseif ($field->get('attribute')) {
if (!$field->get('attribute_name')) {
throw new \InvalidArgumentException("'attribute' parameter required an 'attribute_name' parameter.");
}
$element = $this->dom->createElement($name);
$element->setAttribute($field->get('attribute_name'), $value);
} else {
if ($format = $field->get('date_format')) {
if (!$value instanceof \DateTime) {
throw new \InvalidArgumentException(sprintf('Field "%s" should be a DateTime instance.', $name));
}
$value = $value->format($format);
}
$element = $this->dom->createElement($name, htmlspecialchars($value));
}
$this->addAttributes($element, $field, $item);
return $element;
}
/**
* Add field attributes to a DOM element.
*
* @param \DOMElement $element A XML DOM element
* @param ItemFieldInterface $field A feed field instance
* @param ItemInterface|null $item A feed item instance
*/
protected function addAttributes(\DOMElement $element, ItemFieldInterface $field, ItemInterface $item = null)
{
foreach ($field->getAttributes() as $key => $value) {
if ($item) {
$key = method_exists($item, $key) ? call_user_func([$item, $key]) : $key;
$value = method_exists($item, $value) ? call_user_func([$item, $value]) : $value;
}
$element->setAttribute($key, $value);
}
}
/**
* Translates a value.
*
* @param string $value
*
* @return string
*/
protected function translate($value)
{
return $this->translator->trans($value, [], $this->domain);
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Formatter/FormatterInterface.php | Formatter/FormatterInterface.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Formatter;
use Eko\FeedBundle\Feed\Feed;
use Eko\FeedBundle\Item\Writer\ItemInterface;
/**
* Formatter interface.
*
* This interface contains the methods that a renderer needs to implement
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
interface FormatterInterface
{
/**
* Sets feed instance.
*
* @param Feed $feed
*/
public function setFeed(Feed $feed);
/**
* Initialize XML DOMDocument.
*
* @abstract
*/
public function initialize();
/**
* Add an entity item to the feed.
*
* @param \DOMElement $channel The channel DOM element
* @param ItemInterface $item An entity object
*/
public function addItem(\DOMElement $channel, ItemInterface $item);
/**
* Returns formatter name.
*
* @return string
*/
public function getName();
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Feed/FeedManager.php | Feed/FeedManager.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Feed;
use Symfony\Component\Routing\RouterInterface;
/**
* FeedManager.
*
* This class manage feeds specified in configuration file
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class FeedManager
{
/**
* @var array
*/
protected $config;
/**
* @var RouterInterface
*/
protected $router;
/**
* @var array
*/
protected $formatters;
/**
* @var array
*/
protected $feeds;
/**
* Constructor.
*
* @param RouterInterface $router A Symfony router instance
* @param array $config Configuration settings
* @param array $formatters Feed formatters list
*/
public function __construct(RouterInterface $router, array $config, array $formatters)
{
$this->config = $config;
$this->router = $router;
$this->formatters = $formatters;
}
/**
* Check if feed exists in configuration under 'feeds' node.
*
* @param string $feed Feed name
*
* @return bool
*/
public function has($feed)
{
return isset($this->config['feeds'][$feed]);
}
/**
* Return specified Feed instance if exists.
*
* @param string $feedName
*
* @throws \InvalidArgumentException
*
* @return Feed
*/
public function get($feedName)
{
if (!$this->has($feedName)) {
throw new \InvalidArgumentException(
sprintf("Specified feed '%s' is not defined in your configuration.", $feedName)
);
}
if (!isset($this->feeds[$feedName])) {
$feed = new Feed($this->config['feeds'][$feedName], $this->formatters);
$feed->setRouter($this->router);
$this->feeds[$feedName] = $feed;
}
return $this->feeds[$feedName];
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Feed/Reader.php | Feed/Reader.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Feed;
use Eko\FeedBundle\Hydrator\HydratorInterface;
use Laminas\Feed\Reader\Feed\FeedInterface;
use Laminas\Feed\Reader\Reader as ZendReader;
/**
* Reader.
*
* This is the main feed reader class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class Reader
{
/**
* @var FeedInterface
*/
protected $feed;
/**
* @var HydratorInterface
*/
protected $hydrator;
/**
* Sets entity hydrator service.
*
* @param HydratorInterface $hydrator
*/
public function setHydrator(HydratorInterface $hydrator)
{
$this->hydrator = $hydrator;
}
/**
* Loads feed from an url or file path.
*
* @param string $file
*
* @return Reader
*/
public function load($file)
{
if (file_exists($file)) {
$this->feed = ZendReader::importFile($file);
} else {
$this->feed = ZendReader::import($file);
}
return $this;
}
/**
* Get feed object previously loaded.
*
* @return FeedInterface
*/
public function get()
{
$this->checkIfFeedIsLoaded();
return $this->feed;
}
/**
* Populate entities with feed entries using hydrator.
*
* @param string $entityName
*
* @throws \RuntimeException if entity name does not exists
*
* @return array
*/
public function populate($entityName)
{
if (!class_exists($entityName)) {
throw new \RuntimeException(sprintf('Entity %s does not exists.', $entityName));
}
$feed = $this->get();
return $this->hydrator->hydrate($feed, $entityName);
}
/**
* Check if a feed is currently loaded.
*
* @throws \RuntimeException if there is no feed loaded
*/
protected function checkIfFeedIsLoaded()
{
if (null === $this->feed) {
throw new \RuntimeException('There is not feed loaded. Please make sure to load a feed before using the get() method.');
}
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Feed/Feed.php | Feed/Feed.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Feed;
use Eko\FeedBundle\Field\Channel\ChannelFieldInterface;
use Eko\FeedBundle\Field\Item\ItemFieldInterface;
use Eko\FeedBundle\Item\Writer\ItemInterface;
use Eko\FeedBundle\Item\Writer\ProxyItem;
use Eko\FeedBundle\Item\Writer\RoutedItemInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
/**
* Feed.
*
* This is the main feed class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class Feed
{
/**
* @var array
*/
protected $config;
/**
* @var array
*/
protected $formatters;
/**
* @var RouterInterface
*/
protected $router;
/**
* @var array
*/
protected $items = [];
/**
* @var array
*/
protected $channelFields = [];
/**
* @var array
*/
protected $itemFields = [];
/**
* Constructor.
*
* @param array $config Configuration settings
* @param array $formatters An array of available formatters services
*/
public function __construct(array $config, array $formatters)
{
$this->config = $config;
$this->formatters = $formatters;
}
/**
* Set the router service.
*
* @param RouterInterface $router
*/
public function setRouter(RouterInterface $router)
{
$this->router = $router;
}
/**
* Set or redefine a configuration value.
*
* @param mixed $parameter A configuration parameter name
* @param mixed $value A value
*
* @return \Eko\FeedBundle\Feed\Feed
*/
public function set($parameter, $value)
{
$this->config[$parameter] = $value;
return $this;
}
/**
* Returns config parameter value.
*
* @param mixed $parameter A configuration parameter name
* @param mixed|null $default A default value if not found
*
* @return mixed
*/
public function get($parameter, $default = null)
{
if ('link' == $parameter) {
return $this->getLink();
}
return isset($this->config[$parameter]) ? $this->config[$parameter] : $default;
}
/**
* Returns absolute link value.
*
* @return string
*/
private function getLink()
{
$linkConfig = $this->config['link'];
if (is_string($linkConfig) || isset($linkConfig['uri'])) {
return (is_string($linkConfig)) ? $linkConfig : $linkConfig['uri'];
}
return $this->router->generate($linkConfig['route_name'], $linkConfig['route_params'], UrlGeneratorInterface::ABSOLUTE_URL);
}
/**
* Add an item (an entity which implements ItemInterface instance).
*
* @param mixed $item An entity item (implements ItemInterface or RoutedItemInterface)
*
* @throws \InvalidArgumentException if item does not implement ItemInterface or RoutedItemInterface
*
* @return \Eko\FeedBundle\Feed\Feed
*/
public function add($item)
{
if (!$item instanceof ItemInterface && !$item instanceof RoutedItemInterface) {
throw new \InvalidArgumentException('Item must implement ItemInterface or RoutedItemInterface');
}
if ($item instanceof RoutedItemInterface) {
$item = new ProxyItem($item, $this->router);
}
$this->items[] = $item;
return $this;
}
/**
* Add items from array.
*
* @param array $items Array of items (implementing ItemInterface or RoutedItemInterface) to add
*
* @return \Eko\FeedBundle\Feed\Feed
*/
public function addFromArray(array $items)
{
foreach ($items as $item) {
$this->add($item);
}
return $this;
}
/**
* Set items from array. Note that this method will override any existing items.
*
* @param array $items Array of items (implementing ItemInterface or RoutedItemInterface) to set
*
* @return \Eko\FeedBundle\Feed\Feed
*/
public function setItems(array $items)
{
$this->items = [];
return $this->addFromArray($items);
}
/**
* Returns feed items.
*
* @return array
*/
public function getItems()
{
return $this->items;
}
/**
* Add a new channel field to render.
*
* @param ChannelFieldInterface $field A custom Field instance
*
* @return \Eko\FeedBundle\Feed\Feed
*/
public function addChannelField(ChannelFieldInterface $field)
{
$this->channelFields[] = $field;
return $this;
}
/**
* Returns custom channel fields.
*
* @return array
*/
public function getChannelFields()
{
return $this->channelFields;
}
/**
* Add a new item field to render.
*
* @param ItemFieldInterface $field A custom Field instance
*
* @return \Eko\FeedBundle\Feed\Feed
*/
public function addItemField(ItemFieldInterface $field)
{
$this->itemFields[] = $field;
return $this;
}
/**
* Returns custom item fields.
*
* @return array
*/
public function getItemFields()
{
return $this->itemFields;
}
/**
* Render the feed in specified format.
*
* @param string $format The format to render (RSS, Atom, ...)
*
* @throws \InvalidArgumentException if given format formatter does not exists
*
* @return string
*/
public function render($format)
{
if (!isset($this->formatters[$format])) {
throw new \InvalidArgumentException(
sprintf("Unable to find a formatter service for format '%s'.", $format)
);
}
$formatter = $this->formatters[$format];
$formatter->setFeed($this);
return $formatter->render();
}
/**
* Return if feed has items.
*
* @return bool
*/
public function hasItems()
{
return (bool) !empty($this->itemFields);
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Hydrator/HydratorInterface.php | Hydrator/HydratorInterface.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Hydrator;
use Laminas\Feed\Reader\Feed\FeedInterface;
/**
* HydratorInterface.
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
interface HydratorInterface
{
/**
* Hydrates given entity from its name with Feed data retrieved from reader.
*
* @param FeedInterface $feed A Feed instance
* @param string $entityName An entity name to populate with feed entries
*
* @throws \RuntimeException if entity does not implements ItemInterface
*
* @return array
*/
public function hydrate(FeedInterface $feed, $entityName);
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Hydrator/DefaultHydrator.php | Hydrator/DefaultHydrator.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Hydrator;
use Eko\FeedBundle\Item\Reader\ItemInterface;
use Laminas\Feed\Reader\Feed\FeedInterface;
/**
* DefaultHydrator.
*
* This is the default feed hydrator
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class DefaultHydrator implements HydratorInterface
{
/**
* {@inheritdoc}
*/
public function hydrate(FeedInterface $feed, $entityName)
{
$items = [];
foreach ($feed as $entry) {
$entity = new $entityName();
if (!$entity instanceof ItemInterface) {
throw new \RuntimeException(
sprintf('Entity "%s" does not implement required %s.', $entityName, ItemInterface::class)
);
}
$entity->setFeedItemTitle($entry->getTitle());
$entity->setFeedItemDescription($entry->getContent());
$entity->setFeedItemLink($entry->getLink());
$entity->setFeedItemPubDate($entry->getDateModified());
$items[] = $entity;
}
return $items;
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/DependencyInjection/EkoFeedExtension.php | DependencyInjection/EkoFeedExtension.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
/**
* EkoFeedExtension.
*
* This class loads services.xml file and tree configuration
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class EkoFeedExtension extends Extension
{
/**
* Configuration extension loader.
*
* @param array $configs An array of configuration settings
* @param ContainerBuilder $container A container builder instance
*/
public function load(array $configs, ContainerBuilder $container)
{
$config = $this->processConfiguration(new Configuration(), $configs);
$loader = new Loader\XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$loader->load('feed.xml');
$loader->load('formatter.xml');
$loader->load('hydrator.xml');
$loader->load('command.xml');
$container->setParameter('eko_feed.config', $config);
$container->setParameter('eko_feed.translation_domain', $config['translation_domain']);
$this->configureHydrator($config, $container);
}
/**
* Configures feed reader hydrator service.
*
* @param array $config Bundle configuration values array
* @param ContainerBuilder $container A ContainerBuilder instance
*
* @throws \RuntimeException
*/
protected function configureHydrator(array $config, ContainerBuilder $container)
{
if (!$container->hasDefinition($config['hydrator'])) {
throw new \RuntimeException(sprintf('Unable to load hydrator service "%s"', $config['hydrator']));
}
$container->getDefinition('Eko\FeedBundle\Feed\Reader')
->addMethodCall('setHydrator', [new Reference($config['hydrator'])]);
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/DependencyInjection/Configuration.php | DependencyInjection/Configuration.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
/**
* Configuration.
*
* This class generates configuration settings tree
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class Configuration implements ConfigurationInterface
{
/**
* Builds configuration tree.
*
* @return TreeBuilder A tree builder instance
*/
public function getConfigTreeBuilder(): TreeBuilder
{
$treeBuilder = new TreeBuilder('eko_feed');
if (\method_exists($treeBuilder, 'getRootNode')) {
$rootNode = $treeBuilder->getRootNode();
} else {
$rootNode = $treeBuilder->root('eko_feed');
}
$rootNode
->children()
->scalarNode('hydrator')->defaultValue('Eko\FeedBundle\Hydrator\DefaultHydrator')->end()
->scalarNode('translation_domain')->defaultNull()->end()
->arrayNode('feeds')
->requiresAtLeastOneElement()
->useAttributeAsKey('name')
->prototype('array')
->children()
->scalarNode('title')->isRequired()->end()
->scalarNode('description')->isRequired()->end()
->arrayNode('link')
->isRequired()
->beforeNormalization()
->ifString()
->then(function ($value) {
return ['uri' => $value];
})
->end()
->children()
->scalarNode('route_name')->end()
->arrayNode('route_params')
->useAttributeAsKey('key')
->prototype('scalar')->end()
->end()
->scalarNode('uri')->end()
->end()
->end()
->scalarNode('encoding')->isRequired()->end()
->scalarNode('author')->end()
->end()
->end()
->end()
->end();
return $treeBuilder;
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/DependencyInjection/Compiler/FeedFormatterPass.php | DependencyInjection/Compiler/FeedFormatterPass.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\DependencyInjection\Compiler;
use Eko\FeedBundle\Feed\FeedManager;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* Retrieve all formatters and inject them into the feed manager service.
*
* @author Vincent Composieux <vincent.composieux@gail.com>
*/
class FeedFormatterPass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
$formatters = [];
$services = $container->findTaggedServiceIds('eko_feed.formatter');
foreach ($services as $identifier => $options) {
$options = current($options);
$formatters[$options['format']] = new Reference($identifier);
}
$manager = $container->getDefinition(FeedManager::class);
$manager->replaceArgument(2, $formatters);
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/DependencyInjection/Compiler/FeedDumpServicePass.php | DependencyInjection/Compiler/FeedDumpServicePass.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\DependencyInjection\Compiler;
use Eko\FeedBundle\Service\FeedDumpService;
use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
/**
* Check if the Eko\FeedBundle\Service\FeedDumpService is missing dependencies
* and if so remove the service.
*
* @author Lukas Kahwe Smith <smith@pooteeweet.org>
*/
class FeedDumpServicePass implements CompilerPassInterface
{
/**
* {@inheritdoc}
*/
public function process(ContainerBuilder $container)
{
if (!$container->hasAlias('doctrine.orm.entity_manager')) {
$container->removeDefinition(FeedDumpService::class);
}
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Tests/bootstrap.php | Tests/bootstrap.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
if (file_exists($file = __DIR__.'/autoload.php')) {
require_once $file;
} elseif (file_exists($file = __DIR__.'/autoload.php.dist')) {
require_once $file;
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Tests/Formatter/RSSFormatterTest.php | Tests/Formatter/RSSFormatterTest.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Tests\Formatter;
use Eko\FeedBundle\Feed\FeedManager;
use Eko\FeedBundle\Field\Channel\ChannelField;
use Eko\FeedBundle\Field\Channel\GroupChannelField;
use Eko\FeedBundle\Field\Item\GroupItemField;
use Eko\FeedBundle\Field\Item\ItemField;
use Eko\FeedBundle\Field\Item\MediaItemField;
use Eko\FeedBundle\Formatter\AtomFormatter;
use Eko\FeedBundle\Formatter\RssFormatter;
use Eko\FeedBundle\Tests\Entity\Writer\FakeItemInterfaceEntity;
use Eko\FeedBundle\Tests\Entity\Writer\FakeRoutedItemInterfaceEntity;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* RSSFormatterTest.
*
* This is the RSS formatter test class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class RSSFormatterTest extends \PHPUnit\Framework\TestCase
{
/**
* @var FeedManager A feed manager instance
*/
protected $manager;
/**
* Sets up elements used in test case.
*/
protected function setUp(): void
{
$config = [
'feeds' => [
'article' => [
'title' => 'My articles/posts',
'description' => 'Latests articles',
'link' => 'http://github.com/eko/FeedBundle',
'encoding' => 'utf-8',
'author' => 'Vincent Composieux',
],
],
];
$router = $this->createMock(RouterInterface::class);
$router->expects($this->any())
->method('generate')
->with('fake_route', [], UrlGeneratorInterface::ABSOLUTE_URL)
->will($this->returnValue('http://github.com/eko/FeedBundle/article/fake/url?utm_source=mysource&utm_medium=mymedium&utm_campaign=mycampaign&utm_content=mycontent'));
$translator = $this->createMock(TranslatorInterface::class);
$formatters = [
'rss' => new RssFormatter($translator, 'test'),
'atom' => new AtomFormatter($translator, 'test'),
];
$this->manager = new FeedManager($router, $config, $formatters);
}
/**
* Check if RSS formatter output item.
*/
public function testRenderCorrectRootNodes()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$output = $feed->render('rss');
$this->assertStringContainsString('<rss version="2.0">', $output);
$this->assertStringContainsString('<channel>', $output);
}
/**
* Check if RSS formatter output a valid XML.
*/
public function testRenderValidXML()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$output = $feed->render('rss');
$dom = new \DOMDocument('1.0', 'utf-8');
$dom->loadXML($output);
$this->assertEquals(0, count(libxml_get_errors()));
$this->assertStringContainsString('<rss version="2.0">', $output);
}
/**
* Check if RSS formatter output item.
*/
public function testRenderItem()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$output = $feed->render('rss');
$this->assertStringContainsString('<title><![CDATA[Fake title]]></title>', $output);
$this->assertStringContainsString('<description><![CDATA[Fake description or content]]></description>', $output);
$this->assertStringContainsString('<link>http://github.com/eko/FeedBundle/article/fake/url</link>', $output);
}
/**
* Check if a custom channel field is properly rendered.
*/
public function testAddCustomChannelField()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addChannelField(new ChannelField('fake_custom_channel', 'My fake value'));
$output = $feed->render('rss');
$this->assertStringContainsString('<fake_custom_channel>My fake value</fake_custom_channel>', $output);
}
/**
* Check if a custom item field is properly rendered with ItemInterface.
*/
public function testAddCustomItemFieldWithItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(new ItemField('fake_custom', 'getFeedItemCustom'));
$output = $feed->render('rss');
$this->assertStringContainsString('<fake_custom>My custom field</fake_custom>', $output);
}
/**
* Check if a custom item field with one attribute only is properly rendered with ItemInterface.
*/
public function testAddCustomItemFieldWithOneAttributeOnly()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(new ItemField('fake_custom', 'getFeedItemCustom', [
'attribute' => true,
'attribute_name' => 'fake-value',
]));
$output = $feed->render('rss');
$this->assertStringContainsString('<fake_custom fake-value="My custom field"/>', $output);
}
/**
* Check if a custom media item field is properly rendered with ItemInterface.
*/
public function testAddCustomMediaItemFieldWithItemInterface()
{
$fakeEntityWithMedias = new FakeItemInterfaceEntity();
$fakeEntityWithMedias->setFeedMediaItem([
'type' => 'image/jpeg',
'length' => 500,
'value' => 'http://website.com/image.jpg',
]);
$fakeEntityNoMedias = new FakeItemInterfaceEntity();
$feed = $this->manager->get('article');
$feed->add($fakeEntityWithMedias);
$feed->add($fakeEntityNoMedias);
$feed->addItemField(new MediaItemField('getFeedMediaItem'));
$output = $feed->render('rss');
$this->assertStringContainsString('<enclosure url="http://website.com/image.jpg" type="image/jpeg" length="500"/>', $output);
}
/**
* Check if a custom group media items field is properly rendered with ItemInterface.
*/
public function testAddCustomGroupMediaItemsFieldsWithItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(new GroupItemField(
'images',
new MediaItemField('getFeedMediaMultipleItems'))
);
$output = $feed->render('rss');
$this->assertStringContainsString('<images>', $output);
$this->assertStringContainsString('<enclosure url="http://website.com/image.jpg" type="image/jpeg" length="500"/>', $output);
$this->assertStringContainsString('<enclosure url="http://website.com/image2.png" type="image/png" length="600"/>', $output);
$this->assertStringContainsString('</images>', $output);
}
/**
* Check if a custom group item field is properly rendered with ItemInterface.
*/
public function testAddCustomGroupItemFieldWithItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(
new GroupItemField('categories', new ItemField('category', 'getFeedCategoriesCustom'))
);
$output = $feed->render('rss');
$this->assertStringContainsString('<categories>', $output);
$this->assertStringContainsString('<category>category 1</category>', $output);
$this->assertStringContainsString('<category>category 2</category>', $output);
$this->assertStringContainsString('<category>category 3</category>', $output);
$this->assertStringContainsString('</categories>', $output);
}
/**
* Check if a custom group item field with attributes is properly rendered.
*/
public function testAddCustomGroupItemFieldWithAttributes()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(
new GroupItemField(
'categories',
new ItemField('category', 'getFeedCategoriesCustom', [], ['category-type' => 'test']),
['is-it-test' => 'yes']
)
);
$output = $feed->render('rss');
$this->assertStringContainsString('<categories is-it-test="yes">', $output);
$this->assertStringContainsString('<category category-type="test">category 1</category>', $output);
$this->assertStringContainsString('<category category-type="test">category 2</category>', $output);
$this->assertStringContainsString('<category category-type="test">category 3</category>', $output);
$this->assertStringContainsString('</categories>', $output);
}
/**
* Check if a custom group item field with attributes from method is properly rendered.
*/
public function testAddCustomGroupItemFieldWithAttributesFromMethod()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(
new GroupItemField(
'categories',
new ItemField('category', 'getFeedCategoriesCustom', [], ['getItemKeyAttribute' => 'getItemValueAttribute']),
['getGroupKeyAttribute' => 'getGroupValueAttribute']
)
);
$output = $feed->render('rss');
$this->assertStringContainsString('<categories my-group-key-attribute="my-group-value-attribute">', $output);
$this->assertStringContainsString('<category my-item-key-attribute="my-item-value-attribute">category 1</category>', $output);
$this->assertStringContainsString('<category my-item-key-attribute="my-item-value-attribute">category 2</category>', $output);
$this->assertStringContainsString('<category my-item-key-attribute="my-item-value-attribute">category 3</category>', $output);
$this->assertStringContainsString('</categories>', $output);
}
/**
* Check if a custom group channel field is properly rendered with GroupFieldInterface.
*/
public function testAddCustomGroupChannelFieldWithItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addChannelField(
new GroupChannelField('image', [
new ChannelField('name', 'My test image'),
new ChannelField('url', 'http://www.example.com/image.jpg'),
])
);
$output = $feed->render('rss');
$this->assertStringContainsString('<image>', $output);
$this->assertStringContainsString('<name>My test image</name>', $output);
$this->assertStringContainsString('<url>http://www.example.com/image.jpg</url>', $output);
$this->assertStringContainsString('</image>', $output);
}
/**
* Check if a custom group channel field is properly rendered with attributes.
*/
public function testAddCustomGroupChannelFieldWithAttributes()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addChannelField(
new GroupChannelField('image', [
new ChannelField('name', 'My test image', [], ['name-attribute' => 'test']),
new ChannelField('url', 'http://www.example.com/image.jpg', [], ['url-attribute' => 'test']),
], ['image-attribute' => 'test'])
);
$output = $feed->render('rss');
$this->assertStringContainsString('<image image-attribute="test">', $output);
$this->assertStringContainsString('<name name-attribute="test">My test image</name>', $output);
$this->assertStringContainsString('<url url-attribute="test">http://www.example.com/image.jpg</url>', $output);
$this->assertStringContainsString('</image>', $output);
}
/**
* Check if a custom group item field with multiple item fields is properly rendered with ItemInterface.
*/
public function testAddCustomGroupMultipleItemFieldWithItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(new GroupItemField('author', [
new ItemField('name', 'getFeedItemAuthorName', ['cdata' => true]),
new ItemField('email', 'getFeedItemAuthorEmail'),
]));
$output = $feed->render('rss');
$this->assertStringContainsString(<<<'EOF'
<author>
<name><![CDATA[John Doe]]></name>
<email>john.doe@example.org</email>
</author>
EOF
, $output);
}
/**
* Check if a custom item field is properly rendered with RoutedItemInterface.
*/
public function testAddCustomItemFieldWithRoutedItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeRoutedItemInterfaceEntity());
$feed->addItemField(new ItemField('fake_custom', 'getFeedItemCustom'));
$output = $feed->render('rss');
$this->assertStringContainsString('<fake_custom>My custom field</fake_custom>', $output);
}
/**
* Check if anchors are really appended to generated url of RouterItemInterface.
*/
public function testAnchorIsAppendedToLinkWithRoutedItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeRoutedItemInterfaceEntity());
$output = $feed->render('atom');
$this->assertStringContainsString('<link href="http://github.com/eko/FeedBundle/article/fake/url?utm_source=mysource&utm_medium=mymedium&utm_campaign=mycampaign&utm_content=mycontent#fake-anchor"/>', $output);
}
/**
* Check if an exception is thrown when trying to render a non-existant method with RoutedItemInterface.
*/
public function testNonExistantCustomItemFieldWithRoutedItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeRoutedItemInterfaceEntity());
$feed->addItemField(new ItemField('fake_custom', 'getFeedDoNotExistsItemCustomMethod'));
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Method "getFeedDoNotExistsItemCustomMethod" should be defined in your entity.');
$feed->render('rss');
}
/**
* Check if values are well translated with "translatable" option.
*/
public function testTranslatableValue()
{
$config = [
'feeds' => [
'article' => [
'title' => 'My title',
'description' => 'My description',
'link' => 'http://github.com/eko/FeedBundle',
'encoding' => 'utf-8',
],
],
];
$translator = $this->createMock(TranslatorInterface::class);
$translator->expects($this->any())->method('trans')->will($this->returnValue('translatable-value'));
$formatters = ['rss' => new RssFormatter($translator, 'test')];
$router = $this->createMock(RouterInterface::class);
$manager = new FeedManager($router, $config, $formatters);
$feed = $manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(new ItemField('fake_custom', 'getFeedItemCustom', [
'translatable' => true,
]));
$output = $feed->render('rss');
$this->assertStringContainsString('<fake_custom>translatable-value</fake_custom>', $output);
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Tests/Formatter/AtomFormatterTest.php | Tests/Formatter/AtomFormatterTest.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Tests\Formatter;
use Eko\FeedBundle\Feed\FeedManager;
use Eko\FeedBundle\Field\Channel\ChannelField;
use Eko\FeedBundle\Field\Channel\GroupChannelField;
use Eko\FeedBundle\Field\Item\GroupItemField;
use Eko\FeedBundle\Field\Item\ItemField;
use Eko\FeedBundle\Field\Item\MediaItemField;
use Eko\FeedBundle\Formatter\AtomFormatter;
use Eko\FeedBundle\Formatter\RssFormatter;
use Eko\FeedBundle\Tests\Entity\Writer\FakeItemInterfaceEntity;
use Eko\FeedBundle\Tests\Entity\Writer\FakeRoutedItemInterfaceEntity;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* AtomFormatterTest.
*
* This is the Atom formatter test class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class AtomFormatterTest extends \PHPUnit\Framework\TestCase
{
/**
* @var FeedManager A feed manager instance
*/
protected $manager;
/**
* Sets up elements used in test case.
*/
protected function setUp(): void
{
$config = [
'feeds' => [
'article' => [
'title' => 'My articles/posts',
'description' => 'Latests articles',
'link' => 'http://github.com/eko/FeedBundle',
'encoding' => 'utf-8',
'author' => 'Vincent Composieux',
],
],
];
$translator = $this->createMock(TranslatorInterface::class);
$formatters = [
'rss' => new RssFormatter($translator, 'test'),
'atom' => new AtomFormatter($translator, 'test'),
];
$this->manager = new FeedManager($this->getMockRouter(), $config, $formatters);
}
/**
* Check if exception is an \InvalidArgumentException is thrown
* when 'author' config parameter is not set or empty.
*/
public function testAuthorEmptyException()
{
$config = [
'feeds' => [
'article' => [
'title' => 'My title',
'description' => 'My description',
'link' => 'http://github.com/eko/FeedBundle',
'encoding' => 'utf-8',
'author' => '',
],
],
];
$translator = $this->createMock(TranslatorInterface::class);
$formatters = [
'rss' => new RssFormatter($translator, 'test'),
'atom' => new AtomFormatter($translator, 'test'),
];
$manager = new FeedManager($this->getMockRouter(), $config, $formatters);
$feed = $manager->get('article');
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Atom formatter requires an "author" parameter in configuration.');
$feed->set('author', null);
$feed->render('atom');
}
/**
* Check if Atom formatter output item.
*/
public function testRenderCorrectRootNodes()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$output = $feed->render('atom');
$this->assertStringContainsString('<feed xmlns="http://www.w3.org/2005/Atom">', $output);
$this->assertStringContainsString('<link href="http://github.com/eko/FeedBundle" rel="self" type="application/rss+xml"/>', $output);
}
/**
* Check if Atom formatter output a valid XML.
*/
public function testRenderValidXML()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$output = $feed->render('atom');
$dom = new \DOMDocument('1.0', 'utf-8');
$dom->loadXML($output);
$this->assertEquals(0, count(libxml_get_errors()));
$this->assertStringContainsString('<feed xmlns="http://www.w3.org/2005/Atom">', $output);
}
/**
* Check if Atom formatter output item.
*/
public function testRenderItem()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$output = $feed->render('atom');
$this->assertStringContainsString('<title><![CDATA[Fake title]]></title>', $output);
$this->assertStringContainsString('<summary type="html"><![CDATA[Fake description or content]]></summary>', $output);
$this->assertStringContainsString('<link href="http://github.com/eko/FeedBundle/article/fake/url"/>', $output);
}
/**
* Check if a custom channel field is properly rendered.
*/
public function testAddCustomChannelField()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addChannelField(new ChannelField('fake_channel_custom', 'My fake value'));
$output = $feed->render('atom');
$this->assertStringContainsString('<fake_channel_custom>My fake value</fake_channel_custom>', $output);
}
/**
* Check if a custom item field is properly rendered with ItemInterface.
*/
public function testAddCustomItemFieldWithItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(new ItemField('fake_custom', 'getFeedItemCustom'));
$output = $feed->render('atom');
$this->assertStringContainsString('<fake_custom>My custom field</fake_custom>', $output);
}
/**
* Check if a custom item field with one attribute only is properly rendered with ItemInterface.
*/
public function testAddCustomItemFieldWithOneAttributeOnly()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(new ItemField('fake_custom', 'getFeedItemCustom', [
'attribute' => true,
'attribute_name' => 'fake-value',
]));
$output = $feed->render('atom');
$this->assertStringContainsString('<fake_custom fake-value="My custom field"/>', $output);
}
/**
* Check if a custom media item field is properly rendered with ItemInterface.
*/
public function testAddCustomMediaItemFieldWithItemInterface()
{
$fakeEntityWithMedias = new FakeItemInterfaceEntity();
$fakeEntityWithMedias->setFeedMediaItem([
'type' => 'image/jpeg',
'length' => 500,
'value' => 'http://website.com/image.jpg',
]);
$fakeEntityNoMedias = new FakeItemInterfaceEntity();
$feed = $this->manager->get('article');
$feed->add($fakeEntityWithMedias);
$feed->add($fakeEntityNoMedias);
$feed->addItemField(new MediaItemField('getFeedMediaItem'));
$output = $feed->render('atom');
$this->assertStringContainsString('<link rel="enclosure" href="http://website.com/image.jpg" type="image/jpeg" length="500"/>', $output);
}
/**
* Check if a custom group media items field is properly rendered with ItemInterface.
*/
public function testAddCustomGroupMediaItemsFieldsWithItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(new GroupItemField(
'images',
new MediaItemField('getFeedMediaMultipleItems'))
);
$output = $feed->render('atom');
$this->assertStringContainsString('<images>', $output);
$this->assertStringContainsString('<link rel="enclosure" href="http://website.com/image.jpg" type="image/jpeg" length="500"/>', $output);
$this->assertStringContainsString('<link rel="enclosure" href="http://website.com/image2.png" type="image/png" length="600"/>', $output);
$this->assertStringContainsString('</images>', $output);
}
/**
* Check if a custom group item field is properly rendered with ItemInterface.
*/
public function testAddCustomGroupItemFieldWithItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(new GroupItemField(
'categories',
new ItemField('category', 'getFeedCategoriesCustom'))
);
$output = $feed->render('atom');
$this->assertStringContainsString('<categories>', $output);
$this->assertStringContainsString('<category>category 1</category>', $output);
$this->assertStringContainsString('<category>category 2</category>', $output);
$this->assertStringContainsString('<category>category 3</category>', $output);
$this->assertStringContainsString('</categories>', $output);
}
/**
* Check if a custom group item field with attributes is properly rendered.
*/
public function testAddCustomGroupItemFieldWithAttributes()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(
new GroupItemField(
'categories',
new ItemField('category', 'getFeedCategoriesCustom', [], ['category-type' => 'test']),
['is-it-test' => 'yes']
)
);
$output = $feed->render('atom');
$this->assertStringContainsString('<categories is-it-test="yes">', $output);
$this->assertStringContainsString('<category category-type="test">category 1</category>', $output);
$this->assertStringContainsString('<category category-type="test">category 2</category>', $output);
$this->assertStringContainsString('<category category-type="test">category 3</category>', $output);
$this->assertStringContainsString('</categories>', $output);
}
/**
* Check if a custom group item field can contain another group items field.
*/
public function testAddCustomGroupItemFieldContainingAnotherGroup()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(
new GroupItemField(
'links',
array(
new GroupItemField('link', new ItemField('category', 'getFeedCategoriesCustom')),
new GroupItemField('link', new ItemField('category', 'getFeedCategoriesCustom'))
)
)
);
$output = $feed->render('atom');
$output = str_replace(array("\r", "\n", " "), '', $output);
$this->assertStringContainsString('<links><link><category>category 1</category><category>category 2</category><category>category 3</category></link><link><category>category 1</category><category>category 2</category><category>category 3</category></link></links>', $output);
}
/**
* Check if a custom group item field with attributes from method is properly rendered.
*/
public function testAddCustomGroupItemFieldWithAttributesFromMethod()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(
new GroupItemField(
'categories',
new ItemField('category', 'getFeedCategoriesCustom', [], ['getItemKeyAttribute' => 'getItemValueAttribute']),
['getGroupKeyAttribute' => 'getGroupValueAttribute']
)
);
$output = $feed->render('atom');
$this->assertStringContainsString('<categories my-group-key-attribute="my-group-value-attribute">', $output);
$this->assertStringContainsString('<category my-item-key-attribute="my-item-value-attribute">category 1</category>', $output);
$this->assertStringContainsString('<category my-item-key-attribute="my-item-value-attribute">category 2</category>', $output);
$this->assertStringContainsString('<category my-item-key-attribute="my-item-value-attribute">category 3</category>', $output);
$this->assertStringContainsString('</categories>', $output);
}
/**
* Check if a custom group channel field is properly rendered with GroupFieldInterface.
*/
public function testAddCustomGroupChannelFieldWithItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addChannelField(
new GroupChannelField('image', [
new ChannelField('name', 'My test image'),
new ChannelField('url', 'http://www.example.com/image.jpg'),
])
);
$output = $feed->render('atom');
$this->assertStringContainsString('<image>', $output);
$this->assertStringContainsString('<name>My test image</name>', $output);
$this->assertStringContainsString('<url>http://www.example.com/image.jpg</url>', $output);
$this->assertStringContainsString('</image>', $output);
}
/**
* Check if a custom group channel field is properly rendered with attributes.
*/
public function testAddCustomGroupChannelFieldWithAttributes()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addChannelField(
new GroupChannelField('image', [
new ChannelField('name', 'My test image', [], ['name-attribute' => 'test']),
new ChannelField('url', 'http://www.example.com/image.jpg', [], ['url-attribute' => 'test']),
], ['image-attribute' => 'test'])
);
$output = $feed->render('atom');
$this->assertStringContainsString('<image image-attribute="test">', $output);
$this->assertStringContainsString('<name name-attribute="test">My test image</name>', $output);
$this->assertStringContainsString('<url url-attribute="test">http://www.example.com/image.jpg</url>', $output);
$this->assertStringContainsString('</image>', $output);
}
/**
* Check if a custom group item field with multiple item fields is properly rendered with ItemInterface.
*/
public function testAddCustomGroupMultipleItemFieldWithItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$feed->addItemField(new GroupItemField('author', [
new ItemField('name', 'getFeedItemAuthorName', ['cdata' => true]),
new ItemField('email', 'getFeedItemAuthorEmail'),
]));
$output = $feed->render('atom');
$this->assertStringContainsString(<<<'EOF'
<author>
<name><![CDATA[John Doe]]></name>
<email>john.doe@example.org</email>
</author>
EOF
, $output);
}
/**
* Check if a custom item field is properly rendered with RoutedItemInterface.
*/
public function testAddCustomItemFieldWithRoutedItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeRoutedItemInterfaceEntity());
$feed->addItemField(new ItemField('fake_custom', 'getFeedItemCustom'));
$output = $feed->render('atom');
$this->assertStringContainsString('<fake_custom>My custom field</fake_custom>', $output);
}
/**
* Check if anchors are really appended to generated url of RouterItemInterface.
*/
public function testAnchorIsAppendedToLinkWithRoutedItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeRoutedItemInterfaceEntity());
$output = $feed->render('atom');
$this->assertStringContainsString('<link href="http://github.com/eko/FeedBundle/article/fake/url#fake-anchor"/>', $output);
}
/**
* Check if an exception is thrown when trying to render a non-existant method with RoutedItemInterface.
*/
public function testNonExistantCustomItemFieldWithRoutedItemInterface()
{
$feed = $this->manager->get('article');
$feed->add(new FakeRoutedItemInterfaceEntity());
$feed->addItemField(new ItemField('fake_custom', 'getFeedDoNotExistsItemCustomMethod'));
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage('Method "getFeedDoNotExistsItemCustomMethod" should be defined in your entity.');
$feed->render('atom');
}
/**
* Check if values are well translated with "translatable" option.
*/
public function testTranslatableValue()
{
$config = [
'feeds' => [
'article' => [
'title' => 'My title',
'description' => 'My description',
'link' => 'http://github.com/eko/FeedBundle',
'encoding' => 'utf-8',
'author' => 'Vincent',
],
],
];
$translator = $this->createMock(TranslatorInterface::class);
$translator->expects($this->any())->method('trans')->will($this->returnValue('translatable-value'));
$formatters = ['atom' => new AtomFormatter($translator, 'test')];
$manager = new FeedManager($this->getMockRouter(), $config, $formatters);
$feed = $manager->get('article');
$feed->add(new FakeRoutedItemInterfaceEntity());
$feed->addItemField(new ItemField('fake_custom', 'getFeedItemCustom', [
'translatable' => true,
]));
$output = $feed->render('atom');
$this->assertStringContainsString('<fake_custom>translatable-value</fake_custom>', $output);
}
/**
* Returns RouterInterface mock.
*
* @return \PHPUnit_Framework_MockObject_MockObject
*/
private function getMockRouter()
{
$mockRouter = $this->createMock(RouterInterface::class);
$mockRouter->expects($this->any())
->method('generate')
->with('fake_route', [], UrlGeneratorInterface::ABSOLUTE_URL)
->will($this->returnValue('http://github.com/eko/FeedBundle/article/fake/url'));
return $mockRouter;
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Tests/Entity/Reader/FakeItemInterfaceEntity.php | Tests/Entity/Reader/FakeItemInterfaceEntity.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Tests\Entity\Reader;
use Eko\FeedBundle\Item\Reader\ItemInterface;
/**
* Fake.
*
* A fake entity implementing ItemInterface for tests
*/
class FakeItemInterfaceEntity implements ItemInterface
{
/**
* @var string
*/
protected $title;
/**
* @var string
*/
protected $description;
/**
* @var string
*/
protected $link;
/**
* @var \DateTime
*/
protected $date;
/**
* Returns a fake title.
*
* @return string
*/
public function setFeedItemTitle($title)
{
$this->title = $title;
}
/**
* Returns a fake description or content.
*
* @return string
*/
public function setFeedItemDescription($description)
{
$this->description = $description;
}
/**
* Returns a fake item link.
*
* @return string
*/
public function setFeedItemLink($link)
{
$this->link = $link;
}
/**
* Returns a fake publication date.
*
* @return \DateTime
*/
public function setFeedItemPubDate(\DateTime $date)
{
$this->date = $date;
}
/**
* Get title.
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Get description.
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Get link.
*
* @return string
*/
public function getLink()
{
return $this->link;
}
/**
* Get publication date.
*
* @return \DateTime
*/
public function getPublicationDate()
{
return $this->date;
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Tests/Entity/Writer/FakeRoutedItemInterfaceEntity.php | Tests/Entity/Writer/FakeRoutedItemInterfaceEntity.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Tests\Entity\Writer;
use Eko\FeedBundle\Item\Writer\RoutedItemInterface;
/**
* Fake.
*
* A fake entity implementing RoutedItemInterface for tests
*/
class FakeRoutedItemInterfaceEntity implements RoutedItemInterface
{
/**
* Returns a fake title.
*
* @return string
*/
public function getFeedItemTitle()
{
return 'Fake title';
}
/**
* Returns a fake description or content.
*
* @return string
*/
public function getFeedItemDescription()
{
return 'Fake description or content';
}
/**
* Returns a fake item link.
*
* @return string
*/
public function getFeedItemRouteName()
{
return 'fake_route';
}
/**
* Returns a fake route parameters array.
*
* @return array
*/
public function getFeedItemRouteParameters()
{
return [];
}
/**
* Returns a fake anchor.
*
* @return string
*/
public function getFeedItemUrlAnchor()
{
return 'fake-anchor';
}
/**
* Returns a fake publication date.
*
* @return \DateTime
*/
public function getFeedItemPubDate()
{
return new \DateTime();
}
/**
* Returns a fake custom field.
*
* @return string
*/
public function getFeedItemCustom()
{
return 'My custom field';
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Tests/Entity/Writer/FakeItemInterfaceEntity.php | Tests/Entity/Writer/FakeItemInterfaceEntity.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Tests\Entity\Writer;
use Eko\FeedBundle\Item\Writer\ItemInterface;
/**
* Fake.
*
* A fake entity implementing ItemInterface for tests
*/
class FakeItemInterfaceEntity implements ItemInterface
{
protected $medias;
/**
* Returns a fake title.
*
* @return string
*/
public function getFeedItemTitle()
{
return 'Fake title';
}
/**
* Returns a fake description or content.
*
* @return string
*/
public function getFeedItemDescription()
{
return 'Fake description or content';
}
/**
* Returns a fake item link.
*
* @return string
*/
public function getFeedItemLink()
{
return 'http://github.com/eko/FeedBundle/article/fake/url';
}
/**
* Returns a fake publication date.
*
* @return \DateTime
*/
public function getFeedItemPubDate()
{
return new \DateTime();
}
/**
* Returns a fake custom field.
*
* @return string
*/
public function getFeedItemCustom()
{
return 'My custom field';
}
/**
* Returns a fake field author name.
*
* @return string
*/
public function getFeedItemAuthorName()
{
return 'John Doe';
}
/**
* Returns a fake field author email.
*
* @return string
*/
public function getFeedItemAuthorEmail()
{
return 'john.doe@example.org';
}
/**
* Sets feed media items.
*
* @param array $medias
*/
public function setFeedMediaItem(array $medias)
{
$this->medias = $medias;
}
/**
* Returns a fake custom media field.
*
* @return string
*/
public function getFeedMediaItem()
{
return $this->medias;
}
/**
* Returns a fake custom multiple media fields.
*
* @return string
*/
public function getFeedMediaMultipleItems()
{
return [
[
'type' => 'image/jpeg',
'length' => 500,
'value' => 'http://website.com/image.jpg',
],
[
'type' => 'image/png',
'length' => 600,
'value' => 'http://website.com/image2.png',
],
];
}
/**
* Returns a fake custom categories array.
*
* @return array
*/
public function getFeedCategoriesCustom()
{
return [
'category 1',
'category 2',
'category 3',
];
}
/**
* @return string
*/
public function getGroupKeyAttribute()
{
return 'my-group-key-attribute';
}
/**
* @return string
*/
public function getGroupValueAttribute()
{
return 'my-group-value-attribute';
}
/**
* @return string
*/
public function getItemKeyAttribute()
{
return 'my-item-key-attribute';
}
/**
* @return string
*/
public function getItemValueAttribute()
{
return 'my-item-value-attribute';
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Tests/Feed/FeedTest.php | Tests/Feed/FeedTest.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Tests\Feed;
use Eko\FeedBundle\Feed\FeedManager;
use Eko\FeedBundle\Formatter\AtomFormatter;
use Eko\FeedBundle\Formatter\RssFormatter;
use Eko\FeedBundle\Tests\Entity\Writer\FakeItemInterfaceEntity;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* FeedTest.
*
* This is the feed test class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class FeedTest extends \PHPUnit\Framework\TestCase
{
/**
* @var FeedManager A feed manager instance
*/
protected $manager;
/**
* Set up.
*/
protected function setUp(): void
{
$config = [
'feeds' => [
'article' => [
'title' => 'My articles/posts',
'description' => 'Latests articles',
'link' => 'http://github.com/eko/FeedBundle',
'encoding' => 'utf-8',
'author' => 'Vincent Composieux',
],
],
];
$router = $this->createMock(RouterInterface::class);
$translator = $this->createMock(TranslatorInterface::class);
$formatters = [
'rss' => new RssFormatter($translator, 'test'),
'atom' => new AtomFormatter($translator, 'test'),
];
$this->manager = new FeedManager($router, $config, $formatters);
}
/**
* Check if there is no item inserted during feed creation.
*/
public function testNoItem()
{
$feed = $this->manager->get('article');
$this->assertEquals(0, count($feed->getItems()));
}
/**
* Check if items are correctly added.
*/
public function testAdditem()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$this->assertEquals(1, count($feed->getItems()));
}
/**
* Check if items are correctly added.
*/
public function testAdditemsFromEmpty()
{
$feed = $this->manager->get('article');
$items = [new FakeItemInterfaceEntity(), new FakeItemInterfaceEntity()];
$feed->addFromArray($items);
$this->assertEquals(2, count($feed->getItems()));
}
/**
* Check if items are correctly added.
*/
public function testAdditemsWithExistingItem()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$items = [new FakeItemInterfaceEntity(), new FakeItemInterfaceEntity()];
$feed->addFromArray($items);
$this->assertEquals(3, count($feed->getItems()));
}
/**
* Check if multiple items are correctly loaded.
*/
public function testSetItemsFromEmpty()
{
$feed = $this->manager->get('article');
$items = [new FakeItemInterfaceEntity(), new FakeItemInterfaceEntity()];
$feed->setItems($items);
$this->assertEquals(2, count($feed->getItems()));
}
/**
* Check if multiple items are correctly loaded.
*/
public function testSetItemsWithExistingItem()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$items = [new FakeItemInterfaceEntity(), new FakeItemInterfaceEntity()];
$feed->setItems($items);
$this->assertEquals(2, count($feed->getItems()));
}
/**
* Check if an \InvalidArgumentException is thrown
* when formatter asked for rendering does not exists.
*/
public function testFormatterNotFoundException()
{
$feed = $this->manager->get('article');
$feed->add(new FakeItemInterfaceEntity());
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage("Unable to find a formatter service for format 'unknown_formatter'.");
$feed->render('unknown_formatter');
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Tests/Feed/ReaderTest.php | Tests/Feed/ReaderTest.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Tests\Feed;
use Eko\FeedBundle\Feed\Reader;
use Eko\FeedBundle\Hydrator\DefaultHydrator;
use Eko\FeedBundle\Tests\Entity\Reader\FakeItemInterfaceEntity;
use Laminas\Feed\Reader\Collection\Author;
use Laminas\Feed\Reader\Feed\FeedInterface;
/**
* ReaderTest.
*
* This is the feed reader test class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class ReaderTest extends \PHPUnit\Framework\TestCase
{
/**
* @var Reader A feed reader instance
*/
protected $reader;
/**
* Sets up elements used in test case.
*/
protected function setUp(): void
{
$this->reader = new Reader();
$this->reader->setHydrator(new DefaultHydrator());
}
/**
* Check if feeds can be loaded from data fixtures.
*/
public function testLoad()
{
$feed = $this->reader->load(__DIR__.'/../DataFixtures/Feed.xml')->get();
$this->assertNotNull($feed, 'Returned feed should not be null');
$this->assertInstanceOf(FeedInterface::class, $feed, 'Should return an AbstractFeed instance');
foreach ($feed as $entry) {
$this->assertEquals('PHP 5.4.11 and PHP 5.3.21 released!', $entry->getTitle(), 'Should be equal');
$this->assertEquals('http://php.net/index.php#id2013-01-17-1', $entry->getLink(), 'Should be equal');
$this->assertInstanceOf(Author::class, $entry->getAuthors(), 'Should be an instance of Author');
}
}
/**
* Check if feeds can populate an entity.
*/
public function testPopulate()
{
$reader = $this->reader->load(__DIR__.'/../DataFixtures/Feed.xml');
$items = $reader->populate(FakeItemInterfaceEntity::class);
$this->assertCount(1, $items, 'Should contain an array with the only feed element');
foreach ($items as $item) {
$this->assertInstanceOf(FakeItemInterfaceEntity::class, $item, 'Should be an instance of populated entity name');
$this->assertEquals('PHP 5.4.11 and PHP 5.3.21 released!', $item->getTitle(), 'Should be correct title');
$this->assertEquals('<div>', substr($item->getDescription(), 0, 5), 'Should be correct description');
$this->assertEquals('http://php.net/index.php#id2013-01-17-1', $item->getLink(), 'Should be correct link');
$this->assertEquals('2013-01-17 14:54:00', $item->getPublicationDate()->format('Y-m-d H:i:s'), 'Should be the same datetime object');
}
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Tests/Feed/FeedManagerTest.php | Tests/Feed/FeedManagerTest.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Tests\Feed;
use Eko\FeedBundle\Feed\FeedManager;
use Eko\FeedBundle\Formatter\AtomFormatter;
use Eko\FeedBundle\Formatter\RssFormatter;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* FeedManagerTest.
*
* This is the feed manager test class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class FeedManagerTest extends \PHPUnit\Framework\TestCase
{
/**
* @var FeedManager A feed manager instance
*/
protected $manager;
/**
* Sets up manager & configuration used in test cases.
*/
protected function setUp(): void
{
$config = [
'feeds' => [
'article' => [
'title' => 'My articles/posts',
'description' => 'Latests articles',
'link' => 'http://github.com/eko/FeedBundle',
'encoding' => 'utf-8',
'author' => 'Vincent Composieux',
],
],
];
$router = $this->createMock(RouterInterface::class);
$translator = $this->createMock(TranslatorInterface::class);
$formatters = [
'rss' => new RssFormatter($translator, 'test'),
'atom' => new AtomFormatter($translator, 'test'),
];
$this->manager = new FeedManager($router, $config, $formatters);
}
/**
* Check if feed is correctly inserted.
*/
public function testHasFeed()
{
$this->assertTrue($this->manager->has('article'));
}
/**
* Check if a fake feed name is not marked as existing.
*/
public function testFeedDoNotExists()
{
$this->assertFalse($this->manager->has('fake_feed_name'));
}
/**
* Check if an \InvalidArgumentException is thrown
* if requested feed does not exists.
*/
public function testNonExistantFeedException()
{
$this->expectException('InvalidArgumentException');
$this->expectExceptionMessage("Specified feed 'unknown_feed_name' is not defined in your configuration.");
$this->manager->get('unknown_feed_name');
}
/**
* Check if the feed data are properly loaded from configuration settings.
*/
public function testGetFeedData()
{
$feed = $this->manager->get('article');
$this->assertEquals('My articles/posts', $feed->get('title'));
$this->assertEquals('Latests articles', $feed->get('description'));
$this->assertEquals('http://github.com/eko/FeedBundle', $feed->get('link'));
$this->assertEquals('utf-8', $feed->get('encoding'));
$this->assertEquals('Vincent Composieux', $feed->get('author'));
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Tests/Service/FeedDumpServiceTest.php | Tests/Service/FeedDumpServiceTest.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Tests\Service;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Eko\FeedBundle\Feed\Feed;
use Eko\FeedBundle\Feed\FeedManager;
use Eko\FeedBundle\Service\FeedDumpService;
use Eko\FeedBundle\Tests\Entity\Writer\FakeItemInterfaceEntity;
use Symfony\Component\Filesystem\Filesystem;
/**
* FeedDumpServiceTest.
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class FeedDumpServiceTest extends \PHPUnit\Framework\TestCase
{
/**
* @var FeedManager
*/
protected $feedManager;
/**
* @var EntityManagerInterface
*/
protected $entityManager;
/**
* @var Filesystem
*/
protected $filesystem;
/**
* @var FeedDumpService
*/
protected $service;
/**
* Sets up a dump service.
*/
protected function setUp(): void
{
$this->feedManager = $this->getMockBuilder(FeedManager::class)
->disableOriginalConstructor()
->getMock();
$this->entityManager = $this->getMockBuilder(EntityManagerInterface::class)
->disableOriginalConstructor()
->getMock();
$this->filesystem = $this->getMockBuilder(Filesystem::class)
->disableOriginalConstructor()
->getMock();
$this->service = new FeedDumpService($this->feedManager, $this->entityManager, $this->filesystem);
}
/**
* Tests the dump() method with an invalid order
* Should throw a \InvalidArgumentException.
*/
public function testDumpWithInvalidOrder()
{
if (!method_exists($this->filesystem, 'dumpFile')) {
$this->markTestSkipped('Test skipped as Filesystem::dumpFile() is not available in this version.');
}
$this->expectException('\InvalidArgumentException');
$this->service->setOrderBy('unexistant-order');
$this->service->dump();
}
/**
* Tests the dump() method with an entity.
*/
public function testDumpWithAnEntity()
{
if (!method_exists($this->filesystem, 'dumpFile')) {
$this->markTestSkipped('Test skipped as Filesystem::dumpFile() is not available in this version.');
}
// Given
$this->service->setRootDir('/unit/test/');
$this->service->setFilename('feed.rss');
$this->service->setEntity(FakeItemInterfaceEntity::class);
$this->service->setDirection('ASC');
$entity = $this->createMock(FakeItemInterfaceEntity::class);
$repository = $this->getMockBuilder(EntityRepository::class)
->disableOriginalConstructor()
->getMock();
$repository->expects($this->once())->method('findBy')->will($this->returnValue([$entity, $entity]));
$this->entityManager->expects($this->once())->method('getRepository')->will($this->returnValue($repository));
$feed = $this->getMockBuilder(Feed::class)
->disableOriginalConstructor()
->getMock();
$feed->expects($this->once())->method('addFromArray');
$feed->expects($this->once())->method('render')->will($this->returnValue('XML content'));
$this->feedManager->expects($this->once())->method('get')->will($this->returnValue($feed));
$this->filesystem
->expects($this->once())
->method('dumpFile')
->with('/unit/test/feed.rss', 'XML content');
// When - Expects actions
$this->service->dump();
}
/**
* Tests the dump() method without any items or entity set.
*/
public function testDumpWithoutItemsOrEntity()
{
if (!method_exists($this->filesystem, 'dumpFile')) {
$this->markTestSkipped('Test skipped as Filesystem::dumpFile() is not available in this version.');
}
$this->expectException('\LogicException');
$this->expectExceptionMessage('An entity should be set OR you should use setItems() first');
// Given
$this->service->setRootDir('/unit/test/');
$this->service->setFilename('feed.rss');
$this->service->setDirection('ASC');
$feed = $this->getMockBuilder(Feed::class)
->disableOriginalConstructor()
->getMock();
$feed->expects($this->once())->method('hasItems')->will($this->returnValue(true));
$this->feedManager->expects($this->once())->method('get')->will($this->returnValue($feed));
// When - Expects exception
$this->service->dump();
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Item/Reader/ItemInterface.php | Item/Reader/ItemInterface.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Item\Reader;
/**
* Item interface.
*
* This interface contains the methods that you need to implement in your entity
* to load data from an XML feed in your entity
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
interface ItemInterface
{
/**
* This method sets feed item title.
*
* @param string $title
*
* @abstract
*/
public function setFeedItemTitle($title);
/**
* This method sets feed item description (or content).
*
* @param string $description
*
* @abstract
*/
public function setFeedItemDescription($description);
/**
* This method sets feed item URL link.
*
* @param string $link
*
* @abstract
*/
public function setFeedItemLink($link);
/**
* This method sets item publication date.
*
* @param \DateTime $date
*
* @abstract
*/
public function setFeedItemPubDate(\DateTime $date);
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Item/Writer/ProxyItem.php | Item/Writer/ProxyItem.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Item\Writer;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\RouterInterface;
/**
* Proxy Item.
*
* This interface contains the methods that you need to implement in your entity
*
* @author Rob Masters <mastahuk@gmail.com>
*/
class ProxyItem implements ItemInterface
{
/**
* @var RoutedItemInterface
*/
protected $item;
/**
* @var RouterInterface
*/
protected $router;
/**
* Constructor.
*
* @param RoutedItemInterface $item
* @param RouterInterface $router
*/
public function __construct(RoutedItemInterface $item, RouterInterface $router)
{
$this->item = $item;
$this->router = $router;
}
/**
* Returns item custom fields methods if exists in entity.
*
* @param string $method Method name
* @param array $args Arguments array
*
* @throws \InvalidArgumentException If method is not defined
*
* @return mixed
*/
public function __call($method, $args)
{
if (method_exists($this->item, $method)) {
return call_user_func_array([$this->item, $method], $args);
}
throw new \InvalidArgumentException(sprintf('Method "%s" should be defined in your entity.', $method));
}
/**
* This method returns feed item title.
*
* @return string
*/
public function getFeedItemTitle()
{
return $this->item->getFeedItemTitle();
}
/**
* This method returns feed item description (or content).
*
* @return string
*/
public function getFeedItemDescription()
{
return $this->item->getFeedItemDescription();
}
/**
* This method returns feed item URL link.
*
* @return string
*/
public function getFeedItemLink()
{
$parameters = $this->item->getFeedItemRouteParameters() ?: [];
$url = $this->router->generate($this->item->getFeedItemRouteName(), $parameters, UrlGeneratorInterface::ABSOLUTE_URL);
$anchor = (string) $this->item->getFeedItemUrlAnchor();
if ($anchor !== '') {
$url .= '#'.$anchor;
}
return $url;
}
/**
* This method returns item publication date.
*
* @return \DateTime
*/
public function getFeedItemPubDate()
{
return $this->item->getFeedItemPubDate();
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Item/Writer/ItemInterface.php | Item/Writer/ItemInterface.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Item\Writer;
/**
* Item interface.
*
* This interface contains the methods that you need to implement in your entity
* to write your entity data in an XML feed
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
interface ItemInterface
{
/**
* This method returns feed item title.
*
* @abstract
*
* @return string
*/
public function getFeedItemTitle();
/**
* This method returns feed item description (or content).
*
* @abstract
*
* @return string
*/
public function getFeedItemDescription();
/**
* This method returns feed item URL link.
*
* @abstract
*
* @return string
*/
public function getFeedItemLink();
/**
* This method returns item publication date.
*
* @abstract
*
* @return \DateTime
*/
public function getFeedItemPubDate();
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Item/Writer/RoutedItemInterface.php | Item/Writer/RoutedItemInterface.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Item\Writer;
/**
* Routed Item interface.
*
* This interface contains the methods that you need to implement in your entity
* to write your entity data in an XML feed
*
* @author Rob Masters <mastahuk@gmail.com>
*/
interface RoutedItemInterface
{
/**
* This method returns feed item title.
*
* @abstract
*
* @return string
*/
public function getFeedItemTitle();
/**
* This method returns feed item description (or content).
*
* @abstract
*
* @return string
*/
public function getFeedItemDescription();
/**
* This method returns the name of the route.
*
* @abstract
*
* @return string
*/
public function getFeedItemRouteName();
/**
* This method returns the parameters for the route.
*
* @abstract
*
* @return array
*/
public function getFeedItemRouteParameters();
/**
* This method returns the anchor to be appended on this item's url.
*
* @abstract
*
* @return string The anchor, without the "#"
*/
public function getFeedItemUrlAnchor();
/**
* This method returns item publication date.
*
* @abstract
*
* @return \DateTime
*/
public function getFeedItemPubDate();
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Field/Channel/GroupChannelField.php | Field/Channel/GroupChannelField.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Field\Channel;
use Eko\FeedBundle\Field\Item\GroupItemField;
/**
* GroupChannelField.
*
* This is channel group field class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class GroupChannelField extends GroupItemField implements ChannelFieldInterface
{
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Field/Channel/ChannelFieldInterface.php | Field/Channel/ChannelFieldInterface.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Field\Channel;
use Eko\FeedBundle\Field\Item\ItemFieldInterface;
/**
* ChannelFieldInterface.
*
* This is the channel field interface
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
interface ChannelFieldInterface extends ItemFieldInterface
{
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Field/Channel/ChannelField.php | Field/Channel/ChannelField.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Field\Channel;
/**
* ChannelField.
*
* This is the channel field class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class ChannelField implements ChannelFieldInterface
{
/**
* @var string Field name
*/
protected $name;
/**
* @var string Field value
*/
protected $value;
/**
* @var array Options array (required, cdata, ...)
*/
protected $options;
/**
* @var array An attributes array
*/
protected $attributes;
/**
* Constructor.
*
* @param string $name A field name
* @param string $value A field value
* @param array $options An options array
* @param array $attributes An attributes array
*/
public function __construct($name, $value, array $options = [], array $attributes = [])
{
$this->name = $name;
$this->value = $value;
if (!empty($options)) {
$this->options = $options;
}
$this->attributes = $attributes;
}
/**
* Returns field name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Returns field value.
*
* @return string
*/
public function getValue()
{
return $this->value;
}
/**
* Returns option value.
*
* @param string $option An option name
* @param mixed $default A default value
*
* @return mixed
*/
public function get($option, $default = false)
{
return isset($this->options[$option]) ? $this->options[$option] : $default;
}
/**
* Returns attributes to be added to this item field.
*
* @return array
*/
public function getAttributes()
{
return $this->attributes;
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Field/Item/MediaItemField.php | Field/Item/MediaItemField.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Field\Item;
/**
* MediaItemField.
*
* This is the media items field class that uses enclosure
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class MediaItemField extends ItemField
{
/**
* Constructor.
*
* @param string $method An item method name
* @param array $options An options array
* @param array $attributes An attributes array
*/
public function __construct($method, array $options = [], array $attributes = [])
{
$name = [
'rss' => 'enclosure',
'atom' => 'link',
];
parent::__construct($name, $method, $options, $attributes);
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Field/Item/ItemField.php | Field/Item/ItemField.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Field\Item;
/**
* ItemField.
*
* This is the items field class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class ItemField implements ItemFieldInterface
{
/**
* @var string Field name
*/
protected $name;
/**
* @var string Item method name
*/
protected $method;
/**
* @var array Options array (required, cdata, ...)
*/
protected $options;
/**
* @var array Attributes to add to this item field
*/
protected $attributes;
/**
* Constructor.
*
* @param string|array $name A field name
* @param string $method An item method name
* @param array $options An options array
* @param array $attributes An attributes array
*/
public function __construct($name, $method, array $options = [], array $attributes = [])
{
$this->name = $name;
$this->method = $method;
if (!empty($options)) {
$this->options = $options;
}
$this->attributes = $attributes;
}
/**
* Returns field name.
*
* @return string|array
*/
public function getName()
{
return $this->name;
}
/**
* Returns method name.
*
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* Returns option value.
*
* @param string $option An option name
* @param mixed $default A default value
*
* @return mixed
*/
public function get($option, $default = false)
{
return isset($this->options[$option]) ? $this->options[$option] : $default;
}
/**
* Returns attributes to be added to this item field.
*
* @return array
*/
public function getAttributes()
{
return $this->attributes;
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Field/Item/ItemFieldInterface.php | Field/Item/ItemFieldInterface.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Field\Item;
/**
* ItemFieldInterface.
*
* This is the item field interface
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
interface ItemFieldInterface
{
/**
* Returns field name.
*
* @return string
*/
public function getName();
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Field/Item/GroupItemField.php | Field/Item/GroupItemField.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Field\Item;
/**
* GroupItemField.
*
* This is items group field class
*
* @author Vincent Composieux <vincent.composieux@gmail.com>
*/
class GroupItemField implements ItemFieldInterface
{
/**
* @var string Field name
*/
protected $name;
/**
* @var array ItemField instances
*/
protected $itemFields;
/**
* @var array
*/
protected $attributes;
/**
* Constructor.
*
* @param string $name A group field name
* @param array|ItemFieldInterface $itemFields An array or a single ItemField instance
* @param array $attributes An attributes array to add to item fields
*
* @throws \RuntimeException if
*/
public function __construct($name, $itemFields, array $attributes = [])
{
$this->name = $name;
if (!is_array($itemFields) && !$itemFields instanceof ItemFieldInterface) {
throw new \RuntimeException('GroupItemField second arguments should be an array or a single ItemField instance');
}
if (!is_array($itemFields)) {
$itemFields = [$itemFields];
}
$this->itemFields = $itemFields;
$this->attributes = $attributes;
}
/**
* Returns group field name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Returns item fields.
*
* @return array
*/
public function getItemFields()
{
return $this->itemFields;
}
/**
* Returns attributes to add to this group item field.
*
* @return array
*/
public function getAttributes()
{
return $this->attributes;
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Service/FeedDumpService.php | Service/FeedDumpService.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
use Eko\FeedBundle\Feed\FeedManager;
use Symfony\Component\Filesystem\Filesystem;
/**
* Class FeedDumpService.
*
* This class helps to dump your feeds on filesystem
*
* @author Thomas P. <http://github.com/ScullWM>
*/
class FeedDumpService
{
/**
* @var FeedManager
*/
private $feedManager;
/**
* @var EntityManagerInterface
*/
private $em;
/**
* @var Filesystem
*/
private $filesystem;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $entity;
/**
* @var string
*/
private $filename;
/**
* @var string
*/
private $format;
/**
* @var int
*/
private $limit;
/**
* @var string
*/
private $direction;
/**
* @var string
*/
private $orderBy;
/**
* @var string
*/
private $rootDir;
/**
* Constructor.
*
* @param FeedManager $feedManager A Feed manager
* @param EntityManagerInterface $em A Doctrine entity manager
* @param Filesystem $filesystem A Symfony Filesystem component
*/
public function __construct(FeedManager $feedManager, EntityManagerInterface $em, Filesystem $filesystem)
{
$this->feedManager = $feedManager;
$this->em = $em;
$this->filesystem = $filesystem;
}
/**
* Dumps a feed from an entity or feed items using Filesystem component.
*
* @throws \RuntimeException
* @throws \LogicException
*/
public function dump()
{
if (!method_exists($this->filesystem, 'dumpFile')) {
throw new \RuntimeException('Method dumpFile() is not available on your Filesystem component version, you should upgrade it.');
}
$this->initDirection();
$feed = $this->feedManager->get($this->name);
if ($this->entity) {
$repository = $this->em->getRepository($this->entity);
$items = $repository->findBy([], $this->orderBy, $this->limit);
$feed->addFromArray($items);
} elseif ($feed->hasItems()) {
throw new \LogicException(sprintf('An entity should be set OR you should use setItems() first'));
}
$dump = $feed->render($this->format);
$filepath = $this->rootDir.$this->filename;
$this->filesystem->dumpFile($filepath, $dump);
}
/**
* Initialize ordering.
*
* @throws \InvalidArgumentException
*/
private function initDirection()
{
if (null !== $this->orderBy) {
switch ($this->direction) {
case 'ASC':
case 'DESC':
$this->orderBy = [$this->orderBy => $this->direction];
break;
default:
throw new \InvalidArgumentException(sprintf('"direction" option should be set with "orderBy" and should be ASC or DESC'));
break;
}
}
}
/**
* Sets items to the feed.
*
* @param array $items items list
*
* @return $this
*/
public function setItems(array $items)
{
$this->feedManager->get($this->name)->addFromArray($items);
return $this;
}
/**
* Sets the value of name.
*
* @param mixed $name the name
*
* @return $this
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Sets the value of entity.
*
* @param mixed $entity the entity
*
* @return $this
*/
public function setEntity($entity)
{
$this->entity = $entity;
return $this;
}
/**
* Sets the value of filename.
*
* @param string $filename
*
* @return $this
*/
public function setFilename($filename)
{
$this->filename = $filename;
return $this;
}
/**
* Sets the value of format.
*
* @param string $format
*
* @return $this
*/
public function setFormat($format)
{
$this->format = $format;
return $this;
}
/**
* Sets the value of limit.
*
* @param int $limit
*
* @return $this
*/
public function setLimit($limit)
{
$this->limit = $limit;
return $this;
}
/**
* Sets the value of direction.
*
* @param string $direction
*
* @return $this
*/
public function setDirection($direction)
{
$this->direction = $direction;
return $this;
}
/**
* Sets the value of orderBy.
*
* @param string $orderBy
*
* @return $this
*/
public function setOrderBy($orderBy)
{
$this->orderBy = $orderBy;
return $this;
}
/**
* Sets the value of rootDir.
*
* @param string $rootDir
*
* @return $this
*/
public function setRootDir($rootDir)
{
$this->rootDir = $rootDir;
return $this;
}
/**
* Return rootdir.
*
* @return string
*/
public function getRootDir()
{
return $this->rootDir;
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
eko/FeedBundle | https://github.com/eko/FeedBundle/blob/f57ad60a9b7eafbd8b87d4788c015d02bcde643b/Command/FeedDumpCommand.php | Command/FeedDumpCommand.php | <?php
/*
* This file is part of the Eko\FeedBundle Symfony bundle.
*
* (c) Vincent Composieux <vincent.composieux@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Eko\FeedBundle\Command;
use Eko\FeedBundle\Service\FeedDumpService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Routing\RouterInterface;
/**
* FeedDumpCommand.
*
* This command generate a feed in an XML file
*
* @author Vincent Composieux <composieux@ekino.com>
*/
class FeedDumpCommand extends Command
{
protected static $defaultName = 'eko:feed:dump';
/**
* @var RouterInterface
*/
private $router;
/**
* @var FeedDumpService|null
*/
private $feedDumpService;
public function __construct(RouterInterface $router, FeedDumpService $feedDumpService = null)
{
$this->router = $router;
$this->feedDumpService = $feedDumpService;
parent::__construct();
}
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setDescription('Generate (dump) a feed in an XML file')
->addOption('name', null, InputOption::VALUE_REQUIRED, 'Feed name defined in eko_feed configuration')
->addOption('entity', null, InputOption::VALUE_REQUIRED, 'Entity to use to generate the feed')
->addOption('filename', null, InputOption::VALUE_REQUIRED, 'Defines feed filename')
->addOption('orderBy', null, InputOption::VALUE_OPTIONAL, 'Order field to sort by using findBy() method')
->addOption('direction', null, InputOption::VALUE_OPTIONAL, 'Direction to give to sort field with findBy() method')
->addOption('format', null, InputOption::VALUE_OPTIONAL, 'Formatter to use to generate, "rss" is default')
->addOption('limit', null, InputOption::VALUE_OPTIONAL, 'Defines a limit of entity items to retrieve')
->addArgument('host', InputArgument::REQUIRED, 'Set the host');
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output): int
{
if (null === $this->feedDumpService) {
throw new \RuntimeException(sprintf(
'The "%s" service used in this command requires Doctrine ORM to be configured.',
FeedDumpService::class
));
}
$name = $input->getOption('name');
$entity = $input->getOption('entity');
$filename = $input->getOption('filename');
$format = $input->getOption('format') ?: 'rss';
$limit = $input->getOption('limit');
$direction = $input->getOption('direction');
$orderBy = $input->getOption('orderBy');
$this->router->getContext()->setHost($input->getArgument('host'));
$this->feedDumpService
->setName($name)
->setEntity($entity)
->setFilename($filename)
->setFormat($format)
->setLimit($limit)
->setDirection($direction)
->setOrderBy($orderBy);
$this->feedDumpService->dump();
$output->writeln('<comment>done!</comment>');
$output->writeln(sprintf('<info>Feed has been dumped and located in "%s"</info>', $this->feedDumpService->getRootDir().$filename));
return 0;
}
}
| php | MIT | f57ad60a9b7eafbd8b87d4788c015d02bcde643b | 2026-01-05T04:47:01.278459Z | false |
Webklex/laravel-pdfmerger | https://github.com/Webklex/laravel-pdfmerger/blob/de88152c793fb190631a050688478f4a18bbac22/src/PDFMerger/PDFMerger.php | src/PDFMerger/PDFMerger.php | <?php
/*
* File: PDFMerger.php
* Category: PDFMerger
* Author: M. Goldenbaum
* Created: 01.12.16 20:18
* Updated: -
*
* Description:
* -
*/
namespace Webklex\PDFMerger;
use setasign\Fpdi\Fpdi as FPDI;
use setasign\Fpdi\PdfParser\StreamReader;
use Illuminate\Filesystem\Filesystem;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Http\Response;
class PDFMerger {
/**
* Access the filesystem on an oop base
*
* @var Filesystem
*/
protected $oFilesystem = Filesystem::class;
/**
* Hold all the files which will be merged
*
* @var Collection
*/
protected $aFiles = Collection::class;
/**
* Holds every tmp file so they can be removed during the deconstruction
*
* @var Collection
*/
protected $tmpFiles = Collection::class;
/**
* The actual PDF Service
*
* @var FPDI
*/
protected $oFPDI = FPDI::class;
/**
* The final file name
*
* @var string
*/
protected $fileName = 'undefined.pdf';
/**
* Construct and initialize a new instance
* @param Filesystem $oFilesystem
*/
public function __construct(Filesystem $oFilesystem){
$this->oFilesystem = $oFilesystem;
$this->oFPDI = new FPDI();
$this->tmpFiles = collect([]);
$this->init();
}
/**
* The class deconstructor method
*/
public function __destruct() {
$oFilesystem = $this->oFilesystem;
$this->tmpFiles->each(function($filePath) use($oFilesystem){
$oFilesystem->delete($filePath);
});
}
/**
* Initialize a new internal instance of FPDI in order to prevent any problems with shared resources
* Please visit https://www.setasign.com/products/fpdi/manual/#p-159 for more information on this issue
*
* @return self
*/
public function init(){
$this->oFPDI = new FPDI();
$this->aFiles = collect([]);
return $this;
}
/**
* Stream the merged PDF content
*
* @return string
*/
public function stream(){
return $this->oFPDI->Output($this->fileName, 'I');
}
/**
* Download the merged PDF content
*
* @return string
*/
public function download(){
$output = $this->output();
$response = new Response($output, 200, [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="' . $this->fileName . '"',
'Content-Length' => strlen($output),
]);
return $response->send();
}
/**
* Save the merged PDF content to the filesystem
*
* @return string
*/
public function save($filePath = null){
return $this->oFilesystem->put($filePath?$filePath:$this->fileName, $this->output());
}
/**
* Get the merged PDF content
*
* @return string
*/
public function output(){
return $this->oFPDI->Output($this->fileName, 'S');
}
/**
* Set the final filename
* @param string $fileName
*
* @return string
*/
public function setFileName($fileName){
$this->fileName = $fileName;
return $this;
}
/**
* Set the final filename
* @param string $string
* @param mixed $pages
* @param mixed $orientation
*
* @return string
*/
public function addString($string, $pages = 'all', $orientation = null){
$filePath = storage_path('tmp/'.Str::random(16).'.pdf');
$this->oFilesystem->put($filePath, $string);
$this->tmpFiles->push($filePath);
return $this->addPDF($filePath, $pages, $orientation);
}
/**
* Add a PDF for inclusion in the merge with a valid file path. Pages should be formatted: 1,3,6, 12-16.
* @param string $filePath
* @param string $pages
* @param string $orientation
*
* @return self
*
* @throws \Exception if the given pages aren't correct
*/
public function addPDF($filePath, $pages = 'all', $orientation = null) {
if (file_exists($filePath)) {
if (!is_array($pages) && strtolower($pages) != 'all') {
throw new \Exception($filePath."'s pages could not be validated");
}
$this->aFiles->push([
'name' => $filePath,
'pages' => $pages,
'orientation' => $orientation
]);
} else {
throw new \Exception("Could not locate PDF on '$filePath'");
}
return $this;
}
/**
* Merges your provided PDFs and outputs to specified location.
* @param string $orientation
*
* @return void
*
* @throws \Exception if there are now PDFs to merge
*/
public function merge($orientation = null) {
$this->doMerge($orientation, false);
}
/**
* Merges your provided PDFs and adds blank pages between documents as needed to allow duplex printing
* @param string $orientation
*
* @return void
*
* @throws \Exception if there are now PDFs to merge
*/
public function duplexMerge($orientation = 'P') {
$this->doMerge($orientation, true);
}
protected function doMerge($orientation, $duplexSafe) {
if ($this->aFiles->count() == 0) {
throw new \Exception("No PDFs to merge.");
}
$oFPDI = $this->oFPDI;
$this->aFiles->each(function($file) use($oFPDI, $orientation, $duplexSafe){
$file['orientation'] = is_null($file['orientation'])?$orientation:$file['orientation'];
$count = $oFPDI->setSourceFile(StreamReader::createByString(file_get_contents($file['name'])));
if ($file['pages'] == 'all') {
for ($i = 1; $i <= $count; $i++) {
$template = $oFPDI->importPage($i);
$size = $oFPDI->getTemplateSize($template);
$autoOrientation = isset($file['orientation']) ? $file['orientation'] : $size['orientation'];
$oFPDI->AddPage($autoOrientation, [$size['width'], $size['height']]);
$oFPDI->useTemplate($template);
}
} else {
foreach ($file['pages'] as $page) {
if (!$template = $oFPDI->importPage($page)) {
throw new \Exception("Could not load page '$page' in PDF '" . $file['name'] . "'. Check that the page exists.");
}
$size = $oFPDI->getTemplateSize($template);
$autoOrientation = isset($file['orientation']) ? $file['orientation'] : $size['orientation'];
$oFPDI->AddPage($autoOrientation, [$size['width'], $size['height']]);
$oFPDI->useTemplate($template);
}
}
if ($duplexSafe && $oFPDI->page % 2) {
$oFPDI->AddPage($file['orientation'], [$size['width'], $size['height']]);
}
});
}
}
| php | MIT | de88152c793fb190631a050688478f4a18bbac22 | 2026-01-05T04:47:05.418543Z | false |
Webklex/laravel-pdfmerger | https://github.com/Webklex/laravel-pdfmerger/blob/de88152c793fb190631a050688478f4a18bbac22/src/PDFMerger/Facades/PDFMergerFacade.php | src/PDFMerger/Facades/PDFMergerFacade.php | <?php
/*
* File: PDFMergerFacade.php
* Category: Facade
* Author: M. Goldenbaum
* Created: 01.12.16 21:06
* Updated: -
*
* Description:
* -
*/
namespace Webklex\PDFMerger\Facades;
use \Illuminate\Support\Facades\Facade;
/**
* @see \Illuminate\Translation\Translator
*/
class PDFMergerFacade extends Facade {
/**
* Get the registered name of the component.
*
* @return string
*/
protected static function getFacadeAccessor() {
return 'PDFMerger';
}
}
| php | MIT | de88152c793fb190631a050688478f4a18bbac22 | 2026-01-05T04:47:05.418543Z | false |
Webklex/laravel-pdfmerger | https://github.com/Webklex/laravel-pdfmerger/blob/de88152c793fb190631a050688478f4a18bbac22/src/PDFMerger/Providers/PDFMergerServiceProvider.php | src/PDFMerger/Providers/PDFMergerServiceProvider.php | <?php
/*
* File: PDFMergerServiceProvider.php
* Category: Provider
* Author: M. Goldenbaum
* Created: 01.12.16 20:28
* Updated: -
*
* Description:
* -
*/
namespace Webklex\PDFMerger\Providers;
use Illuminate\Support\ServiceProvider;
use Webklex\PDFMerger\PDFMerger;
class PDFMergerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the service provider.
*
* @return void
*/
public function register()
{
$this->app->singleton('PDFMerger', function ($app) {
$oPDFMerger = new PDFMerger($app['files']);
return $oPDFMerger;
});
}
} | php | MIT | de88152c793fb190631a050688478f4a18bbac22 | 2026-01-05T04:47:05.418543Z | false |
cebe/js-search | https://github.com/cebe/js-search/blob/3756a8b3387f3f7e5c778b964ec681dcf110b098/lib/Indexer.php | lib/Indexer.php | <?php
/**
* @copyright Copyright (c) 2014 Carsten Brandt
* @license https://github.com/cebe/js-search/blob/master/LICENSE
* @link https://github.com/cebe/js-search#readme
*/
namespace cebe\jssearch;
use cebe\jssearch\analyzer\HtmlAnalyzer;
use cebe\jssearch\tokenizer\StandardTokenizer;
/**
* @author Carsten Brandt <mail@cebe.cc>
*/
class Indexer
{
public $index = [];
public $files = [];
public function indexFiles($files, $basePath, $baseUrl = './')
{
$fi = count($this->files);
foreach($files as $file) {
$fi++;
$contents = file_get_contents($file);
// create file entry
$this->files[$fi] = $this->generateFileInfo($file, $contents, $basePath, $baseUrl);
// analyze file
foreach($this->getAnalyzer()->analyze($contents, $this->getTokenizer()) as $index) {
foreach($index as $word) {
// $word['t'] - the token
// $word['w'] - the weight
if (isset($this->index[$word['t']][$fi])) {
$this->index[$word['t']][$fi]['w'] *= $word['w'];
} else {
$this->index[$word['t']][$fi] = [
'f' => $fi,
'w' => $word['w'],
];
}
}
}
}
// reset array indexes for files to create correct json arrays
foreach($this->index as $word => $files) {
$this->index[$word] = array_values($files);
}
}
protected function generateFileInfo($file, $contents, $basePath, $baseUrl)
{
// create file entry
if (preg_match('~<h1>(.*?)</h1>~s', $contents, $matches)) {
$title = strip_tags($matches[1]);
} elseif (preg_match('~<title>(.*?)</title>~s', $contents, $matches)) {
$title = strip_tags($matches[1]);
} else {
$title = '<i>No title</i>';
}
return [
'url' => $baseUrl . str_replace('\\', '/', substr($file, strlen(rtrim($basePath, '\\/')))),
'title' => $title,
];
}
public function exportJs()
{
$index = json_encode($this->index);
$files = json_encode($this->files);
$tokenizeString = $this->getTokenizer()->tokenizeJs();
return <<<JS
jssearch.index = $index;
jssearch.files = $files;
jssearch.tokenizeString = $tokenizeString;
JS;
}
private $_tokenizer;
/**
* @return TokenizerInterface
*/
public function getTokenizer()
{
if ($this->_tokenizer === null) {
$this->_tokenizer = new StandardTokenizer();
}
return $this->_tokenizer;
}
/**
* @param TokenizerInterface $tokenizer
*/
public function setTokenizer($tokenizer)
{
$this->_tokenizer = $tokenizer;
}
private $_analyzer;
/**
* @return AnalyzerInterface
*/
public function getAnalyzer()
{
if ($this->_analyzer === null) {
$this->_analyzer = new HtmlAnalyzer();
}
return $this->_analyzer;
}
/**
* @param AnalyzerInterface $analyzer
*/
public function setAnalyzer($analyzer)
{
$this->_analyzer = $analyzer;
}
} | php | MIT | 3756a8b3387f3f7e5c778b964ec681dcf110b098 | 2026-01-05T04:47:13.076020Z | false |
cebe/js-search | https://github.com/cebe/js-search/blob/3756a8b3387f3f7e5c778b964ec681dcf110b098/lib/TokenizerInterface.php | lib/TokenizerInterface.php | <?php
/**
* @copyright Copyright (c) 2014 Carsten Brandt
* @license https://github.com/cebe/js-search/blob/master/LICENSE
* @link https://github.com/cebe/js-search#readme
*/
namespace cebe\jssearch;
/**
* Interface for all Tokenizers.
*
* @author Carsten Brandt <mail@cebe.cc>
*/
interface TokenizerInterface
{
/**
* Tokenizes a string and returns an array of the following format:
*
* ```
* [['word', 2], ['other', 1]]
* ```
*
* where the first part is the token string and the second is a weight value.
*
* @param string $string the string to tokenize
* @return array
*/
public function tokenize($string);
/**
* Returns a javascript equivalent of [[tokenize]] that will be used
* on client side to tokenize the search query.
* @return string
*/
public function tokenizeJs();
} | php | MIT | 3756a8b3387f3f7e5c778b964ec681dcf110b098 | 2026-01-05T04:47:13.076020Z | false |
cebe/js-search | https://github.com/cebe/js-search/blob/3756a8b3387f3f7e5c778b964ec681dcf110b098/lib/AnalyzerInterface.php | lib/AnalyzerInterface.php | <?php
/**
* @copyright Copyright (c) 2014 Carsten Brandt
* @license https://github.com/cebe/js-search/blob/master/LICENSE
* @link https://github.com/cebe/js-search#readme
*/
namespace cebe\jssearch;
/**
* Interface for all Tokenizers.
*
* @author Carsten Brandt <mail@cebe.cc>
*/
interface AnalyzerInterface
{
/**
* Analyzes a string and returns an array of the following format:
*
* TODO
* ```
* ```
*
* @param string $string the string to analyze
* @return array
*/
public function analyze($string, TokenizerInterface $tokenizer);
} | php | MIT | 3756a8b3387f3f7e5c778b964ec681dcf110b098 | 2026-01-05T04:47:13.076020Z | false |
cebe/js-search | https://github.com/cebe/js-search/blob/3756a8b3387f3f7e5c778b964ec681dcf110b098/lib/tokenizer/StandardTokenizer.php | lib/tokenizer/StandardTokenizer.php | <?php
/**
* @copyright Copyright (c) 2014 Carsten Brandt
* @license https://github.com/cebe/js-search/blob/master/LICENSE
* @link https://github.com/cebe/js-search#readme
*/
namespace cebe\jssearch\tokenizer;
use cebe\jssearch\TokenizerInterface;
/**
* StandardTokenizer
*
* @author Carsten Brandt <mail@cebe.cc>
*/
class StandardTokenizer implements TokenizerInterface
{
/**
* @var array a list of stopwords to remove from the token list.
*/
public $stopWords = [
// default lucene http://stackoverflow.com/questions/17527741/what-is-the-default-list-of-stopwords-used-in-lucenes-stopfilter
"a", "an", "and", "are", "as", "at", "be", "but", "by",
"for", "if", "in", "into", "is", "it",
"no", "not", "of", "on", "or", "such",
"that", "the", "their", "then", "there", "these",
"they", "this", "to", "was", "will", "with"
];
/**
* @var string a list of characters that should be used as word delimiters.
*/
public $delimiters = '.,;:\\/[](){}';
/**
* Tokenizes a string and returns an array of the following format:
*
* ```
* [['t' => 'word', 'w' => 2], ['t' => 'other', 'w' => 1]]
* ```
*
* where the first part is the token string and the second is a weight value.
*
* Also removes [[stopWords]] from the list.
*
* @param string $string the string to tokenize
* @return array
*/
public function tokenize($string)
{
$delimiters = preg_quote($this->delimiters, '/');
return array_map(function($token) {return ['t' => $token, 'w' => 1]; }, array_filter(
array_map(function($t) { return mb_strtolower($t, 'UTF-8'); }, preg_split("/[\\s$delimiters]+/", $string, -1, PREG_SPLIT_NO_EMPTY)),
function($word) {
return !in_array($word, $this->stopWords);
}
));
}
/**
* Returns a javascript equivalent of [[tokenize]] that will be used
* on client side to tokenize the search query.
*
* This is used to ensure the same tokenizer is used for building the index and for searching.
*
* @return string
*/
public function tokenizeJs()
{
$delimiters = preg_quote($this->delimiters, '/');
$stopWords = json_encode($this->stopWords);
return <<<JS
function(string) {
var stopWords = $stopWords;
return string.split(/[\s$delimiters]+/).map(function(val) {
return val.toLowerCase();
}).filter(function(val) {
for (w in stopWords) {
if (stopWords[w] == val) return false;
}
return true;
}).map(function(word) {
return {t: word, w: 1};
});
}
JS;
}
} | php | MIT | 3756a8b3387f3f7e5c778b964ec681dcf110b098 | 2026-01-05T04:47:13.076020Z | false |
cebe/js-search | https://github.com/cebe/js-search/blob/3756a8b3387f3f7e5c778b964ec681dcf110b098/lib/analyzer/HtmlAnalyzer.php | lib/analyzer/HtmlAnalyzer.php | <?php
/**
* @copyright Copyright (c) 2014 Carsten Brandt
* @license https://github.com/cebe/js-search/blob/master/LICENSE
* @link https://github.com/cebe/js-search#readme
*/
namespace cebe\jssearch\analyzer;
use cebe\jssearch\AnalyzerInterface;
use cebe\jssearch\TokenizerInterface;
/**
* Analyzer for HTML files
*
* @author Carsten Brandt <mail@cebe.cc>
*/
class HtmlAnalyzer implements AnalyzerInterface
{
public $headWeight = 20;
public $titleWeight = 4;
public $textWeight = 1.2;
/**
* @inheritDoc
*/
public function analyze($string, TokenizerInterface $tokenizer)
{
$index = array_merge(
$this->findText($string, '~<h(\d)>(.*?)</h\1>~s', ['text' => 2, 'weight' => 1], $tokenizer, function($w, $h) { return $w * ($this->headWeight - $h) / 10; }),
$this->findText($string, '~<title>(.*?)</title>~s', ['text' => 1], $tokenizer, $this->titleWeight),
$this->findText($string, '~<p>(.*?|(?R))</p>~s', ['text' => 1], $tokenizer, $this->textWeight),
$this->findText($string, '~<(th|td|li|dd|dt)>(.*?)</\1>~s', ['text' => 2], $tokenizer, $this->textWeight)
);
$wordCount = array_reduce($index, function($carry, $item) { return $carry + count($item); }, 0);
foreach($index as $i => $words) {
foreach($words as $w => $word) {
// $index[$i][$w]['w'] = 1 + $index[$i][$w]['w'] / $wordCount; // TODO improve weight formula here
}
}
return $index;
}
/**
* @param $string
* @param $pattern
* @param $selectors
* @param TokenizerInterface $tokenizer
*/
private function findText($string, $pattern, $selectors, $tokenizer, $weight)
{
$index = [];
preg_match_all($pattern, $string, $matches);
foreach($matches[0] as $i => $match) {
$index[] = array_map(
function($token) use ($weight, $matches, $selectors, $i) {
if ($weight instanceof \Closure) {
$w = call_user_func_array($weight, [$token['w'], $matches[$selectors['weight']][$i]]);
} else {
$w = $token['w'] * $weight;
}
return ['t' => $token['t'], 'w' => $w];
},
$tokenizer->tokenize(strip_tags($matches[$selectors['text']][$i]))
);
}
return $index;
}
} | php | MIT | 3756a8b3387f3f7e5c778b964ec681dcf110b098 | 2026-01-05T04:47:13.076020Z | false |
jeffpiazza/derbynet | https://github.com/jeffpiazza/derbynet/blob/07b0d7303c2d2563b7adfd8af1cabe389c114bac/testing/test-face-detection.php | testing/test-face-detection.php | <?php
$php_file = $argv[1];
$directory = $argv[2]; // e.g., 'data/headshots';
require_once($php_file);
$start = microtime(true);
$detector = new FaceDetector();
$files = array();
$dh = @opendir($directory);
while (($filename = readdir($dh)) !== false) {
if (preg_match('/jpg/i', $filename) && is_file($directory.DIRECTORY_SEPARATOR.$filename)) {
$files[] = $directory.DIRECTORY_SEPARATOR.$filename;
}
}
closedir($dh);
echo count($files)." photos to scan.\n";
$fail_count = 0;
foreach ($files as $file) {
$image = imagecreatefromjpeg($file);
$detection_start_time = microtime(true);
$box = $detector->detect_face($image);
$detection_end_time = microtime(true);
imagedestroy($image);
if ($box) {
echo " Identified ".$file." in ".($detection_end_time - $detection_start_time)."s\n";
} else {
++$fail_count;
echo "** Failed for ".$file." in ".($detection_end_time - $detection_start_time)."s\n";
}
}
$end_time = microtime(true);
echo "Net: $fail_count failed out of ".count($files)."\n";
echo "Total time ".($end_time - $start)."s\n";
?> | php | MIT | 07b0d7303c2d2563b7adfd8af1cabe389c114bac | 2026-01-05T04:46:00.013344Z | false |
jeffpiazza/derbynet | https://github.com/jeffpiazza/derbynet/blob/07b0d7303c2d2563b7adfd8af1cabe389c114bac/extras/facedetection/convert_haarcascade_data.php | extras/facedetection/convert_haarcascade_data.php | <?php
// The facedetection code is based on the OpenCV (http://opencv.org)
// implementation of Viola-Jones, and uses classifier data expressed as PHP data
// structures as follows:
//
// <classifier> ::= [ [ <width>, <height> ], <stage>... ]
// <stage> ::= [ <stage_threshold>, <weak>... ]
// <weak> ::= <node>
// <node> ::= [ <threshold>, <feature>, <left>, <right> ]
// <threshold> ::= number
// <left>, <right> ::= <value> (if is_number) OR
// ::= <node>
// <feature> ::= [ x, y, width, height, weight, x, y, width, height, weight ] OR
// <feature> ::= [ x, y, width, height, weight, x, y, width, height, weight, x, y, width, height, weight ]
//
// This script converts an xml file of classifier data, as found in the OpenCV
// project, into a serialized PHP data file.
//
// E.g., convert_from_xml('facedetection2/haarcascade_frontalface_alt2.xml', 'facedetection2/alt2.ser');
function convert_xml($infile, $outfile) {
$xml = simplexml_load_file($infile);
$classifier = new CascadeClassifier($xml->xpath('cascade')[0]);
file_put_contents($outfile, serialize($classifier->emit()));
}
function purge_empty(&$pieces) {
if (count($pieces) > 0 && empty($pieces[0])) {
array_shift($pieces);
}
}
function split_text($txt) {
$pieces = preg_split('/\s+/', $txt);
purge_empty($pieces);
return $pieces;
}
function as_int($x) {
if (!is_int($x)) {
$xx = $x>>0;
if ($xx != $x) {
trigger_error("Can't make integer from ".$x);
}
$x = $xx;
}
return $x;
}
// Rects have inclusive lower bounds (x,y) that go to zero,
// and exclusive upper bounds (x + width, y + height) that can reach window size limits
class Rect {
private $x;
private $y;
private $width;
private $height;
private $weight;
// xpath would be cascade/features/_/rects/_ to a single node
function __construct($underscore) {
$pieces = split_text((string) $underscore);
$this->x = as_int(array_shift($pieces));
$this->y = as_int(array_shift($pieces));
$this->width = as_int(array_shift($pieces));
$this->height = as_int(array_shift($pieces));
$this->weight = array_shift($pieces) + 0;
if (!is_int($this->x) || !is_int($this->y) || !is_int($this->width) || !is_int($this->height)) {
trigger_error("Non-integer rect coordinate: ".(string) $underscore);
}
purge_empty($pieces);
if (count($pieces) > 0) {
trigger_error("Rect failure: ".(string) $underscore);
}
}
function emit_to(&$value) {
$value[] = $this->x;
$value[] = $this->y;
$value[] = $this->width;
$value[] = $this->height;
$value[] = $this->weight;
}
}
class Feature {
private $rects;
// xpath would be cascade/features/_
function __construct($underscore) {
if (count($underscore->xpath('rects')) != 1) {
trigger_error("Ill-formed feature: ".$underscore->__toString());
}
if (count($underscore->xpath('rects/_')) > 3) {
trigger_error("Ill-formed feature: ".$underscore->__toString());
}
$this->rects = array();
foreach ($underscore->xpath('rects/_') as $rect) {
$this->rects[] = new Rect($rect);
}
}
function emit() {
$value = array();
foreach ($this->rects as $rect) {
$rect->emit_to($value);
}
return $value;
}
}
class InternalNode {
private $left; // <= 0 for a leaf value,
private $right; // > 0 for another InternalNode
private $feature_index;
private $threshold;
function __construct(&$pieces) {
$this->left = as_int(array_shift($pieces));
$this->right = as_int(array_shift($pieces));
$this->feature_index = as_int(array_shift($pieces));
$this->threshold = array_shift($pieces) + 0;
}
function emit(&$internals, &$leaves, &$features) {
$value = array();
$value[] = $this->threshold;
$value[] = $features[$this->feature_index]->emit();
$value[] = $this->emit_sub($this->left, $internals, $leaves, $features);
$value[] = $this->emit_sub($this->right, $internals, $leaves, $features);
return $value;
}
function emit_sub($selector, &$internals, &$leaves, &$features) {
if ($selector <= 0) {
return $leaves[-$selector];
} else {
return $internals[$selector]->emit($internals, $leaves, $features);
}
}
};
class WeakClassifier {
private $internals;
private $leaves;
// xpath is cascade/stages/_/weakClassifiers/_
function __construct($underscore) {
if (count($underscore->xpath('leafValues')) != 1) {
trigger_error("Ill-formed Weak Classifer: no leaf values: ".$underscore->__toString());
}
$this->internals = array();
$this->leaves = array();
$pieces = split_text((string) $underscore->xpath('leafValues')[0]);
while (count($pieces) > 0) {
$this->leaves[] = array_shift($pieces) + 0;
}
if (count($underscore->xpath('internalNodes')) != 1) {
tigger_error("Ill-formed Weak Classifier: no internal nodes: ".$underscore->__toString());
}
$pieces = split_text((string) $underscore->xpath('internalNodes')[0]);
while (count($pieces) > 0) {
$this->internals[] = new InternalNode($pieces);
}
}
function emit(&$features) {
return $this->internals[0]->emit($this->internals, $this->leaves, $features);
}
}
class Stage {
private $weaks; // weak classifiers
private $stage_threshold;
// xpath is cascade/stages/_
function __construct($underscore) {
// stageThreshold
$this->stage_threshold = 0 + (string) ($underscore->xpath('stageThreshold')[0]);
$this->weaks = array();
foreach ($underscore->xpath('weakClassifiers/_') as $underscore) {
$this->weaks[] = new WeakClassifier($underscore);
}
$weak = $underscore->xpath('maxWeakCount');
if (count($weak) == 0) {
} else if (count($weak) == 1) {
echo "maxWeakCount: ".((string) ($underscore->xpath('maxWeakCount')[0]))."\n";
$maxWeakCount = ((string) ($underscore->xpath('maxWeakCount')[0]))>>0;
if (count($this->weaks) != $maxWeakCount) {
trigger_error("Wrong number of weak classifiers (".$maxWeakCounts." vs ".count($this->weaks).")");
}
} else {
trigger_error("Too many maxWeakCount: ".$underscore->__toString());
}
}
function emit(&$features) {
$value = array();
$value[] = $this->stage_threshold;
foreach ($this->weaks as $weak) {
$value[] = $weak->emit($features);
}
return $value;
}
}
class CascadeClassifier {
public $window_width;
public $window_height;
private $features;
private $stages;
// xpath is just 'cascade'
function __construct($cascade) {
$this->window_width = ((string) ($cascade->xpath('width')[0]))>>0;
$this->window_height = ((string) ($cascade->xpath('height')[0]))>>0;
$this->features = array();
foreach ($cascade->xpath('features/_') as $underscore) {
$this->features[] = new Feature($underscore);
}
$this->stages = array();
foreach($cascade->xpath("stages/_") as $underscore) {
$this->stages[] = new Stage($underscore);
}
}
function emit() {
$value = array();
$value[] = array($this->window_width, $this->window_height);
foreach ($this->stages as $stage) {
$value[] = $stage->emit($this->features);
}
return $value;
}
}
?> | php | MIT | 07b0d7303c2d2563b7adfd8af1cabe389c114bac | 2026-01-05T04:46:00.013344Z | false |
jeffpiazza/derbynet | https://github.com/jeffpiazza/derbynet/blob/07b0d7303c2d2563b7adfd8af1cabe389c114bac/demo/now-racing.php | demo/now-racing.php | <?php
session_start();
$simulated_polling_url = 'js/simulated-polling.js';
function get_lane_count() { return 4; }
require_once('inc/kiosks.inc');
$_GET['page'] = 'kiosks/now-racing.kiosk';
require('kiosks/now-racing.kiosk');
?>
| php | MIT | 07b0d7303c2d2563b7adfd8af1cabe389c114bac | 2026-01-05T04:46:00.013344Z | false |
jeffpiazza/derbynet | https://github.com/jeffpiazza/derbynet/blob/07b0d7303c2d2563b7adfd8af1cabe389c114bac/website/scenes.php | website/scenes.php | <?php @session_start();
// $_GET['back'] if "Back" button should go to another page, otherwise kiosk-coordinator.php.
require_once('inc/data.inc');
require_once('inc/authorize.inc');
session_write_close();
require_once('inc/banner.inc');
require_once('inc/kiosks.inc');
require_once('inc/scenes.inc');
require_once('inc/schema_version.inc');
require_once('inc/standings.inc');
require_permission(SET_UP_PERMISSION);
?><!DOCTYPE html>
<html>
<head>
<title>Scenes</title>
<?php require('inc/stylesheet.inc'); ?>
<link rel="stylesheet" type="text/css" href="css/mobile.css"/>
<link rel="stylesheet" type="text/css" href="css/scenes.css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/mobile.js"></script>
<script type='text/javascript' src="js/modal.js"></script>
<script type="text/javascript" src="js/kiosk-parameters.js"></script>
<script type='text/javascript' src="js/scenes.js"></script>
<script type='text/javascript'>
///////////////////////////////////
// g_all_scene_kiosk_names is a sorted list of kiosk names, e.g.,
// ["Main","Aux1","Aux2"].
//
// g_all_scenes is an array of e.g.
// { "sceneid": "4",
// "name": "Awards",
// "kiosks": [{ "kiosk_name": "Main",
// "page": "kiosks\/award-presentations.kiosk",
// "parameters": "{}"
// }]
// }
//
// g_current_scene is the name of the scene currently being shown on this page.
//
// g_all_pages is an array of e.g.
// { "brief": "award-presentations",
// "full": "kiosks\/award-presentations.kiosk" },
///////////////////////////////////
var g_all_scenes = <?php echo json_encode(all_scenes(),
JSON_HEX_TAG | JSON_HEX_AMP | JSON_PRETTY_PRINT); ?>;
var g_all_scene_kiosk_names = <?php echo json_encode(all_scene_kiosk_names(),
JSON_HEX_TAG | JSON_HEX_AMP); ?>;
var g_current_scene = <?php echo json_encode(read_raceinfo('current_scene', ''),
JSON_HEX_TAG | JSON_HEX_AMP); ?>;
var g_all_pages = <?php echo json_encode(all_kiosk_pages(),
JSON_HEX_TAG | JSON_HEX_AMP | JSON_PRETTY_PRINT); ?>;
<?php
$oracle = new StandingsOracle();
?>
var g_standings_choices = <?php echo json_encode($oracle->standings_choices_for_scenes(),
JSON_HEX_TAG | JSON_HEX_AMP | JSON_PRETTY_PRINT); ?>;
</script>
</head>
<body>
<?php make_banner('Scenes', isset($_GET['back']) ? $_GET['back'] : 'kiosk-dashboard.php'); ?>
<div id="select-wrap" class="block_buttons">
<!-- block_buttons for .block_buttons option css rule -->
<select id="scenes-select">
</select>
</div>
<div id="previews">
</div>
<div class="block_buttons">
<input type="button" id="add_kiosk_button" value="Add Kiosk Name"
onclick='on_add_kiosk()'/>
<input type="button" id="delete_scene_button" class="delete_button" value="Delete Scene"
onclick='on_delete_scene()'/>
</div>
<?php require('inc/kiosk-parameters.inc'); ?>
<div id="new_scene_modal" class="modal_dialog hidden block_buttons">
<form>
<h3>Make New Scene</h3>
<input type="text" id="new_scene_name"/>
<input type="submit" value="Create"/>
<input type="button" value="Cancel"
onclick='close_modal("#new_scene_modal");'/>
</form>
</div>
<div id="new_kiosk_modal" class="modal_dialog hidden block_buttons">
<form>
<h3>Make New Kiosk Name</h3>
<input type="text" id="new_kiosk_name"/>
<input type="submit" value="Create"/>
<input type="button" value="Cancel"
onclick='close_modal("#new_kiosk_modal");'/>
</form>
</div>
</body>
</html>
| php | MIT | 07b0d7303c2d2563b7adfd8af1cabe389c114bac | 2026-01-05T04:46:00.013344Z | false |
jeffpiazza/derbynet | https://github.com/jeffpiazza/derbynet/blob/07b0d7303c2d2563b7adfd8af1cabe389c114bac/website/post-timer-log.php | website/post-timer-log.php | <?php @session_start(); ?>
<?php
require_once('inc/data.inc');
session_write_close();
require_once('inc/timer-logging.inc');
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
header('Content-Type: text/xml; charset=utf-8');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$post_data = fopen('php://input', 'r');
$log_file = read_raceinfo('timer-log');
if (!$log_file) {
$log_file = set_timer_log_file();
}
$log = fopen($log_file, 'a+');
if ($log !== false) {
flock($log, LOCK_EX);
$nbytes = stream_copy_to_stream($post_data, $log);
flock($log, LOCK_UN);
fclose($log);
echo "<success>$nbytes bytes</success>\n";
} else {
echo "<failure>Can't open ".read_raceinfo('timer-log')."\n";
echo json_encode(error_get_last(), JSON_HEX_TAG | JSON_HEX_AMP | JSON_PRETTY_PRINT);
echo "</failure>\n";
// Pick a new timer log file
set_timer_log_file();
}
} else {
echo '<!DOCTYPE html><html><head><title>Not a Page</title></head><body><h1>This is not a page.</h1></body></html>';
}
?>
| php | MIT | 07b0d7303c2d2563b7adfd8af1cabe389c114bac | 2026-01-05T04:46:00.013344Z | false |
jeffpiazza/derbynet | https://github.com/jeffpiazza/derbynet/blob/07b0d7303c2d2563b7adfd8af1cabe389c114bac/website/import-results.php | website/import-results.php | <?php @session_start();
require_once('inc/data.inc');
require_once('inc/authorize.inc');
session_write_close();
require_permission(SET_UP_PERMISSION);
require_once('inc/import-csv.inc');
class ImportResults extends ImportCsvGenerator {
protected function make_encoding_section() {
?>
<div id="variations">
<div id="sheet">
</div>
</div>
<?php
} // No encodings to choose
protected function make_column_labels($labels) {
// See js/import-results.js for the interpretation on import
// See inc/export-results.inc for the columns produced by export
// See ajax/action.result.import.inc for processing on import
?>
<div class="fields hidden">
Expected fields, in order:
<table>
<tr>
<td>Group/Class</td>
<td>Round</td>
<td>Heat</td>
<td>Lane</td>
<td>FirstName</td>
<td>LastName</td>
<td>CarNumber</td>
<td>CarName</td>
<td>FinishTime</td>
<td>Scale MPH (Ignored)</td>
<td>FinishPlace</td>
<td>Completed</td>
</tr>
</table>
</div>
<?php
}
}
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Import Results</title>
<?php make_head_matter_for_import_page(); ?>
<script type="text/javascript" src="js/import-results.js"></script>
<style>
div.fields {
padding-left: 120px;
}
.fields td {
border: 2px blue solid;
}
</style>
</head>
<body>
<?php make_banner('Import Results', 'setup.php');
$page_maker = new ImportResults;
$page_maker->make_import_csv_div('Import Race Results', array());
?>
<?php
require_once('inc/ajax-pending.inc');
?>
</body>
</html>
| php | MIT | 07b0d7303c2d2563b7adfd8af1cabe389c114bac | 2026-01-05T04:46:00.013344Z | false |
jeffpiazza/derbynet | https://github.com/jeffpiazza/derbynet/blob/07b0d7303c2d2563b7adfd8af1cabe389c114bac/website/about.php | website/about.php | <?php
@session_start();
// NOTE: Loading inc/data.inc will cause a redirect to the set-up page if there's
// an issue with the database. We want to avoid that, since an important use of the
// about page is to capture diagnostic information when troubleshooting...
require_once('inc/authorize.inc');
session_write_close();
// Note that schema_version doesn't load data.inc
require_once('inc/schema_version.inc');
require_once('inc/banner.inc');
require_once('inc/locked.inc');
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>About DerbyNet</title>
<?php require('inc/stylesheet.inc'); ?>
<script type="text/javascript">
window.onload = function() {
var span = document.getElementById("useragent");
if (span) {
span.innerHTML = navigator.userAgent;
}
};
</script>
<style type="text/css">
.advert {
font-size: 18px;
border: 5px solid #023882;
background-color: #fcf0b5;
padding: 20px;
margin-bottom: 50px;
margin-left: 50px;
margin-right: 50px;
}
.ip_addr { border: 2px solid red; padding: 2px; }
.phpinfo {background-color: #ffffff; color: #000000;}
.phpinfo, .phpinfo td, .phpinfo th, .phpinfo h1, .phpinfo h2 {font-family: sans-serif;}
.phpinfo pre {margin: 0px; font-family: monospace;}
.phpinfo a:link {color: #000099; text-decoration: none; background-color: #ffffff;}
.phpinfo a:hover {text-decoration: underline;}
.phpinfo table {border-collapse: collapse;}
.phpinfo .center {text-align: center;}
.phpinfo .center table { margin-left: auto; margin-right: auto; text-align: left;}
.phpinfo .center th { text-align: center !important; }
.phpinfo td, .phpinfo th { border: 1px solid #000000; font-size: 75%; vertical-align: baseline;}
.phpinfo h1 {font-size: 150%;}
.phpinfo h2 {font-size: 125%;}
.phpinfo .p {text-align: left;}
.phpinfo .e {background-color: #ccccff; font-weight: bold; color: #000000;}
.phpinfo .h {background-color: #9999cc; font-weight: bold; color: #000000;}
.phpinfo .v {background-color: #cccccc; color: #000000;}
.phpinfo .vr {background-color: #cccccc; text-align: right; color: #000000;}
.phpinfo img {float: right; border: 0px;}
.phpinfo hr {width: 600px; background-color: #cccccc; border: 0px; height: 1px; color: #000000;}
.main-body {
margin-right: 350px;
margin-left: 20px;
}
.capture-link {
position: absolute;
top: 100px;
right: 50px;
width: 250px;
text-align: center;
background-color: #408040;
}
.capture-link p {
margin-top: 46px;
margin-bottom: 46px;
}
.capture-link a {
color: white;
}
</style>
</head>
<body>
<?php make_banner('About DerbyNet'); ?>
<div class="main-body">
<h1>About DerbyNet</h1>
<p class='advert'><b>DerbyNet</b> is the free, open-source, multi-screen race management system for Pinewood Derby-style racing. It's used by packs and other groups all around the country, and around the globe!
Check us out <a href="http://jeffpiazza.github.io/derbynet/" target="_blank">on GitHub!</a></p>
<?php
$urls = preferred_urls();
if (count($urls) == 0 || empty($urls[0])) {
echo "<p>The local IP address for this server can't be determined.</p>\n";
} else {
echo '<p>It looks like you can use ';
for ($i = 0; $i < count($urls); ++$i) {
if ($i > 0) {
echo ' or ';
}
echo "<span class='ip_addr'>".$urls[$i]."</span>";
}
echo " as the URL for connecting other local devices to this server.</p>\n";
}
?>
<p>Please include this page if you wish to report a bug, and
contact me at <a href="mailto:bugs@derbynet.org">bugs@derbynet.org</a>.</p>
<p>Your browser's User Agent string is<br/><span id="useragent"></span>.</p>
<p>Your browser supports javascript version <span id="jsver">unspecified</span>.</p>
<h4>DerbyNet Revision</h4>
<?php
$version = @file_get_contents('inc/generated-version.inc');
$build_date = @file_get_contents('inc/generated-build-date.inc');
$git_hash = @file_get_contents('inc/generated-commit-hash.inc');
if ($version === false) {
echo "<p>No version found.</p>\n";
} else {
echo "<p>This is revision <b>".$version."</b>, built on ".$build_date.".<br/>\n";
echo "(".$git_hash.")</p>\n";
}
?>
<?php
$failed = false;
set_error_handler(function() { global $failed; $failed = true; }, E_WARNING);
date_default_timezone_get();
restore_error_handler();
if ($failed) {
echo "<h3>Time zone not set!</h3>\n";
echo "<p>You need to set the date.timezone setting in the php.ini file!</p>\n";
}
?>
<h4>Database Configuration</h4>
<?php
$configdir = isset($_SERVER['DERBYNET_CONFIG_DIR']) ? $_SERVER['DERBYNET_CONFIG_DIR'] : 'local';
if (have_permission(SET_UP_PERMISSION)) {
$config_content = @file_get_contents($configdir.DIRECTORY_SEPARATOR.'config-database.inc',
/* use_include_path */ true);
if ($config_content === false) {
echo '<p>Database configuration file, '.
htmlspecialchars($configdir.DIRECTORY_SEPARATOR.'config-database.inc',
ENT_QUOTES, 'UTF-8').
', could not be opened.'.
'</p>'."\n";
} else {
echo "<pre>\n";
echo htmlspecialchars($config_content, ENT_QUOTES, 'UTF-8');
echo "</pre>\n";
}
} else {
echo "<p>Database configuration information is available if you are logged in.</p>\n";
}
?>
<?php
// Try setting up the database, but it's OK if it doesn't work out
try {
@include($configdir.DIRECTORY_SEPARATOR."config-database.inc");
} catch (PDOException $p) {
}
if (isset($db)) {
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "<h4>Database Schema</h4>\n";
try {
// Can't use schema_version(), because it depends on functions from data.inc
$rs = $db->prepare('SELECT itemvalue FROM RaceInfo WHERE itemkey = :key');
$rs->execute(array(':key' => 'schema'));
$row = $rs->fetch(PDO::FETCH_NUM);
$rs->closeCursor();
$schema_version = $row === false ? false : $row[0];
echo '<p>Schema version '.$schema_version.' (expecting version '.expected_schema_version().')</p>'."\n";
if (have_permission(SET_UP_PERMISSION)) {
echo "<div class='capture-link'>"
."<p class=''>Download Database Snapshot:<br/>"
."<a download='derbynet-".date('Ymd-His').".xml'"
." href='action.php?query=snapshot.get'>Complete</a>"
."<br/>or<br/>"
."<a download='derbynet-".date('Ymd-His').".xml'"
." href='action.php?query=snapshot.get&clean'>Cleaned</a>"
."</p>"
."<p style='border-top: 1px solid white; padding: 26px; margin-bottom: 0px;'>"
."Download<br/><a download='derbynet.pref'"
." href='preferences.php'>Preferences</a>"
."</p></div>\n";
}
} catch (PDOException $p) {
echo '<p>Can\'t determine schema version (expecting version '.expected_schema_version().')</p>'."\n";
}
}
?>
<?php
if (isset($db)) {
function read_single_row($sql, $params = array(), $fetch = PDO::FETCH_NUM) {
global $db;
$rs = $db->prepare($sql);
$rs->execute($params);
$row = $rs->fetch($fetch);
$rs->closeCursor();
return $row;
}
function read_single_value($sql, $params = array(), $def = false) {
$row = read_single_row($sql, $params);
if ($row === false || $row[0] === null) {
return $def;
}
return $row[0];
}
function read_raceinfo($key, $def = false) {
return read_single_value('SELECT itemvalue FROM RaceInfo WHERE itemkey = :key',
array(':key' => $key), $def);
}
$timer = read_raceinfo('timer-type');
if ($timer) {
echo "<h4>Timer</h4>\n";
echo "<p>";
echo htmlspecialchars($timer, ENT_QUOTES, 'UTF-8');
$timer_human = read_raceinfo('timer-humant');
if ($timer_human) {
echo " $timer_human";
}
$timer_ident = read_raceinfo('timer-ident');
if ($timer_ident) {
echo " ($timer_ident)";
}
echo "</p>\n";
}
}
?>
<h4>PHP Configuration Information</h4>
</div>
<div class="phpinfo">
<?php
ob_start();
@phpinfo();
$buf = ob_get_clean();
$start = strpos($buf, '<body>') + 6;
$stop = strpos($buf, '</body>');
echo substr($buf, $start, $stop - $start);
?>
</div>
</body>
<script type="text/javascript">
document.getElementById("jsver").textContent = "1.0";
</script>
<script language="Javascript1.1">
document.getElementById("jsver").textContent = "1.1";
</script>
<script language="Javascript1.2">
document.getElementById("jsver").textContent = "1.2";
</script>
<script language="Javascript1.3">
document.getElementById("jsver").textContent = "1.3";
</script>
<script language="Javascript1.4">
document.getElementById("jsver").textContent = "1.4";
</script>
<script language="Javascript1.5">
document.getElementById("jsver").textContent = "1.5";
</script>
<script language="Javascript1.6">
document.getElementById("jsver").textContent = "1.6";
</script>
<script language="Javascript1.7">
document.getElementById("jsver").textContent = "1.7";
</script>
<script language="Javascript1.8">
document.getElementById("jsver").textContent = "1.8";
</script>
<script language="Javascript1.9">
document.getElementById("jsver").textContent = "1.9";
</script>
</html>
| php | MIT | 07b0d7303c2d2563b7adfd8af1cabe389c114bac | 2026-01-05T04:46:00.013344Z | false |
jeffpiazza/derbynet | https://github.com/jeffpiazza/derbynet/blob/07b0d7303c2d2563b7adfd8af1cabe389c114bac/website/fullscreen.php | website/fullscreen.php | <!DOCTYPE html>
<html>
<head>
<title>Fullscreen Kiosk</title>
<?php
require('inc/stylesheet.inc');
require('inc/servername.inc');
?>
<style type="text/css">
.full-window {
position: absolute;
top: 0;
height: 100%;
left: 0;
width: 100%;
border: none;
}
#setup {
margin-top: 100px;
}
</style>
<?php
$server = server_name();
$path = request_path();
$url = $server . $path;
$last = strrpos($url, '/');
if ($last === false) {
$last = -1;
}
// Don't force http !
$kiosk_url = '//'.substr($url, 0, $last + 1).'kiosk.php';
?>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/screenfull.min.js"></script>
<script type="text/javascript">
function on_proceed() {
$("#interior").attr('src', $("#inner_url").val());
$("#setup").addClass('hidden');
$("#interior").removeClass('hidden');
if (screenfull.enabled) {
screenfull.request();
}
}
</script>
</head>
<body>
<iframe id="interior" class="hidden full-window">
</iframe>
<div id="setup" class ="full-window block_buttons">
<label for="inner_url">URL:</label>
<input type="text" name="inner_url" id="inner_url" size="100"
value="<?php echo htmlspecialchars($kiosk_url, ENT_QUOTES, 'UTF-8'); ?>"/>
<input type="button" value="Proceed"
onclick="on_proceed();"/>
</div>
</body>
</html> | php | MIT | 07b0d7303c2d2563b7adfd8af1cabe389c114bac | 2026-01-05T04:46:00.013344Z | false |
jeffpiazza/derbynet | https://github.com/jeffpiazza/derbynet/blob/07b0d7303c2d2563b7adfd8af1cabe389c114bac/website/history.php | website/history.php | <?php @session_start(); ?>
<?php
require_once('inc/data.inc');
require_once('inc/authorize.inc');
session_write_close();
require_once('inc/banner.inc');
require_once('inc/schema_version.inc');
require_once('inc/events.inc');
require_once('inc/lane-bias.inc');
require_once('inc/history-formatter.inc');
if (isset($_GET['debug'])) {
$debug_history_entries = true;
}
require_permission(CHECK_IN_RACERS_PERMISSION);
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Race History</title>
<?php require('inc/stylesheet.inc'); ?>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function() {
$("#lane-bias").on('click', function() {
let details = $("#lane-bias-details");
if (details.css("display") == "none") {
// Opening
$("#lane-bias-triangle").attr('src', 'img/triangle_south.png');
details.slideDown(200);
} else {
// Closing
$("#lane-bias-triangle").attr('src', 'img/triangle_east.png');
details.slideUp(200);
}
});
});
</script>
<style type="text/css">
div.content {
margin-left: 50px;
}
table.event-history {
}
table.event-history tr.event td {
padding-top: 6px;
padding-bottom: 6px;
}
table.event-history tr.event-identifier td {
border-top-width: 2px;
}
table.event-history tr.event-explanation td {
border-bottom-width: 2px;
}
table.event-history tr.event.irregular td {
background: #ffdddd;
}
table.event-history tr.event-explanation.discarded-event td {
text-align: left;
}
table.event-history tr.event-explanation.first td {
border-bottom-width: 0px;
}
table.event-history tr.event-explanation.follow-on td {
border-top-width: 0px;
}
/* first, follow-on */
table.event-history tr.event td:first-child {
border-left-width: 2px;
}
table.event-history tr.event td:last-child {
border-right-width: 2px;
}
#lane-bias-details {
display: none;
}
</style>
</head>
<body>
<?php
make_banner('Retrospective');
$bias = lane_bias_analysis();
?>
<div class="content">
<h3>Lane Bias Analysis</h3>
<div id="lane-bias">
<?php
if (empty($bias)) {
echo "<p>There isn't enough evidence to assess lane bias.</p>";
} else {
?>
<p id="lane-bias-summary">
<img id="lane-bias-triangle" src="img/triangle_east.png"/>
<?php
if ($bias['biased']) {
echo "<b style='color: red;'>The track lanes appear to be biased, with 90% confidence.</b>";
} else {
echo "There is no evidence of significant lane bias.";
}
?>
</p>
<div id="lane-bias-details">
<table><?php lane_bias_analysis(true); ?></table>
<?php
echo "<p>F statistic is ".sprintf("%5.3f", $bias['f-statistic'])." with df1=".$bias['df1']." and df2=".$bias['df2']."</p>\n";
echo "<p>Critical value for F statistic is ".sprintf("%5.3f", $bias['critical-value'])."</p>\n";
?>
</div>
<?php } ?>
</div>
<p> </p>
<h3>Events Timeline</h3>
<table class="event-history">
<?php
if (schema_version() < PER_SUBGROUP_AWARDS_SCHEMA) {
require('inc/old-history.inc');
} else {
$formatter = new HistoryActionFormatter;
$history = $db->prepare('SELECT * FROM ActionHistory ORDER BY received');
$history->execute();
foreach ($history as $action) {
$formatter->SetAction($action['request']);
$curr_heat = $formatter->CurrentHeatString();
$step = $formatter->Process();
if (!empty($step)) {
$irregular = '';
echo "<tr class='event $irregular event-identifier'>";
echo "<td>";
echo $curr_heat;
echo "</td>";
echo "<td>".$action['received']."</td>";
echo "<td>"./* turnaround time */"</td>";
echo "</tr>\n";
echo "<tr class='event $irregular event-explanation'><td colspan='3'>$step</td>";
echo "</tr>\n";
}
}
}
?>
</table>
</div> <!-- content -->
</body>
</html>
| php | MIT | 07b0d7303c2d2563b7adfd8af1cabe389c114bac | 2026-01-05T04:46:00.013344Z | false |
jeffpiazza/derbynet | https://github.com/jeffpiazza/derbynet/blob/07b0d7303c2d2563b7adfd8af1cabe389c114bac/website/coordinator.php | website/coordinator.php | <?php session_start(); ?>
<?php
require_once('inc/data.inc');
require_once('inc/authorize.inc');
session_write_close();
require_once('inc/banner.inc');
require_once('inc/partitions.inc');
require_permission(SET_UP_PERMISSION); // TODO: What's the correct permission?
$warn_no_timer = warn_no_timer();
?><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title>Race Coordinator Page</title>
<link rel="stylesheet" type="text/css" href="css/jquery-ui.min.css"/>
<?php require('inc/stylesheet.inc'); ?>
<link rel="stylesheet" type="text/css" href="css/mobile.css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/ajax-setup.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/coordinator.css"/>
<script type="text/javascript" src="js/mobile.js"></script>
<script type="text/javascript" src="js/dashboard-ajax.js"></script>
<script type="text/javascript" src="js/modal.js"></script>
<script type="text/javascript" src="js/coordinator-controls.js"></script>
<script type="text/javascript" src="js/coordinator-poll.js"></script>
<script type="text/javascript" src="js/timer-alive.js"></script>
<script type="text/javascript">
var g_use_subgroups = <?php echo use_subgroups() ? "true" : "false"; ?>;
$(function() {
$("#replay-skipback option[value='<?php
echo read_raceinfo('replay-skipback', '3000'); ?>']").attr('selected', 'selected');
mobile_select_refresh('#replay-skipback');
$("#replay-num-showings option[value='<?php
echo read_raceinfo('replay-num-showings', '2'); ?>']").attr('selected', 'selected');
mobile_select_refresh('#replay-num-showings');
$("#replay-rate option[value='<?php
echo read_raceinfo('replay-rate', '50'); ?>']").attr('selected', 'selected');
mobile_select_refresh('#replay-rate');
});
</script>
<style>
input[type=number].lane-time {
-moz-appearance: textfield;
width: 105px;
}
input.lane-time::-webkit-inner-spin-button {
-webkit-appearance: none;
}
input.lane-time::-webkit-outer-spin-button {
-webkit-appearance: none;
margin: 0;
}
</style>
</head>
<body>
<?php make_banner('Race Dashboard'); ?>
<div class="double_control_column">
<div id="not-racing-warning" class="hidden">
Turn on racing mode or <a target='_blank' href='timer-test.php'>simulate racing</a>
if you wish to record results.
</div>
<div id="now-racing-group" class="scheduling_control_group">
<p>Waiting for poll.coordinator query...</p>
</div>
<div id="notifications" class="hidden">
<img src="img/cancel-20.png" onclick="clear_notifications()"/>
</div>
</div>
<div class="control_column_container">
<div class="control_column">
<div class="control_group heat_control_group">
<div id="start_race_button_div" class="block_buttons hidden">
<input type="button" value="Start Race" onclick="handle_start_race_button()"/>
</div>
<div class="centered_flipswitch">
<input type="checkbox" class="flipswitch" name="is-currently-racing" id="is-currently-racing"
checked="checked"
data-on-text="Racing" data-off-text="Not Racing"/>
</div>
<div class="block_buttons">
<div id="prev_heat_button" class="button_link" onclick="handle_previous_heat_button()">
<img src="img/left-white-60.png"/>
</div>
<input type="button" id="manual_results_button" value="Manual Results"
onclick="on_manual_results_button_click(<?php echo !$warn_no_timer ? "true" : "false"; ?>)" />
<div id="skip_heat_button" class="button_link" onclick="handle_skip_heat_button()">
<img src="img/right-white-60.png"/>
</div>
<input type="button" id="rerun-button" value="Re-Run"
data-rerun="none"
onclick="handle_rerun(this);"/>
</div>
</div>
<div id="supplemental-control-group" class="control_group block_buttons new_round_control hidden">
<div id="now-racing-group-buttons"></div>
<div id="add-new-rounds-button" class="hidden">
<input type="button" value="Add New Rounds"
onclick="show_choose_new_round_modal()"/>
</div>
</div>
<div class="control_group timer_control_group">
<?php if (!$warn_no_timer) { ?>
<p>Not monitoring timer state</p>
<?php } else { ?>
<div class="status_icon">
<img id="timer_status_icon" src="img/status/unknown.png"/>
</div>
<div id='timer-test' class="block_buttons">
<a class="button_link" onclick="open_timer_window();">Timer</a>
<a class='button_link' href='timer-test.php'>Test</a>
</div>
<h3>Timer Status</h3>
<p><b id="timer_status_text">Timer status not yet updated</b></p>
<p>The track has <span id="lane_count">an unknown number of</span> lane(s).</p>
<?php } ?>
</div>
<div class="control_group replay_control_group">
<div class="status_icon">
<img id="replay_status_icon" src="img/status/unknown.png"/>
</div>
<h3>Replay Status</h3>
<p><b id="replay_status">Remote replay status not yet updated</b></p>
<div id="test_replay" class="block_buttons">
<input type="button" value="Trigger Replay" onclick="handle_test_replay();"/>
</div>
<div class="block_buttons">
<input type="button" value="Replay Settings" onclick="show_replay_settings_modal();"/>
</div>
</div>
</div>
<div class="control_column">
<div id="playlist-group" class="block_buttons">
<a class='button_link' href='playlist.php'>Rounds Playlist</a>
<div id="playlist-start">
<input type="button" value="Start Playlist" onclick="handle_start_playlist();"/>
</div>
</div>
<div id="master-schedule-group" class="master_schedule_group"></div>
<div id="ready-to-race-group" class="scheduling_control_group"></div>
<div id="not-yet-scheduled-group" class="scheduling_control_group"></div>
<div id="done-racing-group" class="scheduling_control_group"></div>
</div>
</div>
<?php require_once('inc/ajax-failure.inc'); ?>
<div id='schedule_modal' class="modal_dialog hidden block_buttons">
<form>
<p>How many times should each racer appear in each lane?</p>
<select id="schedule_num_rounds">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
</select>
<input id="schedule-and-race"
type="submit" value="Schedule + Race"
data-race="true" onclick='mark_clicked($(this));'/>
<input id="schedule-only"
type="submit" value="Schedule Only"
data-race="false" onclick='mark_clicked($(this));'/>
<input type="button" value="Cancel"
onclick='close_modal("#schedule_modal");'/>
</form>
</div>
<div id='manual_results_modal' class="modal_dialog hidden block_buttons">
<form>
<input type="hidden" name="action" value="result.write"/>
<table></table>
<input type="button"
id="discard-results"
onclick='handle_discard_results_button();'
value="Discard Results"/>
<input type="submit" value="Change"/>
<input type="button" value="Cancel"
onclick='close_modal("#manual_results_modal");'/>
</form>
</div>
<div id='replay_settings_modal' class="modal_dialog hidden block_buttons">
<form>
<input type="hidden" name="action" value="settings.write"/>
<label for="replay-skipback">Duration of replay, in seconds:</label>
<!-- Value in milliseconds, must match as a string -->
<select id="replay-skipback" name="replay-skipback">
<!-- <option value="2000">2.0</option> -->
<option value="2500">2.5</option>
<option value="3000">3.0</option>
<option value="3500">3.5</option>
<option value="4000">4.0</option>
<option value="4500">4.5</option>
<option value="5000">5.0</option>
<!-- <option value="5500">5.5</option> -->
<option value="6000">6.0</option>
<!-- <option value="6500">6.5</option> -->
</select>
<label for="replay-num-showings">Number of times to show replay:</label>
<!-- Could be any positive integer -->
<select id="replay-num-showings" name="replay-num-showings">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<label for="replay_rate">Replay playback speed:</label>
<!-- Expressed as a percentage -->
<select id="replay-rate" name="replay-rate">
<option value="10">0.1x</option>
<option value="25">0.25x</option>
<option value="50">0.5x</option>
<option value="75">0.75x</option>
<option value="100">1x</option>
</select>
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"
onclick='close_modal("#replay_settings_modal");'/>
</form>
</div>
<div id='choose_new_round_modal' class="modal_dialog block_buttons hidden">
<!-- Populated by script: see offer_new_rounds() -->
</div>
<div id='new-round-modal' class="modal_dialog wide_modal block_buttons hidden">
<form>
<div id='aggregate-by-div' class='aggregate-only for-choosing-constituents'>
<label for='aggregate-by-checkbox'>Aggregate by </label>
<input id='aggregate-by-checkbox' type='checkbox' class='flipswitch'
onchange='on_aggregate_by_change()'
data-off-text="<?php echo group_label();?>"
data-on-text="<?php echo subgroup_label();?>"/>
</div>
<div id="new-round-common">
<div>
<label for='new-round-top'>Choose top </label>
<input id='new-round-top' type='number' name="top" value="3" class='not-mobile'/>
<span id="new-round-top-racers" class='hidden follow-on-only'> racers</span>
</div>
<div id='bucketed-div'>
<label for='bucketed-checkbox'>racers from </label>
<input id='bucketed-checkbox' type='checkbox' class='flipswitch' name="bucketed"
data-group-text="Each <?php echo group_label(); ?>"
data-subgroup-text="Each <?php echo subgroup_label(); ?>"
data-on-text="Each <?php echo subgroup_label(); ?>"
data-off-text="Overall"/>
</div>
</div>
<div id='agg-classname-div' class='aggregate-only'>
<label for='agg-classname'>Name for new round:</label>
<input id='agg-classname' type='text' name="classname" value="Grand Finals"/>
</div>
<div id='constituent-clip' class='aggregate-only for-choosing-constituents'>
<div id='constituent-div'>
<div id='constituent-rounds'></div>
<div id='constituent-subgroups'></div>
</div>
</div>
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"
onclick='g_new_round_modal_open = false; close_modal("#new-round-modal");'/>
</form>
</div>
<div id='unschedule_modal' class="modal_dialog hidden block_buttons">
<p>Round <span id="unschedule_round"></span> for <span id="unschedule_class"></span>
has a schedule, but no heats have been run. If you want to add or remove racers,
you need to delete the schedule for this round. Is that what you would like to do?</p>
<form>
<input type="submit" value="Unschedule"/>
<input type="button" value="Cancel"
onclick='close_modal("#unschedule_modal");'/>
</form>
</div>
<div id="purge_modal" class="modal_dialog wide_modal block_buttons hidden">
<div id="purge_modal_inner">
<form>
<h3><span id="purge_round_name"></span> Round <span id="purge_round_no"></span></h3>
<p>This round has <span id="purge_results_count"></span> heat(s) with results.</p>
<input type="submit" value="Purge Results"/>
<p> </p>
<input type="button" value="Cancel"
onclick='close_modal("#purge_modal");'/>
</form>
</div>
</div>
<div id="purge_confirmation_modal" class="modal_dialog block_buttons hidden">
<form>
<p>You are about to purge all the race results for this round.
This operation cannot be undone.
Are you sure that's what you want to do?</p>
<input type="submit" value="Purge Results"/>
<p> </p>
<input type="button" value="Cancel"
onclick='close_secondary_modal("#purge_confirmation_modal");'/>
</form>
</div>
<div id='delete_round_modal' class="modal_dialog hidden block_buttons">
<p>Round <span id="delete_round_round"></span> for <span id="delete_round_class"></span>
has no schedule, and no heats have been run. To choose different racers for this round,
you need to delete this round and generate a new one. Is that what you would like to do?</p>
<form>
<input type="submit" value="Delete Round"/>
<input type="button" value="Cancel"
onclick='close_modal("#delete_round_modal");'/>
</form>
</div>
</body>
</html>
| php | MIT | 07b0d7303c2d2563b7adfd8af1cabe389c114bac | 2026-01-05T04:46:00.013344Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.