😑 Fixed bug detected in 1.1.1

pull/40/head 1.1.3
rodolfoberrios 2019-02-19 17:35:48 -03:00
parent f33b7e1a50
commit c9998cfb06
7 changed files with 1078 additions and 1346 deletions

View File

@ -1,6 +1,6 @@
<?php
define('G_APP_NAME', 'Chevereto Free');
define('G_APP_VERSION', '1.1.2');
define('G_APP_VERSION', '1.1.3');
define('G_APP_GITHUB_OWNER', 'Chevereto');
define('G_APP_GITHUB_REPO', 'Chevereto-Free');
define('G_APP_GITHUB_REPO_URL', 'https://github.com/' . G_APP_GITHUB_OWNER . '/' . G_APP_GITHUB_REPO);

View File

@ -254,6 +254,7 @@ try {
],
'1.1.1' => NULL,
'1.1.2' => NULL,
'1.1.3' => NULL,
];
// Settings that must be renamed from NAME to NEW NAME and DELETE old NAME
$settings_rename = [];

View File

@ -16,14 +16,12 @@
namespace G;
if (!defined('access') or !access) {
die("This file cannot be directly accessed.");
}
if(!defined('access') or !access) die("This file cannot be directly accessed.");
define('G_VERSION', '1.0.42');
// Error reporting setup
@ini_set('log_errors', true);
@ini_set('log_errors', TRUE);
error_reporting(E_ALL ^ E_NOTICE);
// Set default locale
@ -33,7 +31,7 @@ setlocale(LC_ALL, 'en_US.UTF8');
@ini_set('default_charset', 'utf-8');
// Set G\ paths and files
define('G_ROOT_PATH', rtrim(str_replace('\\', '/', dirname(dirname(__DIR__))), '/') . '/');
define('G_ROOT_PATH', rtrim(str_replace('\\','/', dirname(dirname(__DIR__))), '/') . '/');
define('G_ROOT_PATH_RELATIVE', rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/') . '/');
define('G_ROOT_LIB_PATH', G_ROOT_PATH . 'lib/');
define('G_PATH', G_ROOT_LIB_PATH . 'G/');
@ -54,75 +52,65 @@ define('G_APP_SETTINGS_FILE_ERROR', '<br />There are errors in the <strong>%%FIL
// Include the static app config file
(file_exists(G_APP_PATH . 'settings.php')) ? require_once(G_APP_PATH . 'settings.php') : die("G\: Can't find app/settings.php");
if (headers_sent()) {
die(str_replace('%%FILE%%', 'app/settings.php', G_APP_SETTINGS_FILE_ERROR));
} // Stop on premature headers
if(headers_sent()) die(str_replace('%%FILE%%', 'app/settings.php', G_APP_SETTINGS_FILE_ERROR)); // Stop on premature headers
// TZ failover
$tz = @date_default_timezone_get();
$dtz = @date_default_timezone_set($tz);
if (!$dtz && !@date_default_timezone_set('America/Santiago')) {
die(strtr('Invalid timezone identifier: %i. Configure php.ini with a valid timezone identifier %l', ['%i' => $tz, '%l' => 'http://php.net/manual/en/timezones.php']));
if(!$dtz && !@date_default_timezone_set('America/Santiago')) {
die(strtr('Invalid timezone identifier: %i. Configure php.ini with a valid timezone identifier %l', ['%i' => $tz, '%l' => 'http://php.net/manual/en/timezones.php']));
}
// Session hack
if ($settings['session.save_path']) {
session_save_path($settings['session.save_path']);
if($settings['session.save_path']) {
session_save_path($settings['session.save_path']);
}
// Can work with sessions?
if (!@session_start()) {
die("G\: Sessions are not working on this server (session_start).");
}
if(!@session_start()) die("G\: Sessions are not working on this server (session_start).");
// Is session save path OK? (you won't believe how many people has session issues!)
$session_save_path = @realpath(session_save_path());
if ($session_save_path) { // realpath on this needs pre-webroot directories access
foreach (['write'] as $k) {
$fn = 'is_' . $k . 'able';
if (!$fn($session_save_path)) {
$session_errors[] = $k;
}
}
if (isset($session_errors)) {
die(strtr("G\: Sessions are not working on this server due to missing %s permission on session save path (%f session.save_path).", ['%s' => implode('/', $session_errors), '%f' => $settings['session.save_path'] ? 'app/settings.php' : 'php.ini']));
}
if($session_save_path) { // realpath on this needs pre-webroot directories access
foreach(['write'] as $k) {
$fn = 'is_' . $k . 'able';
if(!$fn($session_save_path)) $session_errors[] = $k;
}
if(isset($session_errors)) die(strtr("G\: Sessions are not working on this server due to missing %s permission on session save path (%f session.save_path).", ['%s' => implode('/', $session_errors), '%f' => $settings['session.save_path'] ? 'app/settings.php' : 'php.ini']));
}
// Are sessions working properly?
$_SESSION['G'] = true;
if (!$_SESSION['G']) {
die("G\: Sessions are not working properly. Check for any conflicting server setting.");
}
$_SESSION['G'] = TRUE;
if(!$_SESSION['G']) die("G\: Sessions are not working properly. Check for any conflicting server setting.");
// Set the starting execution time
define('G_APP_TIME_EXECUTION_START', microtime(true));
// Include G\ core functions
(file_exists(__DIR__ . '/functions.php')) ? require_once(__DIR__ . '/functions.php') : die("G\: Can't find <strong>" . __DIR__ . '/functions.php' . '</strong>. Make sure that this file exists.');
if (file_exists(__DIR__ . '/functions.render.php')) {
require_once(__DIR__ . '/functions.render.php');
if(file_exists(__DIR__ . '/functions.render.php')) {
require_once(__DIR__ . '/functions.render.php');
}
if (isset($settings) && $settings['error_reporting'] === false) {
error_reporting(0);
if(isset($settings) && $settings['error_reporting'] === false) {
error_reporting(0);
}
// Set the default timezone
if (isset($settings['default_timezone']) && is_valid_timezone($settings['default_timezone'])) {
if (!@date_default_timezone_set($settings['default_timezone'])) {
die(strtr("G\: Can't set %s timezone on line %l", ['%s' => $settings['default_timezone'], '%l' => __LINE__ - 1]));
}
if(isset($settings['default_timezone']) && is_valid_timezone($settings['default_timezone'])) {
if(!@date_default_timezone_set($settings['default_timezone'])) {
die(strtr("G\: Can't set %s timezone on line %l", ['%s' => $settings['default_timezone'], '%l' => __LINE__ - 1]));
}
}
// Set the system environment
if (isset($settings['environment'])) {
define('G_APP_ENV', $settings['environment']);
if(isset($settings['environment'])) {
define('G_APP_ENV', $settings['environment']);
}
// Set the HTTP definitions
define('G_HTTP_HOST', $_SERVER['HTTP_HOST']);
define('G_HTTP_PROTOCOL', 'http' . ((((!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') || $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') || $settings['https']) ? 's' : null));
define('G_HTTP_PROTOCOL', 'http' . ((((!empty($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) || $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') || $settings['https']) ? 's' : NULL));
// La cumbia me divierte y mesita
@ -130,24 +118,24 @@ define('G_HTTP_PROTOCOL', 'http' . ((((!empty($_SERVER['HTTPS']) && strtolower($
$_SERVER['SCRIPT_FILENAME'] = forward_slash($_SERVER['SCRIPT_FILENAME']);
$_SERVER['SCRIPT_NAME'] = forward_slash($_SERVER['SCRIPT_NAME']);
// Fix CloudFlare REMOTE_ADDR
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
if(isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
}
// Inherit application definitions
if (file_exists(G_APP_PATH . 'app.php')) {
require_once(G_APP_PATH . 'app.php');
if(file_exists(G_APP_PATH . 'app.php')) {
require_once(G_APP_PATH . 'app.php');
}
// Set the DB constants
foreach (['host', 'port', 'name', 'user', 'pass', 'driver', 'pdo_attrs'] as $k) {
define('G_APP_DB_' . strtoupper($k), isset($settings['db_' . $k]) ? (is_array($settings['db_' . $k]) ? serialize($settings['db_' . $k]) : $settings['db_' . $k]) : null);
foreach(['host', 'port', 'name', 'user', 'pass', 'driver', 'pdo_attrs'] as $k) {
define('G_APP_DB_' . strtoupper($k), isset($settings['db_' . $k]) ? (is_array($settings['db_' . $k]) ? serialize($settings['db_' . $k]) : $settings['db_' . $k]) : NULL);
}
// Include app functions
(file_exists(G_APP_FILE_FUNCTIONS)) ? require_once(G_APP_FILE_FUNCTIONS) : die("G\: Can't find <strong>" . G_APP_FILE_FUNCTIONS . '</strong>. Make sure that this file exists.');
if (file_exists(G_APP_FILE_FUNCTIONS_RENDER)) {
require_once(G_APP_FILE_FUNCTIONS_RENDER);
if(file_exists(G_APP_FILE_FUNCTIONS_RENDER)) {
require_once(G_APP_FILE_FUNCTIONS_RENDER);
}
// Set the URLs
@ -157,11 +145,11 @@ define("G_APP_LIB_URL", absolute_to_url(G_APP_PATH_LIB));
// Define the app theme
define('G_APP_PATH_THEMES', G_APP_PATH . 'themes/');
if (!file_exists(G_APP_PATH_THEMES)) {
die("G\: Theme path doesn't exists!");
if(!file_exists(G_APP_PATH_THEMES)) {
die("G\: Theme path doesn't exists!");
}
if (isset($settings['theme']) and file_exists(G_APP_PATH_THEMES . $settings['theme'])) {
define('G_APP_PATH_THEME', G_APP_PATH_THEMES . $settings['theme'].'/');
define('BASE_URL_THEME', absolute_to_url(G_APP_PATH_THEME));
}
if(isset($settings['theme']) and file_exists(G_APP_PATH_THEMES . $settings['theme'])) {
define('G_APP_PATH_THEME', G_APP_PATH_THEMES . $settings['theme'].'/');
define('BASE_URL_THEME', absolute_to_url(G_APP_PATH_THEME));
}

View File

@ -20,550 +20,528 @@
*/
namespace G;
use PDO, PDOException, Exception;
use PDO;
use PDOException;
use Exception;
class DB {
class DB
{
private static $instance;
private static $instance;
private $host = G_APP_DB_HOST;
private $port = G_APP_DB_PORT;
private $name = G_APP_DB_NAME;
private $user = G_APP_DB_USER;
private $pass = G_APP_DB_PASS;
private $driver = G_APP_DB_DRIVER;
private $pdo_attrs = G_APP_DB_PDO_ATTRS;
private $host = G_APP_DB_HOST;
private $port = G_APP_DB_PORT;
private $name = G_APP_DB_NAME;
private $user = G_APP_DB_USER;
private $pass = G_APP_DB_PASS;
private $driver = G_APP_DB_DRIVER;
private $pdo_attrs = G_APP_DB_PDO_ATTRS;
public static $dbh;
public $query;
static $dbh;
public $query;
/**
* Connect to the DB server
* Throws an Exception on error (tay weando? en serio?)
*/
public function __construct($conn=[])
{
try {
// PDO already connected
if (empty($conn) and isset(self::$dbh) and get_class(self::$dbh) == 'PDO') {
return true;
}
/**
* Connect to the DB server
* Throws an Exception on error (tay weando? en serio?)
*/
public function __construct($conn=[]) {
if (!empty($conn)) {
// Inject connection info
foreach (['host', 'user', 'name', 'pass', 'port', 'driver', 'pdo_attrs'] as $k) {
$this->{$k} = $conn[$k];
}
}
try {
// PDO already connected
if(empty($conn) and isset(self::$dbh) and get_class(self::$dbh) == 'PDO') {
return TRUE;
}
$pdo_connect = $this->driver . ':host=' . $this->host . ';dbname=' . $this->name;
if ($this->port) {
$pdo_connect .= ';port=' . $this->port;
}
// $pdo_connect .= ';charset=UTF8';
if(!empty($conn)) {
// Inject connection info
foreach(['host', 'user', 'name', 'pass', 'port', 'driver', 'pdo_attrs'] as $k) {
$this->{$k} = $conn[$k];
}
}
$this->pdo_attrs = @unserialize($this->pdo_attrs) ?: $this->pdo_attrs;
$pdo_connect = $this->driver . ':host=' . $this->host . ';dbname=' . $this->name;
if($this->port) {
$pdo_connect .= ';port=' . $this->port;
}
// PDO defaults
$this->pdo_default_attrs = [
PDO::ATTR_TIMEOUT => 30,
];
$this->pdo_attrs = @unserialize($this->pdo_attrs) ?: $this->pdo_attrs;
// Override PDO defaults ?
$this->pdo_attrs = (is_array($this->pdo_attrs) ? $this->pdo_attrs : []) + $this->pdo_default_attrs;
// PDO defaults
$this->pdo_default_attrs = [
PDO::ATTR_TIMEOUT => 30,
//PDO::ATTR_PERSISTENT => FALSE
];
// PDO hard overrides
$this->pdo_attrs[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$this->pdo_attrs[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET time_zone = '+00:00', NAMES 'UTF8'"; // UTC for timestamps
// Override PDO defaults ?
$this->pdo_attrs = (is_array($this->pdo_attrs) ? $this->pdo_attrs : []) + $this->pdo_default_attrs;
// Turn off PHP error reporting just for the connection here (invalid host names will trigger a PHP warning)
$error_reporting = error_reporting();
error_reporting(0);
// PDO hard overrides
$this->pdo_attrs[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$this->pdo_attrs[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES 'UTF8'";
// Note that PDO::ERRMODE_SILENT has no effect on connection. Connections always throw an exception if it fails
self::$dbh = new PDO($pdo_connect, $this->user, $this->pass, $this->pdo_attrs);
// Turn off PHP error reporting just for the connection here (invalid host names will trigger a PHP warning)
$error_reporting = error_reporting();
error_reporting(0);
// Re-enable the error_reporting level
error_reporting($error_reporting);
// Note that PDO::ERRMODE_SILENT has no effect on connection. Connections always throw an exception if it fails
self::$dbh = new PDO($pdo_connect, $this->user, $this->pass, $this->pdo_attrs);
// PDO emulate prepares if needed
if (version_compare(self::$dbh->getAttribute(PDO::ATTR_SERVER_VERSION), '5.1.17', '<')) {
self::$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
}
// Re-enable the error_reporting level
error_reporting($error_reporting);
self::$instance = $this;
} catch (Exception $e) {
self::$dbh = null;
throw new DBException($e->getMessage(), 400);
}
}
// PDO emulate prepares if needed
if(version_compare(self::$dbh->getAttribute(PDO::ATTR_SERVER_VERSION), '5.1.17', '<')) {
self::$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
}
/**
* Singleton instance handler
* Used for the static methods of this class
*/
public static function getInstance()
{
if (is_null(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
self::$instance = $this;
/**
* Populates the class DB own PDO attributes array with an entire array
* Attribute list here: http://php.net/manual/en/pdo.setattribute.php
*/
public function setPDOAttrs($attributes)
{
$this->pdo_attrs = $attributes;
}
} catch(Exception $e) {
self::$dbh = NULL;
throw new DBException($e->getMessage(), 400);
}
/**
* Populates the class DB own PDO attributes array with a single key
* Attributes list here: http://php.net/manual/en/pdo.setattribute.php
*/
public function setPDOAttr($key, $value)
{
$this->pdo_attrs[$key] = $value;
}
}
public function getAttr($attr)
{
return self::$dbh->getAttribute($attr);
}
/**
* Singleton instance handler
* Used for the static methods of this class
*/
public static function getInstance() {
if(is_null(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Prepares an SQL statement to be executed by the PDOStatement::execute() method
* http://php.net/manual/en/pdo.prepare.php
*/
public function query($query)
{
$this->query = self::$dbh->prepare($query);
}
/**
* Populates the class DB own PDO attributes array with an entire array
* Attribute list here: http://php.net/manual/en/pdo.setattribute.php
*/
public function setPDOAttrs($attributes) {
$this->pdo_attrs = $attributes;
}
public function errorInfo()
{
return self::$dbh->errorInfo();
}
/**
* Populates the class DB own PDO attributes array with a single key
* Attributes list here: http://php.net/manual/en/pdo.setattribute.php
*/
public function setPDOAttr($key, $value) {
$this->pdo_attrs[$key] = $value;
}
/**
* Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement
* http://php.net/manual/en/pdostatement.bindvalue.php
*/
public function bind($param, $value, $type = null)
{
if (is_null($type)) {
switch (true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
break;
}
}
$this->query->bindValue($param, $value, $type);
}
public function getAttr($attr) {
return self::$dbh->getAttribute($attr);
}
public function exec()
{
return $this->query->execute();
}
/**
* Prepares an SQL statement to be executed by the PDOStatement::execute() method
* http://php.net/manual/en/pdo.prepare.php
*/
public function query($query) {
$this->query = self::$dbh->prepare($query);
}
public function fetchColumn()
{
return $this->query->fetchColumn();
}
public function errorInfo() {
return self::$dbh->errorInfo();
}
public function closeCursor()
{
return $this->query->closeCursor();
}
/**
* Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement
* http://php.net/manual/en/pdostatement.bindvalue.php
*/
public function bind($param, $value, $type = null) {
if(is_null($type)) {
switch(true) {
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
break;
}
}
$this->query->bindValue($param, $value, $type);
}
public function fetchAll($mode=PDO::FETCH_ASSOC)
{
$this->exec();
return $this->query->fetchAll(is_int($mode) ? $mode : PDO::FETCH_ASSOC);
}
public function exec() {
return $this->query->execute();
}
/**
* Execute and returns the single result from the prepared statement
* http://php.net/manual/en/pdostatement.fetch.php
*/
public function fetchSingle($mode=PDO::FETCH_ASSOC)
{
$this->exec();
return $this->query->fetch(is_int($mode) ? $mode : PDO::FETCH_ASSOC);
}
public function fetchColumn() {
return $this->query->fetchColumn();
}
/**
* Query and exec, return number of affected rows or FALSE
*/
public static function queryExec($query)
{
try {
$db = self::getInstance();
$db->query($query);
return $db->exec() ? $db->rowCount() : false;
} catch (Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
public function closeCursor() {
return $this->query->closeCursor();
}
/**
* Query and fetch single record
*/
public static function queryFetchSingle($query, $fetch_style=null)
{
try {
return self::queryFetch($query, 1, $fetch_style);
} catch (Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
public function fetchAll($mode=PDO::FETCH_ASSOC) {
$this->exec();
return $this->query->fetchAll(is_int($mode) ? $mode : PDO::FETCH_ASSOC);
}
/**
* Query and fetch all records
*/
public static function queryFetchAll($query, $fetch_style=null)
{
try {
return self::queryFetch($query, null, $fetch_style);
} catch (Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
/**
* Execute and returns the single result from the prepared statement
* http://php.net/manual/en/pdostatement.fetch.php
*/
public function fetchSingle($mode=PDO::FETCH_ASSOC) {
$this->exec();
return $this->query->fetch(is_int($mode) ? $mode : PDO::FETCH_ASSOC);
}
/**
* Query fetch (core version)
*/
public static function queryFetch($query, $limit=1, $fetch_style=null)
{
try {
$db = self::getInstance();
$db->query($query);
return $limit == 1 ? $db->fetchSingle($fetch_style) : $db->fetchAll($fetch_style);
} catch (Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
/**
* Query and exec, return number of affected rows or FALSE
*/
public static function queryExec($query) {
try {
$db = self::getInstance();
$db->query($query);
return $db->exec() ? $db->rowCount() : FALSE;
} catch(Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
/**
* Returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed
* http://php.net/manual/en/pdostatement.rowcount.php
*/
public function rowCount()
{
return $this->query->rowCount();
}
/**
* Query and fetch single record
*/
public static function queryFetchSingle($query, $fetch_style=NULL) {
try {
return self::queryFetch($query, 1, $fetch_style);
} catch(Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
/**
* Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver
* http://php.net/manual/en/pdo.lastinsertid.php
*/
public function lastInsertId()
{
return self::$dbh->lastInsertId();
}
/**
* Query and fetch all records
*/
public static function queryFetchAll($query, $fetch_style=NULL) {
try {
return self::queryFetch($query, NULL, $fetch_style);
} catch(Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
/**
* Turns off autocommit mode
* http://php.net/manual/en/pdo.begintransaction.php
*/
public function beginTransaction()
{
return self::$dbh->beginTransaction();
}
/**
* Query fetch (core version)
*/
public static function queryFetch($query, $limit=1, $fetch_style=NULL) {
try {
$db = self::getInstance();
$db->query($query);
return $limit == 1 ? $db->fetchSingle($fetch_style) : $db->fetchAll($fetch_style);
} catch(Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
/**
* Commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction
* http://php.net/manual/en/pdo.commit.php
*/
public function endTransaction()
{
return self::$dbh->commit();
}
/**
* Returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed
* http://php.net/manual/en/pdostatement.rowcount.php
*/
public function rowCount() {
return $this->query->rowCount();
}
/**
* Rolls back the current transaction, as initiated by PDO::beginTransaction()
* http://php.net/manual/en/pdo.rollback.php
*/
public function cancelTransaction()
{
return self::$dbh->rollBack();
}
/**
* Returns the ID of the last inserted row, or the last value from a sequence object, depending on the underlying driver
* http://php.net/manual/en/pdo.lastinsertid.php
*/
public function lastInsertId() {
return self::$dbh->lastInsertId();
}
/**
* Dumps the informations contained by a prepared statement directly on the output
* http://php.net/manual/en/pdostatement.debugdumpparams.php
*/
public function debugDumpParams()
{
return $this->query->debugDumpParams();
}
/**
* Turns off autocommit mode
* http://php.net/manual/en/pdo.begintransaction.php
*/
public function beginTransaction(){
return self::$dbh->beginTransaction();
}
/* Now the G\ fast DB methods, presented by Chevereto */
/**
* Commits a transaction, returning the database connection to autocommit mode until the next call to PDO::beginTransaction() starts a new transaction
* http://php.net/manual/en/pdo.commit.php
*/
public function endTransaction(){
return self::$dbh->commit();
}
/**
* Get the table with its prefix
*/
public static function getTable($table)
{
return get_app_setting('db_table_prefix') . $table;
}
/**
* Rolls back the current transaction, as initiated by PDO::beginTransaction()
* http://php.net/manual/en/pdo.rollback.php
*/
public function cancelTransaction(){
return self::$dbh->rollBack();
}
/**
* Get values from DB
*/
public static function get($table, $values, $clause='AND', $sort=[], $limit=null, $fetch_style=null)
{
if (!is_array($values) and $values !== 'all') {
throw new DBException('Expecting array values, '.gettype($values).' given in ' . __METHOD__, 100);
}
/**
* Dumps the informations contained by a prepared statement directly on the output
* http://php.net/manual/en/pdostatement.debugdumpparams.php
*/
public function debugDumpParams(){
return $this->query->debugDumpParams();
}
self::validateClause($clause, __METHOD__);
/* Now the G\ fast DB methods, presented by Chevereto */
if (is_array($table)) {
$join = $table['join'];
$table = $table['table'];
}
/**
* Get the table with its prefix
*/
public static function getTable($table) {
return get_app_setting('db_table_prefix') . $table;
}
$table = DB::getTable($table);
/**
* Get values from DB
*/
public static function get($table, $values, $clause='AND', $sort=[], $limit=NULL, $fetch_style=NULL) {
$query = 'SELECT * FROM '.$table;
if(!is_array($values) and $values !== 'all') {
throw new DBException('Expecting array values, '.gettype($values).' given in ' . __METHOD__, 100);
}
if ($join) {
$query .= ' ' . $join . ' ';
}
self::validateClause($clause, __METHOD__);
if (is_array($values) and !empty($values)) {
$query .= ' WHERE ';
foreach ($values as $k => $v) {
if (is_null($v)) {
$query .= '`'.$k.'` IS :'.$k.' '.$clause.' ';
} else {
$query .= '`'.$k.'`=:'.$k.' '.$clause.' ';
}
}
}
if(is_array($table)) {
$join = $table['join'];
$table = $table['table'];
}
$query = rtrim($query, $clause . ' ');
$table = DB::getTable($table);
if (is_array($sort) and !empty($sort)) {
if (!$sort['field']) {
$sort['field'] = 'date';
}
if (!$sort['order']) {
$sort['order'] = 'desc';
}
$query .= ' ORDER BY '.$sort['field'].' '.strtoupper($sort['order']).' ';
}
$query = 'SELECT * FROM '.$table;
if ($limit and is_int($limit)) {
$query .= " LIMIT $limit";
}
if($join) {
$query .= ' ' . $join . ' ';
}
try {
$db = self::getInstance();
$db->query($query);
if (is_array($values)) {
foreach ($values as $k => $v) {
$db->bind(':'.$k, $v);
}
}
return $limit == 1 ? $db->fetchSingle($fetch_style) : $db->fetchAll($fetch_style);
} catch (Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
if(is_array($values) and !empty($values)) {
$query .= ' WHERE ';
foreach($values as $k => $v) {
if(is_null($v)) {
$query .= '`'.$k.'` IS :'.$k.' '.$clause.' ';
} else {
$query .= '`'.$k.'`=:'.$k.' '.$clause.' ';
}
}
}
/**
* Update target table row(s)
* Returns the number of affected rows or false
*/
public static function update($table, $values, $wheres, $clause='AND')
{
if (!is_array($values)) {
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
}
if (!is_array($wheres)) {
throw new DBException('Expecting array values, '.gettype($wheres).' given in '. __METHOD__, 100);
}
$query = rtrim($query, $clause . ' ');
self::validateClause($clause, __METHOD__);
if(is_array($sort) and !empty($sort)) {
if(!$sort['field']) {
$sort['field'] = 'date';
}
if(!$sort['order']) {
$sort['order'] = 'desc';
}
$query .= ' ORDER BY '.$sort['field'].' '.strtoupper($sort['order']).' ';
}
$table = DB::getTable($table);
if($limit and is_int($limit)) {
$query .= " LIMIT $limit";
}
$query = 'UPDATE `'.$table.'` SET ';
try {
$db = self::getInstance();
$db->query($query);
if(is_array($values)) {
foreach($values as $k => $v) {
$db->bind(':'.$k, $v);
}
}
return $limit == 1 ? $db->fetchSingle($fetch_style) : $db->fetchAll($fetch_style);
} catch(Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
// Set the value pairs
foreach ($values as $k => $v) {
$query .= '`' . $k . '`=:value_' . $k . ',';
}
$query = rtrim($query, ',') . ' WHERE ';
/**
* Update target table row(s)
* Returns the number of affected rows or false
*/
public static function update($table, $values, $wheres, $clause='AND') {
// Set the where pairs
foreach ($wheres as $k => $v) {
$query .= '`'.$k.'`=:where_'.$k.' '.$clause.' ';
}
$query = rtrim($query, $clause.' ');
if(!is_array($values)) {
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
}
if(!is_array($wheres)) {
throw new DBException('Expecting array values, '.gettype($wheres).' given in '. __METHOD__, 100);
}
try {
$db = self::getInstance();
$db->query($query);
self::validateClause($clause, __METHOD__);
// Bind the values
foreach ($values as $k => $v) {
$db->bind(':value_'.$k, $v);
}
foreach ($wheres as $k => $v) {
$db->bind(':where_'.$k, $v);
}
$table = DB::getTable($table);
return $db->exec() ? $db->rowCount() : false;
} catch (Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
$query = 'UPDATE `'.$table.'` SET ';
/**
* Insert single row to the table
*/
public static function insert($table, $values)
{
if (!is_array($values)) {
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
}
// Set the value pairs
foreach($values as $k => $v) {
$query .= '`' . $k . '`=:value_' . $k . ',';
}
$query = rtrim($query, ',') . ' WHERE ';
$table = DB::getTable($table);
// Set the where pairs
foreach($wheres as $k => $v) {
$query .= '`'.$k.'`=:where_'.$k.' '.$clause.' ';
}
$query = rtrim($query, $clause.' ');
$table_fields = [];
foreach ($values as $k => $v) {
$table_fields[] = $k;
}
try {
$db = self::getInstance();
$db->query($query);
$query = 'INSERT INTO
// Bind the values
foreach($values as $k => $v) {
$db->bind(':value_'.$k, $v);
}
foreach($wheres as $k => $v) {
$db->bind(':where_'.$k, $v);
}
return $db->exec() ? $db->rowCount() : FALSE;
} catch(Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
/**
* Insert single row to the table
*/
public static function insert($table, $values) {
if(!is_array($values)) {
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
}
$table = DB::getTable($table);
$table_fields = [];
foreach($values as $k => $v) {
$table_fields[] = $k;
}
$query = 'INSERT INTO
`'.$table.'` (`' . ltrim(implode('`,`', $table_fields), '`,`') . '`)
VALUES (' . ':' . str_replace(':', ',:', implode(':', $table_fields)) . ')';
try {
$db = self::getInstance();
$db->query($query);
foreach ($values as $k => $v) {
$db->bind(':'.$k, $v);
}
return $db->exec() ? $db->lastInsertId() : false;
} catch (Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
try {
$db = self::getInstance();
$db->query($query);
foreach($values as $k => $v) {
$db->bind(':'.$k, $v);
}
return $db->exec() ? $db->lastInsertId() : FALSE;
} catch(Exception $e) {
throw new DBException($e->getMessage(), 400);
}
/**
* Update target numecic table row(s) with and increment (positive or negative)
* Returns the number of affected rows or false
* Note: Minimum value to be set is zero, no negative values here
*/
public static function increment($table, $values, $wheres, $clause='AND')
{
foreach (['values', 'wheres'] as $k) {
if (!is_array(${$k})) {
throw new DBException('Expecting array values, '.gettype(${$k}).' given in '. __METHOD__, 100);
}
}
}
$table = DB::getTable($table);
$query = 'UPDATE `'.$table.'` SET ';
/**
* Update target numecic table row(s) with and increment (positive or negative)
* Returns the number of affected rows or false
* Note: Minimum value to be set is zero, no negative values here
*/
public static function increment($table, $values, $wheres, $clause='AND') {
foreach ($values as $k => $v) {
if (preg_match('/^([+-]{1})\s*([\d]+)$/', $v, $matches)) { // 1-> op 2-> number
$query .= '`' . $k . '`=';
if ($matches[1] == '+') {
$query .= '`' . $k . '`' . $matches[1] . $matches[2] . ',';
}
if ($matches[1] == '-') {
$query .= 'GREATEST(cast(`'.$k.'` AS SIGNED) - '.$matches[2].', 0),';
}
}
}
foreach(['values', 'wheres'] as $k) {
if(!is_array(${$k})) {
throw new DBException('Expecting array values, '.gettype(${$k}).' given in '. __METHOD__, 100);
}
}
$query = rtrim($query, ',') . ' WHERE ';
$table = DB::getTable($table);
$query = 'UPDATE `'.$table.'` SET ';
// Set the where pairs
foreach ($wheres as $k => $v) {
$query .= '`'.$k.'`=:where_'.$k.' '.$clause.' ';
}
$query = rtrim($query, $clause.' ');
foreach($values as $k => $v) {
if(preg_match('/^([+-]{1})\s*([\d]+)$/', $v, $matches)) { // 1-> op 2-> number
$query .= '`' . $k . '`=';
if($matches[1] == '+') {
$query .= '`' . $k . '`' . $matches[1] . $matches[2] . ',';
}
if($matches[1] == '-') {
$query .= 'GREATEST(cast(`'.$k.'` AS SIGNED) - '.$matches[2].', 0),';
}
}
}
try {
$db = self::getInstance();
$db->query($query);
foreach ($wheres as $k => $v) {
$db->bind(':where_'.$k, $v);
}
return $db->exec() ? $db->rowCount() : false;
} catch (Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
$query = rtrim($query, ',') . ' WHERE ';
/**
* Delete row(s) from table
* Returns the number of affected rows or false
*/
public static function delete($table, $values, $clause='AND')
{
if (!is_array($values)) {
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
}
// Set the where pairs
foreach($wheres as $k => $v) {
$query .= '`'.$k.'`=:where_'.$k.' '.$clause.' ';
}
$query = rtrim($query, $clause.' ');
self::validateClause($clause, __METHOD__);
try {
$db = self::getInstance();
$db->query($query);
foreach($wheres as $k => $v) {
$db->bind(':where_'.$k, $v);
}
return $db->exec() ? $db->rowCount() : false;
} catch(Exception $e) {
throw new DBException($e->getMessage(), 400);
}
$table = DB::getTable($table);
$query = 'DELETE FROM `'.$table.'` WHERE ';
}
$table_fields = array();
foreach ($values as $k => $v) {
$query .= '`'.$k.'`=:'.$k.' '.$clause.' ';
}
$query = rtrim($query, $clause.' ');
/**
* Delete row(s) from table
* Returns the number of affected rows or false
*/
public static function delete($table, $values, $clause='AND') {
try {
$db = self::getInstance();
$db->query($query);
foreach ($values as $k => $v) {
$db->bind(':'.$k, $v);
}
return $db->exec() ? $db->rowCount() : false;
} catch (Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
if(!is_array($values)) {
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
}
self::validateClause($clause, __METHOD__);
$table = DB::getTable($table);
$query = 'DELETE FROM `'.$table.'` WHERE ';
$table_fields = array();
foreach($values as $k => $v) {
$query .= '`'.$k.'`=:'.$k.' '.$clause.' ';
}
$query = rtrim($query, $clause.' ');
try {
$db = self::getInstance();
$db->query($query);
foreach($values as $k => $v) {
$db->bind(':'.$k, $v);
}
return $db->exec() ? $db->rowCount() : FALSE;
} catch(Exception $e) {
throw new DBException($e->getMessage(), 400);
}
}
/**
* Validate clause
*/
private static function validateClause($clause, $method=NULL) {
if(!is_null($clause)) {
$clause = strtoupper($clause);
if(!in_array($clause, ['AND', 'OR'])) {
throw new DBException('Expecting clause string \'AND\' or \'OR\' in ' . (!is_null($method) ? $method : __CLASS__), 100);
}
}
}
/**
* Validate clause
*/
private static function validateClause($clause, $method=null)
{
if (!is_null($clause)) {
$clause = strtoupper($clause);
if (!in_array($clause, ['AND', 'OR'])) {
throw new DBException('Expecting clause string \'AND\' or \'OR\' in ' . (!is_null($method) ? $method : __CLASS__), 100);
}
}
}
}
// DB class own Exception
class DBException extends Exception
{
}
class DBException extends Exception {}

File diff suppressed because it is too large Load Diff

View File

@ -310,12 +310,9 @@ namespace G {
*/
function abbreviate_number($number)
{
if ($number === null) {
$number = 0;
} else {
// strip any formatting
$number = (0+str_replace(',', '', $number));
}
// strip any formatting
$number = (0+str_replace(',', '', $number));
// Not a number, keep it "as is"
if (!is_numeric($number) or $number == 0) {
@ -563,7 +560,7 @@ namespace G {
function exception_to_error($e, $die=true)
{
$internal_code = 500;
$internal_error = '<b>Aw, snap!</b> ' . get_set_status_header_desc($internal_code) . ' - Check your error_log or enable debug_mode = 3 (chevereto.com/docs/debug).';
$internal_error = '<b>'.G_APP_NAME.' error:</b> ' . get_set_status_header_desc($internal_code);
set_status_header($internal_code);
@ -819,20 +816,18 @@ namespace G {
function get_client_ip()
{
if(isset($_SERVER['G_CLIENT_IP'])) {
return $_SERVER['G_CLIENT_IP'];
$client_ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : (!empty($_ENV['REMOTE_ADDR']) ? $_ENV['REMOTE_ADDR'] : null);
if (array_key_exists('HTTP_CF_CONNECTING_IP', $_SERVER) && $_SERVER['HTTP_CF_CONNECTING_IP'] == $_SERVER['REMOTE_ADDR']) {
return $_SERVER['HTTP_CF_CONNECTING_IP'];
}
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
$client_ip = $_SERVER['HTTP_CF_CONNECTING_IP'];
} else {
$client_ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
}
if (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $client_ip != $_SERVER['HTTP_X_FORWARDED_FOR']) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$entries = preg_split('/[\s,]/', $_SERVER['HTTP_X_FORWARDED_FOR'], -1, PREG_SPLIT_NO_EMPTY);
reset($entries);
foreach ($entries as $entry) {
while (list(, $entry) = each($entries)) {
$entry = trim($entry);
if (preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/', $entry, $ip_list)) {
$private_ip = array(
@ -843,6 +838,7 @@ namespace G {
'/^10\..*/');
$found_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);
if ($client_ip != $found_ip) { // and !isset($_SERVER['HTTP_CF_CONNECTING_IP']
$client_ip = $found_ip;
break;
@ -850,7 +846,7 @@ namespace G {
}
}
}
$_SERVER['G_CLIENT_IP'] = $client_ip;
return $client_ip;
}
@ -1133,23 +1129,6 @@ namespace G {
return $path;
}
function rrmdir($dir)
{
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (is_dir($dir."/".$object)) {
rrmdir($dir."/".$object);
} else {
unlink($dir."/".$object);
}
}
}
rmdir($dir);
}
}
/**
* Returns a sanitized string, typically for URLs
* This function was borrowed from chyrp.net (MIT License)
@ -1459,7 +1438,7 @@ namespace G {
function relative_to_url($filepath, $root_url=null)
{
if (!check_value($root_url)) {
$root_url = get_root_url();
$root_url = G_ROOT_URL;
}
return str_replace(G_ROOT_PATH_RELATIVE, $root_url, forward_slash($filepath));
}
@ -1468,7 +1447,7 @@ namespace G {
function url_to_relative($url, $root_url=null)
{
if (!check_value($root_url)) {
$root_url = get_root_url();
$root_url = G_ROOT_URL;
}
return str_replace($root_url, G_ROOT_PATH_RELATIVE, $url);
}
@ -1483,7 +1462,7 @@ namespace G {
function absolute_to_url($filepath, $root_url=null)
{
if (!check_value($root_url)) {
$root_url = get_root_url();
$root_url = G_ROOT_URL;
}
if (G_ROOT_PATH === G_ROOT_PATH_RELATIVE) {
return $root_url . ltrim($filepath, '/');
@ -1495,7 +1474,7 @@ namespace G {
function url_to_absolute($url, $root_url=null)
{
if (!check_value($root_url)) {
$root_url = get_root_url();
$root_url = G_ROOT_URL;
}
return str_replace($root_url, G_ROOT_PATH, $url);
}
@ -1529,43 +1508,21 @@ namespace G {
return get_global('settings')[$key];
}
function get_domain()
{
return HTTP_HOST;
}
function get_base_url($path='')
{
$path = sanitize_relative_path($path);
$return = get_root_url() . ltrim($path, '/');
$return = G_ROOT_URL . ltrim($path, '/');
return rtrim($return, '/');
}
function get_host()
function get_current_url()
{
return defined('APP_G_HTTP_HOST') ? APP_G_HTTP_HOST : G_HTTP_HOST;
}
function get_root_url()
{
return defined('APP_G_ROOT_URL') ? APP_G_ROOT_URL : G_ROOT_URL;
}
/**
* @param string Querystring keys to remove (comma separated)
*/
function get_current_url($safe=true, $removeQs=[])
{
$request_uri = $_SERVER['REQUEST_URI'];
$request_path = rtrim(strtok($request_uri, '?'), '/');
if ($_SERVER['QUERY_STRING'] && $removeQs) {
parse_str($_SERVER['QUERY_STRING'], $parse);
foreach ($removeQs as $v) {
unset($parse[$v]);
}
$querystring = $parse ? http_build_query($parse) : null;
$request_uri = $request_path;
if ($querystring) {
$request_uri .= '/?' . $querystring;
}
}
$path = preg_replace('#'.G_ROOT_PATH_RELATIVE.'#', '', rtrim($request_uri, '/') . '/', 1);
return get_base_url($path);
return get_base_url(preg_replace('#'.G_ROOT_PATH_RELATIVE.'#', '', $_SERVER['REQUEST_URI'], 1));
}
function settings_has_db_info()
@ -1937,26 +1894,9 @@ namespace G {
return basename($file);
}
function get_basename_without_extension($filename)
function get_filename_without_extension($file)
{
$extension = pathinfo($filename, PATHINFO_EXTENSION);
$filename = basename($filename);
return str_replace_last(".$extension", null, $filename);
}
function get_pathname_without_extension($filename)
{
$extension = pathinfo($filename, PATHINFO_EXTENSION);
return str_replace_last(".$extension", null, $filename);
}
function change_pathname_extension($filename, $extension)
{
$chop = get_pathname_without_extension($filename);
if ($chop == $filename) {
return $filename;
}
return "$chop.$extension";
return preg_replace('/\\.[^.\\s]{2,4}$/', '', basename($file));
}
/**
@ -2262,9 +2202,9 @@ namespace G {
// https://github.com/Chevereto/Chevereto-Free/pull/35
function imagecreatefrombmp($file)
{
// if (function_exists('imagecreatefrombmp')) {
// return imagecreatefrombmp($file);
// }
if (function_exists('imagecreatefrombmp')) {
return imagecreatefrombmp($file);
}
// version 1.00
if (!($fh = fopen($file, 'rb'))) {
trigger_error('imagecreatefrombmp: Can not open ' . $file, E_USER_WARNING);
@ -2585,126 +2525,6 @@ namespace G {
return trim(preg_replace('/\s*(?:\*\/|\?>).*/', '', $string));
}
/**
* function xml2array
*
* This function is part of the PHP manual.
*
* The PHP manual text and comments are covered by the Creative Commons
* Attribution 3.0 License, copyright (c) the PHP Documentation Group
*
* @author k dot antczak at livedata dot pl
* @date 2011-04-22 06:08 UTC
* @link http://www.php.net/manual/en/ref.simplexml.php#103617
* @license http://www.php.net/license/index.php#doc-lic
* @license http://creativecommons.org/licenses/by/3.0/
* @license CC-BY-3.0 <http://spdx.org/licenses/CC-BY-3.0>
*/
function xml2array($xmlObject, $out = array())
{
foreach ((array) $xmlObject as $index => $node) {
$out[$index] = (is_object($node)) ? xml2array($node) : $node;
}
return $out;
}
/**
* @param string $domain Pass $_SERVER['SERVER_NAME'] here
* @param bool $debug
*
* @debug bool $debug
* @return string
*
* @link https://gist.github.com/pocesar/5366899
*/
function get_domain($domain, $debug = false)
{
$original = $domain = strtolower($domain);
if (filter_var($domain, FILTER_VALIDATE_IP)) { return $domain; }
$debug ? print('<strong style="color:green">&raquo;</strong> Parsing: '.$original) : false;
$arr = array_slice(array_filter(explode('.', $domain, 4), function($value){
return $value !== 'www';
}), 0); //rebuild array indexes
if (count($arr) > 2)
{
$count = count($arr);
$_sub = explode('.', $count === 4 ? $arr[3] : $arr[2]);
$debug ? print(" (parts count: {$count})") : false;
if (count($_sub) === 2) // two level TLD
{
$removed = array_shift($arr);
if ($count === 4) // got a subdomain acting as a domain
{
$removed = array_shift($arr);
}
$debug ? print("<br>\n" . '[*] Two level TLD: <strong>' . join('.', $_sub) . '</strong> ') : false;
}
elseif (count($_sub) === 1) // one level TLD
{
$removed = array_shift($arr); //remove the subdomain
if (strlen($_sub[0]) === 2 && $count === 3) // TLD domain must be 2 letters
{
array_unshift($arr, $removed);
}
else
{
// non country TLD according to IANA
$tlds = array(
'aero',
'arpa',
'asia',
'biz',
'cat',
'com',
'coop',
'edu',
'gov',
'info',
'jobs',
'mil',
'mobi',
'museum',
'name',
'net',
'org',
'post',
'pro',
'tel',
'travel',
'xxx',
);
if (count($arr) > 2 && in_array($_sub[0], $tlds) !== false) //special TLD don't have a country
{
array_shift($arr);
}
}
$debug ? print("<br>\n" .'[*] One level TLD: <strong>'.join('.', $_sub).'</strong> ') : false;
}
else // more than 3 levels, something is wrong
{
for ($i = count($_sub); $i > 1; $i--)
{
$removed = array_shift($arr);
}
$debug ? print("<br>\n" . '[*] Three level TLD: <strong>' . join('.', $_sub) . '</strong> ') : false;
}
}
elseif (count($arr) === 2)
{
$arr0 = array_shift($arr);
if (strpos(join('.', $arr), '.') === false
&& in_array($arr[0], array('localhost','test','invalid')) === false) // not a reserved domain
{
$debug ? print("<br>\n" .'Seems invalid domain: <strong>'.join('.', $arr).'</strong> re-adding: <strong>'.$arr0.'</strong> ') : false;
// seems invalid domain, restore it
array_unshift($arr, $arr0);
}
}
$debug ? print("<br>\n".'<strong style="color:gray">&laquo;</strong> Done parsing: <span style="color:red">' . $original . '</span> as <span style="color:blue">'. join('.', $arr) ."</span><br>\n") : false;
return join('.', $arr);
}
} // G Namespace
// Global namespace
@ -2947,4 +2767,5 @@ namespace {
return $status === 0;
}
}
}

View File

@ -8,14 +8,13 @@
@author Rodolfo Berrios A. <http://rodolfoberrios.com/>
Copyright (c) Rodolfo Berrios <inbox@rodolfoberrios.com> All rights reserved.
Licensed under the MIT license
http://opensource.org/licenses/MIT
--------------------------------------------------------------------- */
namespace G\Render;
use G;
/**
@ -23,38 +22,34 @@ use G;
* ---------------------------------------------------------------------
*/
function include_theme_file($filename, $args=[])
{
$file = G_APP_PATH_THEME . $filename;
$override = G_APP_PATH_THEME . 'overrides/' . $filename;
if (!file_exists($file)) {
$file .= '.php';
$override .= '.php';
}
if (file_exists($override)) {
$file = $override;
}
if (file_exists($file)) {
$GLOBALS['theme_include_args'] = $args;
include($file);
unset($GLOBALS['theme_include_args']);
}
function include_theme_file($filename, $args=[]) {
$file = G_APP_PATH_THEME . $filename;
$override = G_APP_PATH_THEME . 'overrides/' . $filename;
if(!file_exists($file)) {
$file .= '.php';
$override .= '.php';
}
if(file_exists($override)) {
$file = $override;
}
if(file_exists($file)) {
$GLOBALS['theme_include_args'] = $args;
include($file);
unset($GLOBALS['theme_include_args']);
}
}
function include_theme_header()
{
include_theme_file('header');
function include_theme_header() {
include_theme_file('header');
}
function include_theme_footer()
{
include_theme_file('footer');
function include_theme_footer() {
include_theme_file('footer');
}
function get_theme_file_contents($filename)
{
$file = G_APP_PATH_THEME . $filename;
return file_exists($file) ? file_get_contents($file) : null;
function get_theme_file_contents($filename) {
$file = G_APP_PATH_THEME . $filename;
return file_exists($file) ? file_get_contents($file) : null;
}
/**
@ -62,9 +57,8 @@ function get_theme_file_contents($filename)
* ---------------------------------------------------------------------
*/
function get_theme_file_url($string)
{
return BASE_URL_THEME . $string;
function get_theme_file_url($string) {
return BASE_URL_THEME . $string;
}
/**
@ -73,15 +67,13 @@ function get_theme_file_url($string)
*/
// Return app lib file url
function get_app_lib_file_url($string)
{
return (defined('APP_G_APP_LIB_URL') ? APP_G_APP_LIB_URL : G_APP_LIB_URL) . $string;
function get_app_lib_file_url($string){
return G_APP_LIB_URL . $string;
}
// Returns the HTML input with the auth token
function get_input_auth_token($name='auth_token')
{
return '<input type="hidden" name="'.$name.'" value="'. G\Handler::getAuthToken() . '">';
function get_input_auth_token($name='auth_token') {
return '<input type="hidden" name="'.$name.'" value="'.G\Handler::getAuthToken().'">';
}
@ -91,84 +83,80 @@ function get_input_auth_token($name='auth_token')
*/
// Outputs the REST_API array to xml
function xml_output($array=array())
{
error_reporting(0);
//@ini_set('display_errors', false);
if (ob_get_level() === 0 and !ob_start('ob_gzhandler')) {
ob_start();
}
header("Last-Modified: ".gmdate("D, d M Y H:i:s")."GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Type:text/xml; charset=UTF-8");
$out = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$out .= "<response>\n";
$out .= " <status_code>$array[status_code]</status_code>\n";
$out .= " <status_txt>$array[status_txt]</status_txt>\n";
if (count($array["data"])>0) {
$out .= " <data>\n";
foreach ($array["data"] as $key => $value) {
$out .= " <$key>$value</$key>\n";
}
$out .= " </data>\n";
}
$out .= "</response>";
echo $out;
function xml_output($array=array()) {
error_reporting(0);
//@ini_set('display_errors', false);
if(ob_get_level() === 0 and !ob_start('ob_gzhandler')) {
ob_start();
}
header("Last-Modified: ".gmdate("D, d M Y H:i:s")."GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Type:text/xml; charset=UTF-8");
$out = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
$out .= "<response>\n";
$out .= " <status_code>$array[status_code]</status_code>\n";
$out .= " <status_txt>$array[status_txt]</status_txt>\n";
if(count($array["data"])>0) {
$out .= " <data>\n";
foreach($array["data"] as $key => $value) {
$out .= " <$key>$value</$key>\n";
}
$out .= " </data>\n";
}
$out .= "</response>";
echo $out;
}
// Procedural function to output an array to json
function json_output($data=[], $callback=null)
{
error_reporting(0);
//@ini_set('display_errors', false);
if (ob_get_level() === 0 and !ob_start('ob_gzhandler')) {
ob_start();
}
header('Last-Modified: '.gmdate('D, d M Y H:i:s').'GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-type: application/json; charset=UTF-8');
// Invalid json request
if (!G\check_value($data) || (G\check_value($callback) and preg_match('/\W/', $callback))) {
G\set_status_header(400);
$json_fail = [
'status_code' => 400,
'status_txt' => G\get_set_status_header_desc(400),
'error' => [
'message' => 'no request data present',
'code' => null
]
];
die(json_encode($json_fail));
}
// Populate missing values
if ($data['status_code'] && !$data['status_txt']) {
$data['status_txt'] = G\get_set_status_header_desc($data['status_code']);
}
$json_encode = json_encode($data);
if (!$json_encode) { // Json failed
G\set_status_header(500);
$json_fail = [
'status_code' => 500,
'status_txt' => G\get_set_status_header_desc(500),
'error' => [
'message' => "data couldn't be encoded into json",
'code' => null
]
];
die(json_encode($json_fail));
}
G\set_status_header($data['status_code']);
if (!is_null($callback)) {
print sprintf('%s(%s);', $callback, $json_encode);
} else {
print $json_encode;
}
die();
}
function json_output($data=[], $callback=NULL) {
error_reporting(0);
//@ini_set('display_errors', false);
if(ob_get_level() === 0 and !ob_start('ob_gzhandler')) ob_start();
header('Last-Modified: '.gmdate('D, d M Y H:i:s').'GMT');
header('Cache-Control: no-cache, must-revalidate');
header('Pragma: no-cache');
header('Content-type: application/json; charset=UTF-8');
// Invalid json request
if(!G\check_value($data) || (G\check_value($callback) and preg_match('/\W/', $callback))) {
G\set_status_header(400);
$json_fail = [
'status_code' => 400,
'status_txt' => G\get_set_status_header_desc(400),
'error' => [
'message' => 'no request data present',
'code' => NULL
]
];
die(json_encode($json_fail));
}
// Populate missing values
if($data['status_code'] && !$data['status_txt']){
$data['status_txt'] = G\get_set_status_header_desc($data['status_code']);
}
$json_encode = json_encode($data);
if(!$json_encode) { // Json failed
G\set_status_header(500);
$json_fail = [
'status_code' => 500,
'status_txt' => G\get_set_status_header_desc(500),
'error' => [
'message' => "data couldn't be encoded into json",
'code' => NULL
]
];
die(json_encode($json_fail));
}
G\set_status_header($data['status_code']);
if(!is_null($callback)) {
print sprintf('%s(%s);', $callback, $json_encode);
} else {
print $json_encode;
}
die();
}