Page MenuHomeDevCentral

No OneTemporary

diff --git a/css/media-queries-generator.php b/css/media-queries-generator.php
index 7d51f17..2c68ec5 100644
--- a/css/media-queries-generator.php
+++ b/css/media-queries-generator.php
@@ -1,117 +1,117 @@
<?php
- $widths = array_key_exists('widths', $_REQUEST) ? $_REQUEST['widths'] : '400, 720, 1280, 1440, 1920, 2880';
+ $widths = $_REQUEST['widths'] ?? '400, 720, 1280, 1440, 1920, 2880';
?>
<form name="media-queries-generator" class="custom">
<div class="row collapse">
<div class="one mobile-one columns">
<span class="prefix">Widths</span>
</div>
<div class="ten mobile-six columns">
<input
name="widths" id="widths" type="text"
placeholder="The widths you want to target, separated by comma"
value="<?= $widths ?>"
onClick="BuildCSS();"
/>
<?php if (isset($regexp) && $regexp->lastError) echo '<small class="error" style="font-weight: 400;">', $regexp->lastError, '</small>'; ?>
</div>
<div class="one mobile-one columns">
<input type="button" class="button expand postfix" value="Generate" />
</div>
</div>
<div class="row collapse">
<div class="one mobile-one columns">
<span class="prefix">Indent</span>
</div>
<div class="one mobile-one columns">
<input name="indentcount" id="indentcount" type="number" min="0" value="4">
</div>
<div class="ten mobile-six columns">
<select name="indenttype" id="indenttype">
<option value="tab">Tabs</option>
<option value="space" selected>Spaces</option>
</select>
</div>
</div>
<div class="row collapse">
<div class="six columns">
- <textarea name="css" id="css" rows="16" style="width: 99%;" placeholder="The CSS content" onChange="BuildCSS();"><?= $_REQUEST['css'] ?></textarea>
+ <textarea name="css" id="css" rows="16" style="width: 99%;" placeholder="The CSS content" onChange="BuildCSS();"><?= $_REQUEST['css'] ?? "" ?></textarea>
</div>
<div class="six columns">
- <textarea name="result" id="result" rows="16" style="width: 99%;" placeholder="The final CSS will appear here."><?= $result ?></textarea>
+ <textarea name="result" id="result" rows="16" style="width: 99%;" placeholder="The final CSS will appear here."></textarea>
</div>
</div>
<div class="row">
<div class="twelve columns">
<p><strong>Note:</strong> Use <strong>%width%</strong> in your CSS to generate code to substitude the current breakpoint width.</p>
</div>
</div>
</form>
<script>
/**
* Build CSS
*/
function BuildCSS () {
widths = document.getElementById('widths').value.split(', ').map(function(s) { return s.trim() });
document.getElementById('result').value = GetMediaQueriesCSS(
widths,
document.getElementById('css').value,
parseInt(document.getElementById('indentcount').value),
document.getElementById('indenttype').value == 'space'
);
}
function GetMediaQueriesCSS(widths, cssContent, indentAmout, useSpaceForIndent) {
var css = '';
for (var i = 0 ; i < widths.length ; i++) {
if (i == 0) {
css += "@media screen and (max-width: " + widths[0] + "px) {";
} else if (i == widths.length - 1) {
css += "@media screen and (min-width: " + (parseInt(widths[i-1]) + 1) + "px) {";
} else {
css += "@media screen and (min-width: " + (parseInt(widths[i-1]) + 1) + "px) and (max-width: " + widths[i] + "px) {";
}
css += '\n';
css += Indent(cssContent.replace(/%width%/g, widths[i]), indentAmout, useSpaceForIndent);
css += '\n}';
if (i < widths.length - 1) {
css += '\n\n';
}
}
return css;
}
/**
* Repeats the current string a specified number of times
*
* @param int count The number of times to repeat thestring
* @return The repeated string
*/
String.prototype.repeat = function (count) {
// Code by artistoex and pimvdb - http://jsfiddle.net/disfated/GejWV/
if (count < 1) {
return '';
}
var result = '';
var pattern = this.valueOf();
while (count > 0) {
if (count & 1) {
result += pattern;
}
count >>= 1;
pattern += pattern;
}
return result;
};
function Indent (code, amount, useSpace) {
return code.split('\n').map(
function(s) {
c = useSpace ? ' ' : '\t';
return c.repeat(amount) + s;
}
).join('\n');
}
BuildCSS();
</script>
diff --git a/finger/index.php b/finger/index.php
index f1a74c0..4eddd9e 100644
--- a/finger/index.php
+++ b/finger/index.php
@@ -1,28 +1,28 @@
<?php
if (array_key_exists('user', $_REQUEST)) {
require_once('FingerClient.php');
$client = FingerClient::FromAddress($_REQUEST['user']);
if ($client == null) {
echo '<div class="alert-box alert">Invalid Finger address format.</div>';
} elseif (!$client->Run()) {
echo '<div class="alert-box alert">', $client->lastError, '</div>';
unset($client);
}
}
?>
<h2>Who?</h2>
<form>
<div class="row collapse">
<div class="ten mobile-three columns">
- <input type="text" name="user" id="user" value="<?= $_REQUEST['user'] ?>" placeholder="username@server" />
+ <input type="text" name="user" id="user" value="<?= $_REQUEST['user'] ?? "" ?>" placeholder="username@server" />
</div>
<div class="two mobile-one columns">
<input type="submit" class="button expand postfix" value="Finger" />
</div>
</div>
</form>
<?php
if (isset($client) && $client->rawResult) {
echo "<h2>Finger $_REQUEST[user]</h2>";
echo '<pre id="finger">', $client->rawResult, '</pre>';
}
diff --git a/finger/thimbl_inputForm.html b/finger/thimbl_inputForm.html
index fecd169..1245054 100644
--- a/finger/thimbl_inputForm.html
+++ b/finger/thimbl_inputForm.html
@@ -1,11 +1,11 @@
<h2>Who?</h2>
<form>
<div class="row collapse">
<div class="ten mobile-three columns">
- <input type="text" name="user" id="user" value="<?= $_REQUEST['user'] ?>" placeholder="username@server" />
+ <input type="text" name="user" id="user" value="<?= $_REQUEST['user'] ?? "" ?>" placeholder="username@server" />
</div>
<div class="two mobile-one columns">
<input type="submit" class="button expand postfix" value="Finger" />
</div>
</div>
</form>
diff --git a/gadgets/motd-variations.php b/gadgets/motd-variations.php
index fbc482b..104ed0c 100644
--- a/gadgets/motd-variations.php
+++ b/gadgets/motd-variations.php
@@ -1,23 +1,23 @@
<!-- Actions -->
<div id="action-icons">
<a href="" title="Refresh this page">
<i class="general foundicon-refresh"></i>
</a>
</div>
<!-- Content -->
<?php
- $fortune = rtrim(`/usr/games/fortune`);
+ $fortune = rtrim(`/usr/bin/fortune`);
echo " <h3>English text</h3>\n";
echo " <p>$fortune</p>\n\n";
$variants = [
'jive',
'valspeak',
];
foreach ($variants as $variant) {
echo " <h3>English variant — $variant</h3>\n";
$text = escapeshellarg($fortune);
echo " <p>", rtrim(`echo $text | $variant`), "</p>\n\n";
}
diff --git a/includes/core.php b/includes/core.php
index 246e748..f0c1ce6 100644
--- a/includes/core.php
+++ b/includes/core.php
@@ -1,400 +1,400 @@
<?php
/*
* Keruald, core libraries for Pluton and Xen engines.
* (c) 2010, Sébastien Santoro aka Dereckson, some rights reserved
* Released under BSD license
*
* Core
*
* 0.1 2010-02-27 2:04 DcK
*/
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Configures PHP and loads site-wide used libraries ///
/// ///
////////////////////////////////////////////////////////////////////////////////
//Disables register globals
ini_set('register_globals', 'off');
//Reports all errors, help notices (including STRICT in PHP 6)
error_reporting(E_ALL & ~E_NOTICE);
//Load config
require_once("default-config.php");
if (file_exists("config.php")) {
include_once("config.php");
}
//Load libraries
include_once("error.php"); //Error management
include_once("mysqli.php"); //MySQL layer
include_once("session.php"); //Sessions handler
include_once("autoload.php"); //Autoloader
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Information helper functions ///
/// ///
////////////////////////////////////////////////////////////////////////////////
/*
* Gets the username matching specified user id
* @param string $user_id the user ID
* @return string the username
*/
function get_username ($user_id) {
$db = sql_db::load();
$user_id = $db->sql_escape($user_id);
$sql = 'SELECT username FROM '. TABLE_USERS . " WHERE user_id = '$userid'";
return $db->sql_query_express($sql, "Can't get username from specified user id");
}
/*
* Gets the user id matching specified username
* @param string $username the username
* @return string the user ID
*/
function get_userid ($username) {
$db = sql_db::load();
$username = $db->sql_escape($username);
$sql = 'SELECT user_id FROM '. TABLE_USERS . " WHERE username LIKE '$username'";
return $db->sql_query_express($sql, "Can't get user id from specified username");
}
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Misc helper functions ///
/// ///
////////////////////////////////////////////////////////////////////////////////
//Plural management
/*
* Gets a "s" if the specified amount requests the plural
* @param mixed $amount the quantity (should be numeric)
* @return string 's' if the amount is greater or equal than 2 ; otherwise, ''
*/
function s ($amount) {
if ($amount >= 2 || $amount <= -2 ) return 's';
}
/*
* Prints human-readable information about a variable, wrapped in a <pre> block
* @param mixed $mixed the variable to dump
*/
function dprint_r ($mixed) {
echo '<pre>';
print_r($mixed);
echo '</pre>';
}
/*
* Generates a new GUID
* @return string a guid (without {})
*/
function new_guid () {
//The guid chars
$chars = explode(',', 'a,b,c,d,e,f,0,1,2,3,4,5,6,7,8,9');
//Let's build our 36 characters string
//e.g. 68ed40c6-f5bb-4a4a-8659-3adf23536b75
$guid = "";
for ($i = 0 ; $i < 36 ; $i++) {
if ($i == 8 || $i == 13 || $i == 18 || $i == 23) {
//Dashes at position 9, 14, 19 and 24
$guid .= "-";
} else {
//0-f hex digit elsewhere
$guid .= $chars[mt_rand() % sizeof($characters)];
}
}
return $guid;
}
/*
* Determines if the expression is a valid guid (in uuid notation, without {})
* @param string $expression the guid to check
* @return true if the expression is a valid guid ; otherwise, false
*/
function is_guid ($expression) {
//We avoid regexp to speed up the check
//A guid is a 36 characters string
if (strlen($expression) != 36) return false;
$expression = strtolower($expression);
for ($i = 0 ; $i < 36 ; $i++) {
if ($i == 8 || $i == 13 || $i == 18 || $i == 23) {
//with dashes
if ($expression[$i] != '-') return false;
} else {
//and hex numbers
if (!is_numeric($expression[$i]) && $expression[$i] != 'a' && $expression[$i] != 'b' && $expression[$i] != 'c' && $expression[$i] != 'd' && $expression[$i] != 'e' && $expression[$i] != 'f' ) return false;
}
}
return true;
}
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Files, extensions and directories ///
/// ///
////////////////////////////////////////////////////////////////////////////////
/**
* Gets files in a directory
*
* @param string $dir The directory files are located (optional, by default the current directory)
* @param string $extension The extension to lookup without initial dot (optional, return every file if omitted)
* @return array the files in the specified directory optionally filtered by extension
*/
function get_files ($dir = '.', $extension = NULL) {
$handle = opendir($dir);
$files = [];
while ($file = readdir($handle)) {
if ($file == '.' || $file == '..' || is_dir($file)) {
continue;
}
if ($extension === NULL || get_extension($file) == $extension) {
$files[] = $file;
}
}
return $files;
}
/**
* Gets file extension
*
* @param string $file the file to get the extension
*/
function get_extension ($file) {
return pathinfo($file, PATHINFO_EXTENSION);
}
////////////////////////////////////////////////////////////////////////////////
/// ///
/// Strings manipulation ///
/// ///
////////////////////////////////////////////////////////////////////////////////
/**
* Determines if a string starts with specified substring
*
* @param string $haystack the string to check
* @param string $needle the substring to determines if it's the start
* @param boolean $case_sensitive determines if the search must be case sensitive
* @return boolean true if $haystack starts with $needle ; otherwise, false.
*/
function string_starts_with ($haystack, $needle, $case_sensitive = true) {
if (!$case_sensitive) {
$haystack = strtoupper($haystack);
$needle = strtoupper($needle);
}
if ($haystack == $needle) return true;
return strpos($haystack, $needle) === 0;
}
/**
* Gets the portion of the string between $includeFrom and $includeTo
*/
function string_between ($haystack, $from, $to, $includeFrom = false, $includeTo = false) {
//Gets start position
$pos1 = strpos($haystack, $from);
if ($pos1 === false) {
return "";
}
if (!$includeFrom) $pos1 += strlen($from);
//Gets end position
$pos2 = strpos($haystack, $to, $pos1 + strlen($from));
if ($pos2 === false) {
return substr($haystack, $pos1);
}
if ($includeTo) $pos2 += strlen($to);
//Gets middle part
return substr($haystack, $pos1, $pos2 - $pos1);
}
////////////////////////////////////////////////////////////////////////////////
/// ///
/// URL helpers functions ///
/// ///
////////////////////////////////////////////////////////////////////////////////
/*
* Gets URL
* @return string URL
*/
function get_url () {
global $Config;
if (func_num_args() > 0) {
$pieces = func_get_args();
return $Config['BaseURL'] . '/' . implode('/', $pieces);
} elseif ($Config['BaseURL'] == "" || $Config['BaseURL'] == "/index.php") {
return "/";
} else {
return $Config['BaseURL'];
}
}
/*
* Gets page URL
* @return string URL
*/
function get_page_url () {
$url = $_SERVER['SCRIPT_NAME'] . $_SERVER['PATH_INFO'];
if (substr($url, -10) == "/index.php") {
return substr($url, 0, -9);
}
return $url;
}
/*
* Gets server URL
* @todo find a way to detect https:// on non standard port
* @return string the server URL
*/
function get_server_url () {
- if (isset($_SERVER['HTTP_HOST'])) {
+ if (isset($_SERVER['HTTP_HOST']) && str_contains($_SERVER['HTTP_HOST'], ":")) {
list($name, $port) = explode(':', $_SERVER['HTTP_HOST'], 2);
} else {
$port = $_SERVER['SERVER_PORT'];
$name = $_SERVER['SERVER_NAME'];
}
switch ($port) {
case '80':
return "http://$name";
case '443':
return "https://$name";
default:
return "http://$name:$port";
}
}
/*
* Gets $_SERVER['PATH_INFO'] or computes the equivalent if not defined.
* @return string the relevant URL part
*/
function get_current_url () {
global $Config;
//Gets relevant URL part from relevant $_SERVER variables
if (!empty($_SERVER['PATH_INFO'])) {
//Without mod_rewrite, and url like /index.php/controller
//we use PATH_INFO. It's the easiest case.
return $_SERVER["PATH_INFO"];
}
//In other cases, we'll need to get the relevant part of the URL
$current_url = get_server_url() . $_SERVER['REQUEST_URI'];
//Relevant URL part starts after the site URL
$len = strlen($Config['SiteURL']);
//We need to assert it's the correct site
if (substr($current_url, 0, $len) != $Config['SiteURL']) {
dieprint_r(GENERAL_ERROR, "Edit includes/config.php and specify the correct site URL<br /><strong>Current value:</strong> $Config[SiteURL]<br /><strong>Expected value:</strong> a string starting by " . get_server_url(), "Setup");
}
//Last possibility: use REQUEST_URI or REDIRECT_URL, but remove QUERY_STRING
//TODO: handle the case of a nginx misconfiguration, where the query_string have been removed.
// e.g. 'fastcgi_param SCRIPT_FILENAME $document_root/index.php;' will remove the QS.
// (a working could be $document_root/index.php?$query_string);
$url = array_key_exists('REDIRECT_URL', $_SERVER) ? $_SERVER["REDIRECT_URL"] : $_SERVER["REQUEST_URI"];
$url = substr(get_server_url() . $url, $len);
$pos = strpos($url, '?');
if ($pos !== false) {
return substr($url, 0, $pos);
}
return $url;
}
/*
* Gets an array of url fragments to be processed by controller
* @return array an array containing URL fragments
*/
function get_current_url_fragments () {
$url_source = get_current_url();
if ($url_source == '/index.php') return array();
return explode('/', substr($url_source, 1));
}
/**
* Gets the URL for the specified resources
*
* @param ... string a arbitray number of path info
*/
function get_url_for () {
global $Config;
- $url = get_server_url() . '/' . $Config[BaseURL];
+ $url = get_server_url() . '/' . $Config['BaseURL'];
if (func_num_args()) {
$url .= implode('/', func_get_args());
}
return $url;
}
/**
* Gets directory relative to the site root
*
* @param string $dir the absolute path
* @return string the relative directory to the site root
*/
function get_directory ($dir) {
$rootPath = dirname(__DIR__);
$rootPathLen = strlen($rootPath);
if (substr($dir, 0, $rootPathLen) != $rootPath) {
throw new InvalidArgumentException("Directory $dir doesn't start by root directory $rootPath.");
}
return substr($dir, ++$rootPathLen);
}
////////////////////////////////////////////////////////////////////////////////
/// ///
/// URL xmlHttpRequest helpers functions ///
/// ///
////////////////////////////////////////////////////////////////////////////////
/*
* Gets an hash value to check the integrity of URLs in /do.php calls
* @param array $args the args to compute the hash
* @return the hash paramater for your xmlHttpRequest url
*/
function get_xhr_hash ($args) {
global $Config;
array_shift($args);
return md5($_SESSION['ID'] . $Config['SecretKey'] . implode('', $args));
}
/*
* Gets the URL to call do.php, the xmlHttpRequest controller
* @return string the xmlHttpRequest url, with an integrity hash
*/
function get_xhr_hashed_url () {
global $Config;
$args = func_get_args();
$args[] = get_xhr_hash($args);
return $Config['DoURL'] . '/' . implode('/', $args);
}
/*
* Gets the URL to call do.php, the xmlHttpRequest controller
* @return string the xmlHttpRequest url
*/
function get_xhr_url () {
global $Config;
$args = func_get_args();
return $Config['DoURL'] . '/' .implode('/', $args);
}
diff --git a/includes/document.php b/includes/document.php
index 3abb766..c4af8d7 100644
--- a/includes/document.php
+++ b/includes/document.php
@@ -1,361 +1,361 @@
<?php
/*
* Keruald, core libraries for Pluton and Xen engines.
* (c) 2010, Sébastien Santoro aka Dereckson, some rights reserved
* Released under BSD license
*
* @package Pluton
* @subpackage Pluton
* @copyright Copyright (c) 2010-2011, Sébastien Santoro aka Dereckson
* @license Released under BSD license
* @version 0.1
*/
class Document {
/**
* URL, before any treatment
*/
public $url;
/**
* Topic, with - as topic seperator
*/
public $topic;
/**
* Article, without extension
*/
public $article;
/**
* Extension, without .
*/
public $extension;
/**
* HTTP status code (200, 404, etC.)
*/
public $status;
/**
* Document title
*/
public $title;
/**
* Document description
*/
public $description;
/**
* Content to write in <head> block
*/
public $head;
/**
* Content to write at the end of the document.
* This is after the site footer.
* To write something before, use a local _footer.php file.
*/
public $footer;
/**
* If true, doesn't print the header
* @var boolean
*/
public $noheader = false;
/**
* If true, doesn't print the footer
* @var boolean
*/
public $nofooter = false;
/**
* Initializes a new instance of Session object
*/
public function __construct ($url) {
$this->url = self::clean_url($url);
$this->get_document();
}
/**
* Finds the document
*/
private function find_document () {
//URL matches an existing file or directory
if (file_exists($this->url)) {
if (is_dir($this->url)) {
//Ensures we've a trailing /
$url = (substr($this->url, -1) == '/') ? $this->url : $this->url . '/';
if (file_exists($url . 'index.html')) {
$this->url = $url . 'index.html';
} elseif (file_exists($url . 'index.php')) {
$this->url = $url . 'index.php';
} else {
return false; //empty directory
}
}
return true;
}
//Application known extensions
$extension = get_extension($this->url);
if ($extension == "query") {
$file = $this->url . ".php";
if (file_exists($file)) {
$this->url = $file;
$this->noheader = true;
$this->nofooter = true;
return true;
}
}
//Tries other extensions
$extensions_to_try = array('html', 'php');
$pathinfo = pathinfo($this->url);
foreach ($extensions_to_try as $ext) {
$file = "$pathinfo[dirname]/$pathinfo[filename].$ext";
if (file_exists($file)) {
$this->url = $file;
return true;
}
}
//Handles homepages
if ($this->is_homepage($this->url)) {
$this->url = "_index/index.html";
return true;
}
return false;
}
/**
* Gets the URL of the entry point script
*/
static function get_entry_point_url () {
$backtrace = debug_backtrace();
$entry_point = array_pop($backtrace)['file'];
return substr($entry_point, strlen(getcwd()));
}
/**
* Gets the document matching the URL
*/
private function get_document () {
global $Config;
//Finds the document
if ($this->find_document()) {
$this->status = 200;
} else {
$this->url = $Config['Pages']['Error404']; //TODO: choose and document error implementation
$this->status = 404;
}
//Fills info from URL
$pathinfo = pathinfo($this->url);
$this->topic = str_replace('/', '-', $pathinfo['dirname']);
$this->article = $pathinfo['filename']; //PHP 5.2.0+
$this->extension = strtolower($pathinfo['extension']);
$this->title = "[$this->article]";
//Fills info from _documents.xml
$this->get_description();
}
/**
* Cleans specified URL
*
* @param string $url the URL to clean
* @return string clean URL
*/
public static function clean_url ($url) {
global $Config;
if ($Config['AllowTopicArticleRequest'] && self::hasTopicArticleRequest()) {
//This legacy mode allows site with 2001 Pluton version like
//espace-win.net to make a smoother transition.
//Cf. www.w3.org/Provider/Style/URI.html Cool URIs don't change
//Topic (?Topic=...)
if (array_key_exists('Topic', $_REQUEST)) {
$url = str_replace('-', '/', $_REQUEST['Topic']) . '/';
}
//Article (&Article=...)
if (array_key_exists('Article', $_REQUEST)) {
$url .= $_REQUEST['Article'];
} else {
$url .= 'index';
}
//Extension (&ext=...)
if (array_key_exists('ext', $_REQUEST)) {
$url .= '.';
$url .= $_REQUEST['ext'];
} else {
$url .= '.html';
}
return $url;
}
//Homepage?
if ($url == '' || $url == '/' || $url == $Config['BaseURL'] || $url == $Config['BaseURL'] . '/') {
return $Config['Homepage'];
}
return substr($url, 1);
}
/**
* Determines if the HTTP request contains Topic, Article or ext parameters
*
* @return bool true if the HTTP request contains Topic, Article or ext parameters ; otherwise, false
*/
public static function hasTopicArticleRequest () {
return array_key_exists('Topic', $_REQUEST) || array_key_exists('Article', $_REQUEST) || array_key_exists('ext', $_REQUEST);
}
/**
* Determines if the current document is the homepage.
*
* @return bool true if the current document is the homepage ; otherwise, false.
*/
public function is_homepage () {
global $Config;
//return $this->url == $Config['Homepage'];
if ( $this->url == $Config['Homepage']) return true;
if ($this->topic == "_index" && substr($this->article, 0, 5) == "index") return true;
return false;
}
/**
* Gets footer file (_footer.php) path in the current or parent directories
*
* @return string the path to the current footer if found ; otherwise, null. (or null if no footer is found)
*/
public function get_footer () {
$dirs = explode('-', $this->topic);
for ($i = count($dirs) ; $i > 0 ; $i--) {
$footer = implode('/', $dirs) . '/_footer.php';
if (file_exists($footer)) {
return $footer;
}
array_pop($dirs);
}
return null;
}
/**
* Prints the document body
*/
public function render_body () {
global $Config, $Session, $CurrentUser;
$document = $this;
//Header content
if (!$this->noheader) {
$header = $this->get_directory() . '/_header.php';
if (file_exists($header)) {
include($header);
}
}
//Includes file
switch ($this->extension) {
case 'txt':
echo "<pre>";
include($this->url);
echo "</pre>";
break;
case 'png':
case 'jpg':
case 'gif':
case 'svg':
case 'bmp':
echo "<div align=center><img src=\"$this->url\" /></div>";
break;
default:
include($this->url);
}
//Footer
- if (!$nofooter && $footer = $this->get_footer()) {
+ if (!$this->nofooter && $footer = $this->get_footer()) {
include($footer);
}
}
/**
* Prints the document
*
* Use this method if you don't wish to have access to any other global
* variables than $Config, $Session and $CurrentUser.
*
* A more flexible method is the body of this method in _includes/body.php
* and to add in your skin <?php include('_includes/body.php'); ?>
*/
function render () {
//Global variables for the header and the footer
global $Config, $Session, $CurrentUser;
$document = $this;
//Headers
if ($this->status == 404) {
header("Status: 404 Not Found");
}
//HTML output
$theme = $Config['Theme'];
if (!$this->noheader) include("themes/$theme/header.php");
$this->render_body();
if (!$this->nofooter) include("themes/$theme/footer.php");
}
/**
* Gets the document description
*/
function get_description () {
if ($this->status == 404) {
$this->title = "404 Not Found";
$this->description = "The requested resource hasn't been found.";
return;
}
if ($description = self::get_description_from_documentsXml($this->topic, $this->article)) {
$variables = [ 'title', 'description', 'head', 'footer' ];
foreach ($variables as $variable) {
if (isset($description->$variable)) {
$this->$variable = (string)$description->$variable;
}
}
$shortTags = [ 'noheader', 'nofooter' ];
foreach ($shortTags as $shortTag) {
if (isset($description->$shortTag)) {
$this->$shortTag = true;
}
}
}
}
public static function get_description_from_documentsXml ($topic, $article) {
$topicDocuments = str_replace('-', '/', $topic) . '/_documents.xml';
if (file_exists($topicDocuments)) {
$xml = simplexml_load_file($topicDocuments, null, LIBXML_NOCDATA);
foreach($xml->document as $document) {
if ($document->article == $article) {
return $document;
}
}
return null;
}
}
public function get_directory () {
return str_replace('-', '/', $this->topic);
}
}
diff --git a/lists/RegexpFactory.php b/lists/RegexpFactory.php
index a4692cf..61008cd 100644
--- a/lists/RegexpFactory.php
+++ b/lists/RegexpFactory.php
@@ -1,109 +1,109 @@
<?php
/**
* Performs operation from given a regular expression
*/
class RegexpFactory {
/**
* The regular expression
* @var string
*/
public $expression;
/**
* The last error
* @var string
*/
public $lastError;
/**
* Initializes a new instance of the RegexpFactory object.
*
* @param string The regular expression
*/
function __construct ($expression) {
$this->expression = $expression;
}
/**
* Replaces an expression using regexp, a similar way Apache mod_rewrite and Nginx wreplace do.
*
* @param string $haystack The expression to perform a replacement on
* @param string $replaceExpression The format of the result string
* @return string The replaced string
*/
function replace ($haystack, $replaceExpression) {
return preg_replace($this->expression, $replaceExpression, $haystack);
}
/**
* Encloses the regular expression with delimiters.
*/
function addDelimiters () {
$delimiters = ['/', '@', '#', '~', '+', '%', '♦', 'µ', '±', '☞'];
//TODO: check if it's okay to use UTF-8 characters as delimiters
foreach ($delimiters as $delimiter) {
if (strpos($this->expression, $delimiter) === false) {
$this->expression = $delimiter . $this->expression . $delimiter;
return;
}
}
throw new Exception("Can't delimite regexp $this->expression");
}
/**
* Determines if the specified expression is valid.
*
* @return bool true if the expression is valid; otherwise, false.
*/
public function isValid () {
$this->lastError = '';
set_error_handler('self::handleErrors');
- $result = preg_match($this->expression, null);
+ $result = preg_match($this->expression, "");
restore_error_handler();
if ($this->lastError === '' && $result === false) {
$this->lastError = self::getPCREError();
}
return $result !== false;
}
/**
* Callback for error handler
*
* @param int $errno he level of the error raised
* @param string $errstr the error message
* @return bool if false, the normal error handler continues
*/
private function handleErrors ($errno, $errstr) {
if ($errno == 2 && substr($errstr, 0, 14) == 'preg_match(): ') {
$this->lastError = substr($errstr, 14);
if (substr($this->lastError, 0, 20) == 'Compilation failed: ') {
$this->lastError = ucfirst(substr($this->lastError, 20));
}
return true;
}
message_die(
GENERAL_ERROR,
$errstr . "<p>Please report this bug. This error should be handled by the regexp factory.</p>",
'Regexp factory error'
);
}
/**
* Gets a string with an English error message matching the last PCRE error.
*
* @return The error message of the last PCRE library error.
*/
public static function getPCREError() {
$errors = array(
PREG_NO_ERROR => 'No error',
PREG_INTERNAL_ERROR => 'There was an internal PCRE error',
PREG_BACKTRACK_LIMIT_ERROR => 'Backtrack limit was exhausted',
PREG_RECURSION_LIMIT_ERROR => 'Recursion limit was exhausted',
PREG_BAD_UTF8_ERROR => 'The offset didn\'t correspond to the begin of a valid UTF-8 code point',
PREG_BAD_UTF8_OFFSET_ERROR => 'Malformed UTF-8 data',
);
return $errors[preg_last_error()];
}
}
diff --git a/lists/operations.php b/lists/operations.php
index 9499f7a..fc51618 100644
--- a/lists/operations.php
+++ b/lists/operations.php
@@ -1,44 +1,44 @@
<?php
$result = '';
if (array_key_exists('operation', $_REQUEST)) {
require('ListOperation.php');
$operation = ucfirst($_REQUEST["operation"]);
if (method_exists('ListOperation', $operation)) {
$left = explode("\n", $_REQUEST['lists'][0]);
$right = explode("\n", $_REQUEST['lists'][1]);
$result = implode("\n", ListOperation::$operation($left, $right));
} else {
$result = "// Unknown list operation.";
}
}
?>
<form name="lists" method="post" action="/lists/operations">
<div class="large-12 columns">
<div class="row">
<div class="large-3 columns">
<h6 class="panel" style="text-align: center;">List A</h6>
- <textarea name="lists[0]" rows=20><?= $_REQUEST['lists'][0] ?></textarea>
+ <textarea name="lists[0]" rows=20><?= $_REQUEST['lists'][0] ?? "" ?></textarea>
</div>
<div class="large-1 columns">
<h6 class="panel" style="text-align: center;">Operation</h6>
<label for="operation_add"><input name="operation" value="add" type="radio" id="operation_add"> <i class="gen-enclosed foundicon-plus"> add</i></label>
<label for="operation_intersect"><input name="operation" value="intersect" CHECKED type="radio" id="operation_intersect"> <i class="gen-enclosed foundicon-remove"> intersect</i></label>
<label for="operation_substract"><input name="operation" value="substract" type="radio" id="operation_substract"> <i class="gen-enclosed foundicon-minus"> substract</i></label>
<p>&nbsp;</p>
<p><input type="submit" value="Compute" class="button" /></p>
</div>
<div class="large-3 columns">
<h6 class="panel" style="text-align: center;">List B</h6>
- <textarea name="lists[1]" rows=20><?= $_REQUEST['lists'][1] ?></textarea>
+ <textarea name="lists[1]" rows=20><?= $_REQUEST['lists'][1] ?? "" ?></textarea>
</div>
<div class="large-3 columns">
<h6 class="panel" style="text-align: center;">Result</h6>
<textarea name="lists[2]" rows=20><?= $result ?></textarea>
</div>
</div>
</div>
<div style="clear: both;" />
</form>
diff --git a/lists/replace.php b/lists/replace.php
index f109c5e..4bb83bb 100644
--- a/lists/replace.php
+++ b/lists/replace.php
@@ -1,133 +1,133 @@
<?php
include('RegexpFactory.php');
// Handles permanent links
if (array_key_exists('r', $_REQUEST)) {
$_REQUEST = unserialize(base64_decode($_REQUEST['r']));
}
// bit.ly
define('FEATURE_BITLY', array_key_exists('BitLyToken', $Config));
// Options handling
$result = '';
$enable_join = array_key_exists('join', $_REQUEST) && $_REQUEST["join"] == 'on';
$enable_split = array_key_exists('split', $_REQUEST) && $_REQUEST["split"] == 'on';
if (array_key_exists('expression', $_REQUEST)) {
$requestSerialized = base64_encode(serialize($_REQUEST));
if (array_key_exists('lists', $_REQUEST) && array_key_exists(0, $_REQUEST['lists']) && array_key_exists('replacement', $_REQUEST)) {
$regexp = new RegexpFactory($_REQUEST['expression']);
$regexp->addDelimiters();
if ($regexp->isValid()) {
$items = explode("\n", $_REQUEST['lists'][0]);
$replace_callback = function (&$item, $key, $replaceExpression) use ($regexp) {
$item = $regexp->replace(trim($item), $replaceExpression);
};
array_walk($items, $replace_callback, $_REQUEST['replacement']);
$result = join("\n", $items);
if ($enable_join) {
$result = join($_REQUEST["joinglue"], $items);
}
if ($enable_split) {
$split_result = [];
foreach ($items as $item) {
$split_result = array_merge($split_result, explode($_REQUEST["splitseparator"], $item));
}
$result = join("\n", $split_result);
}
}
}
//If no list is given, or the replacement expression is blank, the result list is blank.
}
?>
<script>
/**
* Updates the form's widgets
*/
function updateUI () {
//Checks the join enable box when a glue string is provided
if (document.getElementById("joinglue").value != "" && !document.getElementById("join").checked) {
document.getElementById("join").checked = true;
$("#join-checkbox .checkbox").addClass("checked");
}
//Checks the split enable box when a split seperator is provided
if (document.getElementById('splitseparator').value != "" && !document.getElementById("split").checked) {
document.getElementById("split").checked = true;
$("#split-checkbox .checkbox").addClass("checked");
}
}
</script>
<form name="lists" method="post" action="/lists/replace" class="custom">
<div class="row collapse">
<div class="one mobile-one columns">
<span class="prefix">Replace</span>
</div>
<div class="five mobile-three columns">
<input
name="expression" id="expression" type="text"
placeholder="The Nginx or Apache mod_rewrite-like regular expression"
- value="<?= $_REQUEST['expression'] ?>"
+ value="<?= $_REQUEST['expression'] ?? "" ?>"
/>
<?php if (isset($regexp) && $regexp->lastError) echo '<small class="error" style="font-weight: 400;">', $regexp->lastError, '</small>'; ?>
</div>
<div class="five mobile-three columns">
<input
name="replacement" id="replacement" type="text"
placeholder="The list format. Use $1, $2, … to use the regexp groups."
- value="<?= $_REQUEST['replacement'] ?>"
+ value="<?= $_REQUEST['replacement'] ?? "" ?>"
/>
</div>
<div class="one mobile-one columns">
<input type="submit" class="button expand postfix" value="Format" />
</div>
</div>
<div class="row collapse">
<div class="one mobile-one columns">
<span class="prefix">Join</span>
</div>
<div class="ten mobile-six columns">
- <input name="joinglue" id="joinglue" type="text" placeholder="Glue text to join the list into a string. Leave blank to concat without seperator. Don't forget to check the checkbox to enable." value="<?= $_REQUEST['joinglue'] ?>" onchange="updateUI();" />
+ <input name="joinglue" id="joinglue" type="text" placeholder="Glue text to join the list into a string. Leave blank to concat without seperator. Don't forget to check the checkbox to enable." value="<?= $_REQUEST['joinglue'] ?? "" ?>" onchange="updateUI();" />
</div>
<div class="one mobile-one columns" style="text-align: center;">
<span id="join-checkbox"><input type="checkbox" id="join" name="join" <?= $enable_join ? 'checked ' : '' ?>/><br /><label for="join">Enable</label></span>
</div>
</div>
<div class="row collapse">
<div class="one mobile-one columns">
<span class="prefix">Split</span>
</div>
<div class="ten mobile-six columns">
- <input name="splitseparator" id="splitseparator" type="text" placeholder="Separator text to split the list furthermore." value="<?= $_REQUEST['splitseparator'] ?>" onchange="updateUI();" />
+ <input name="splitseparator" id="splitseparator" type="text" placeholder="Separator text to split the list furthermore." value="<?= $_REQUEST['splitseparator'] ?? "" ?>" onchange="updateUI();" />
</div>
<div class="one mobile-one columns" style="text-align: center;">
<span id="split-checkbox"><input type="checkbox" id="split" name="split" <?= $enable_split ? 'checked ' : '' ?>/><br /><label for="split">Enable</label></span>
</div>
</div>
<div class="row collapse">
<div class="six columns">
- <textarea name="lists[0]" rows="16" style="width: 99%;" placeholder="The list to format"><?= $_REQUEST['lists'][0] ?></textarea>
+ <textarea name="lists[0]" rows="16" style="width: 99%;" placeholder="The list to format"><?= $_REQUEST['lists'][0] ?? "" ?></textarea>
</div>
<div class="six columns">
<textarea name="lists[1]" rows="16" style="width: 99%;" placeholder="The formatted list will appear here."><?= $result ?></textarea>
</div>
</div>
</form>
<?php
if (isset($requestSerialized)) {
$permUrl = "/lists/replace/?r=$requestSerialized";
if (FEATURE_BITLY) {
try {
$permUrl = bitly_shorten(get_server_url() . $permUrl);
} catch (Guzzle\Http\Exception\ServerErrorResponseException $ex) {
// Degrades silently when bit.ly API throws an error response like a 500.
}
}
echo " <p><a href=\"$permUrl\">Permanent link to this query</a></p>\n";
}
?>
<p><strong>Documentation resources:</strong> <a href="http://perldoc.perl.org/perlre.html">PCRE syntax</a> • <a href="http://www.cheatography.com/davechild/cheat-sheets/regular-expressions/">Regular Expressions Cheat Sheet</a>
<br /><strong>Note:</strong> Write your regexp without delimiter.</p>

File Metadata

Mime Type
text/x-diff
Expires
Wed, Mar 18, 10:37 (6 h, 45 m)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3539363
Default Alt Text
(45 KB)

Event Timeline