parent
f33b7e1a50
commit
c9998cfb06
|
@ -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);
|
||||
|
|
|
@ -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 = [];
|
||||
|
|
32
lib/G/G.php
32
lib/G/G.php
|
@ -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
|
||||
|
@ -54,9 +52,7 @@ 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();
|
||||
|
@ -71,29 +67,21 @@ if ($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(!$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));
|
||||
|
@ -122,7 +110,7 @@ if (isset($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
|
||||
|
||||
|
@ -141,7 +129,7 @@ if (file_exists(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);
|
||||
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
|
||||
|
|
|
@ -20,13 +20,10 @@
|
|||
*/
|
||||
|
||||
namespace G;
|
||||
use PDO, PDOException, Exception;
|
||||
|
||||
use PDO;
|
||||
use PDOException;
|
||||
use Exception;
|
||||
class DB {
|
||||
|
||||
class DB
|
||||
{
|
||||
private static $instance;
|
||||
|
||||
private $host = G_APP_DB_HOST;
|
||||
|
@ -37,19 +34,19 @@ class DB
|
|||
private $driver = G_APP_DB_DRIVER;
|
||||
private $pdo_attrs = G_APP_DB_PDO_ATTRS;
|
||||
|
||||
public static $dbh;
|
||||
static $dbh;
|
||||
public $query;
|
||||
|
||||
/**
|
||||
* Connect to the DB server
|
||||
* Throws an Exception on error (tay weando? en serio?)
|
||||
*/
|
||||
public function __construct($conn=[])
|
||||
{
|
||||
public function __construct($conn=[]) {
|
||||
|
||||
try {
|
||||
// PDO already connected
|
||||
if(empty($conn) and isset(self::$dbh) and get_class(self::$dbh) == 'PDO') {
|
||||
return true;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
if(!empty($conn)) {
|
||||
|
@ -63,13 +60,13 @@ class DB
|
|||
if($this->port) {
|
||||
$pdo_connect .= ';port=' . $this->port;
|
||||
}
|
||||
// $pdo_connect .= ';charset=UTF8';
|
||||
|
||||
$this->pdo_attrs = @unserialize($this->pdo_attrs) ?: $this->pdo_attrs;
|
||||
|
||||
// PDO defaults
|
||||
$this->pdo_default_attrs = [
|
||||
PDO::ATTR_TIMEOUT => 30,
|
||||
//PDO::ATTR_PERSISTENT => FALSE
|
||||
];
|
||||
|
||||
// Override PDO defaults ?
|
||||
|
@ -77,7 +74,7 @@ class DB
|
|||
|
||||
// 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
|
||||
$this->pdo_attrs[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET NAMES 'UTF8'";
|
||||
|
||||
// Turn off PHP error reporting just for the connection here (invalid host names will trigger a PHP warning)
|
||||
$error_reporting = error_reporting();
|
||||
|
@ -95,18 +92,19 @@ class DB
|
|||
}
|
||||
|
||||
self::$instance = $this;
|
||||
|
||||
} catch(Exception $e) {
|
||||
self::$dbh = null;
|
||||
self::$dbh = NULL;
|
||||
throw new DBException($e->getMessage(), 400);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Singleton instance handler
|
||||
* Used for the static methods of this class
|
||||
*/
|
||||
public static function getInstance()
|
||||
{
|
||||
public static function getInstance() {
|
||||
if(is_null(self::$instance)) {
|
||||
self::$instance = new self;
|
||||
}
|
||||
|
@ -117,8 +115,7 @@ class DB
|
|||
* 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)
|
||||
{
|
||||
public function setPDOAttrs($attributes) {
|
||||
$this->pdo_attrs = $attributes;
|
||||
}
|
||||
|
||||
|
@ -126,13 +123,11 @@ class DB
|
|||
* 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)
|
||||
{
|
||||
public function setPDOAttr($key, $value) {
|
||||
$this->pdo_attrs[$key] = $value;
|
||||
}
|
||||
|
||||
public function getAttr($attr)
|
||||
{
|
||||
public function getAttr($attr) {
|
||||
return self::$dbh->getAttribute($attr);
|
||||
}
|
||||
|
||||
|
@ -140,13 +135,11 @@ class DB
|
|||
* Prepares an SQL statement to be executed by the PDOStatement::execute() method
|
||||
* http://php.net/manual/en/pdo.prepare.php
|
||||
*/
|
||||
public function query($query)
|
||||
{
|
||||
public function query($query) {
|
||||
$this->query = self::$dbh->prepare($query);
|
||||
}
|
||||
|
||||
public function errorInfo()
|
||||
{
|
||||
public function errorInfo() {
|
||||
return self::$dbh->errorInfo();
|
||||
}
|
||||
|
||||
|
@ -154,8 +147,7 @@ class DB
|
|||
* 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)
|
||||
{
|
||||
public function bind($param, $value, $type = null) {
|
||||
if(is_null($type)) {
|
||||
switch(true) {
|
||||
case is_int($value):
|
||||
|
@ -175,23 +167,19 @@ class DB
|
|||
$this->query->bindValue($param, $value, $type);
|
||||
}
|
||||
|
||||
public function exec()
|
||||
{
|
||||
public function exec() {
|
||||
return $this->query->execute();
|
||||
}
|
||||
|
||||
public function fetchColumn()
|
||||
{
|
||||
public function fetchColumn() {
|
||||
return $this->query->fetchColumn();
|
||||
}
|
||||
|
||||
public function closeCursor()
|
||||
{
|
||||
public function closeCursor() {
|
||||
return $this->query->closeCursor();
|
||||
}
|
||||
|
||||
public function fetchAll($mode=PDO::FETCH_ASSOC)
|
||||
{
|
||||
public function fetchAll($mode=PDO::FETCH_ASSOC) {
|
||||
$this->exec();
|
||||
return $this->query->fetchAll(is_int($mode) ? $mode : PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
@ -200,8 +188,7 @@ class DB
|
|||
* 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)
|
||||
{
|
||||
public function fetchSingle($mode=PDO::FETCH_ASSOC) {
|
||||
$this->exec();
|
||||
return $this->query->fetch(is_int($mode) ? $mode : PDO::FETCH_ASSOC);
|
||||
}
|
||||
|
@ -209,12 +196,11 @@ class DB
|
|||
/**
|
||||
* Query and exec, return number of affected rows or FALSE
|
||||
*/
|
||||
public static function queryExec($query)
|
||||
{
|
||||
public static function queryExec($query) {
|
||||
try {
|
||||
$db = self::getInstance();
|
||||
$db->query($query);
|
||||
return $db->exec() ? $db->rowCount() : false;
|
||||
return $db->exec() ? $db->rowCount() : FALSE;
|
||||
} catch(Exception $e) {
|
||||
throw new DBException($e->getMessage(), 400);
|
||||
}
|
||||
|
@ -223,8 +209,7 @@ class DB
|
|||
/**
|
||||
* Query and fetch single record
|
||||
*/
|
||||
public static function queryFetchSingle($query, $fetch_style=null)
|
||||
{
|
||||
public static function queryFetchSingle($query, $fetch_style=NULL) {
|
||||
try {
|
||||
return self::queryFetch($query, 1, $fetch_style);
|
||||
} catch(Exception $e) {
|
||||
|
@ -235,10 +220,9 @@ class DB
|
|||
/**
|
||||
* Query and fetch all records
|
||||
*/
|
||||
public static function queryFetchAll($query, $fetch_style=null)
|
||||
{
|
||||
public static function queryFetchAll($query, $fetch_style=NULL) {
|
||||
try {
|
||||
return self::queryFetch($query, null, $fetch_style);
|
||||
return self::queryFetch($query, NULL, $fetch_style);
|
||||
} catch(Exception $e) {
|
||||
throw new DBException($e->getMessage(), 400);
|
||||
}
|
||||
|
@ -247,8 +231,7 @@ class DB
|
|||
/**
|
||||
* Query fetch (core version)
|
||||
*/
|
||||
public static function queryFetch($query, $limit=1, $fetch_style=null)
|
||||
{
|
||||
public static function queryFetch($query, $limit=1, $fetch_style=NULL) {
|
||||
try {
|
||||
$db = self::getInstance();
|
||||
$db->query($query);
|
||||
|
@ -262,8 +245,7 @@ class DB
|
|||
* 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()
|
||||
{
|
||||
public function rowCount() {
|
||||
return $this->query->rowCount();
|
||||
}
|
||||
|
||||
|
@ -271,8 +253,7 @@ class DB
|
|||
* 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()
|
||||
{
|
||||
public function lastInsertId() {
|
||||
return self::$dbh->lastInsertId();
|
||||
}
|
||||
|
||||
|
@ -280,8 +261,7 @@ class DB
|
|||
* Turns off autocommit mode
|
||||
* http://php.net/manual/en/pdo.begintransaction.php
|
||||
*/
|
||||
public function beginTransaction()
|
||||
{
|
||||
public function beginTransaction(){
|
||||
return self::$dbh->beginTransaction();
|
||||
}
|
||||
|
||||
|
@ -289,8 +269,7 @@ class DB
|
|||
* 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()
|
||||
{
|
||||
public function endTransaction(){
|
||||
return self::$dbh->commit();
|
||||
}
|
||||
|
||||
|
@ -298,8 +277,7 @@ class DB
|
|||
* Rolls back the current transaction, as initiated by PDO::beginTransaction()
|
||||
* http://php.net/manual/en/pdo.rollback.php
|
||||
*/
|
||||
public function cancelTransaction()
|
||||
{
|
||||
public function cancelTransaction(){
|
||||
return self::$dbh->rollBack();
|
||||
}
|
||||
|
||||
|
@ -307,8 +285,7 @@ class DB
|
|||
* Dumps the informations contained by a prepared statement directly on the output
|
||||
* http://php.net/manual/en/pdostatement.debugdumpparams.php
|
||||
*/
|
||||
public function debugDumpParams()
|
||||
{
|
||||
public function debugDumpParams(){
|
||||
return $this->query->debugDumpParams();
|
||||
}
|
||||
|
||||
|
@ -317,16 +294,15 @@ class DB
|
|||
/**
|
||||
* Get the table with its prefix
|
||||
*/
|
||||
public static function getTable($table)
|
||||
{
|
||||
public static function getTable($table) {
|
||||
return get_app_setting('db_table_prefix') . $table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get values from DB
|
||||
*/
|
||||
public static function get($table, $values, $clause='AND', $sort=[], $limit=null, $fetch_style=null)
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
@ -391,8 +367,8 @@ class DB
|
|||
* Update target table row(s)
|
||||
* Returns the number of affected rows or false
|
||||
*/
|
||||
public static function update($table, $values, $wheres, $clause='AND')
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
@ -430,17 +406,18 @@ class DB
|
|||
$db->bind(':where_'.$k, $v);
|
||||
}
|
||||
|
||||
return $db->exec() ? $db->rowCount() : false;
|
||||
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)
|
||||
{
|
||||
public static function insert($table, $values) {
|
||||
|
||||
if(!is_array($values)) {
|
||||
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
|
||||
}
|
||||
|
@ -462,10 +439,11 @@ class DB
|
|||
foreach($values as $k => $v) {
|
||||
$db->bind(':'.$k, $v);
|
||||
}
|
||||
return $db->exec() ? $db->lastInsertId() : false;
|
||||
return $db->exec() ? $db->lastInsertId() : FALSE;
|
||||
} catch(Exception $e) {
|
||||
throw new DBException($e->getMessage(), 400);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -473,8 +451,8 @@ class DB
|
|||
* 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')
|
||||
{
|
||||
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);
|
||||
|
@ -514,14 +492,15 @@ class DB
|
|||
} catch(Exception $e) {
|
||||
throw new DBException($e->getMessage(), 400);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete row(s) from table
|
||||
* Returns the number of affected rows or false
|
||||
*/
|
||||
public static function delete($table, $values, $clause='AND')
|
||||
{
|
||||
public static function delete($table, $values, $clause='AND') {
|
||||
|
||||
if(!is_array($values)) {
|
||||
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
|
||||
}
|
||||
|
@ -543,17 +522,17 @@ class DB
|
|||
foreach($values as $k => $v) {
|
||||
$db->bind(':'.$k, $v);
|
||||
}
|
||||
return $db->exec() ? $db->rowCount() : false;
|
||||
return $db->exec() ? $db->rowCount() : FALSE;
|
||||
} catch(Exception $e) {
|
||||
throw new DBException($e->getMessage(), 400);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate clause
|
||||
*/
|
||||
private static function validateClause($clause, $method=null)
|
||||
{
|
||||
private static function validateClause($clause, $method=NULL) {
|
||||
if(!is_null($clause)) {
|
||||
$clause = strtoupper($clause);
|
||||
if(!in_array($clause, ['AND', 'OR'])) {
|
||||
|
@ -561,9 +540,8 @@ class DB
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// DB class own Exception
|
||||
class DBException extends Exception
|
||||
{
|
||||
}
|
||||
class DBException extends Exception {}
|
|
@ -20,35 +20,24 @@
|
|||
*/
|
||||
|
||||
namespace G;
|
||||
|
||||
use Exception;
|
||||
|
||||
class Handler
|
||||
{
|
||||
public static $route;
|
||||
public static $route_request;
|
||||
public static $route_name;
|
||||
public static $base_request;
|
||||
public static $doctitle;
|
||||
public static $vars;
|
||||
public static $conds;
|
||||
public static $routes;
|
||||
public static $template_used;
|
||||
public static $prevented_route;
|
||||
public static $mapped_args;
|
||||
class Handler {
|
||||
|
||||
public static $route, $route_request, $route_name, $base_request, $doctitle, $vars, $conds, $routes, $template_used, $prevented_route, $mapped_args;
|
||||
|
||||
/**
|
||||
* Build a valid request
|
||||
*/
|
||||
public function __construct($hook=[])
|
||||
{
|
||||
function __construct($hook=[]) {
|
||||
|
||||
if(!defined('G_APP_PATH_THEME')) {
|
||||
throw new HandlerException('G_APP_PATH_THEME is not defined', 100);
|
||||
}
|
||||
|
||||
// Parse the definitions to this object.. This is not necessary but in case of changes...
|
||||
$this->relative_root = G_ROOT_PATH_RELATIVE; // nota: realmente necesitamos estos this?
|
||||
$this->base_url = get_root_url();
|
||||
$this->base_url = G_ROOT_URL;
|
||||
$this->path_theme = G_APP_PATH_THEME;
|
||||
|
||||
// Parse the request
|
||||
|
@ -65,10 +54,10 @@ class Handler
|
|||
|
||||
if(!empty($_SERVER['QUERY_STRING'])) {
|
||||
$this->request_uri = $_SERVER['REQUEST_URI'];
|
||||
$this->valid_request .= /*'/' .*/ $query_string;
|
||||
$this->valid_request .= '/' . $query_string;
|
||||
}
|
||||
|
||||
// Store the canonical request, used for redirect to a valid request
|
||||
// Store the canonical request, useful for redirect to a valid request
|
||||
$this->canonical_request = $this->valid_request;
|
||||
|
||||
if(is_dir(G_ROOT_PATH . $this->valid_request) && $this->valid_request !== '/') {
|
||||
|
@ -128,9 +117,7 @@ class Handler
|
|||
}
|
||||
|
||||
// It is a valid request on index.php?
|
||||
if ($this->isIndex()) {
|
||||
$this->processRequest();
|
||||
}
|
||||
if($this->isIndex()) $this->processRequest();
|
||||
|
||||
// Hook a fn AFTER the process
|
||||
if(is_array($hook) and is_callable($hook['after'])) {
|
||||
|
@ -151,22 +138,20 @@ class Handler
|
|||
}
|
||||
|
||||
$this->loadTemplate();
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over the route app folder
|
||||
* This populates Handler::$routes with all the valid routes
|
||||
*/
|
||||
private static function routeIterator($path)
|
||||
{
|
||||
if (!file_exists($path)) {
|
||||
return;
|
||||
}
|
||||
private static function routeIterator($path) {
|
||||
|
||||
if(!file_exists($path)) return;
|
||||
|
||||
foreach(new \DirectoryIterator($path) as $fileInfo) {
|
||||
if ($fileInfo->isDot() or $fileInfo->isDir()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if($fileInfo->isDot() or $fileInfo->isDir()) continue;
|
||||
|
||||
$route_file = $path . $fileInfo->getFilename();
|
||||
$route_override = $path . 'overrides/' . $fileInfo->getFilename();
|
||||
|
@ -187,8 +172,7 @@ class Handler
|
|||
* Stock (save) the valid routes of the G\ app
|
||||
* This method is optional because the routeIterator takes some memory
|
||||
*/
|
||||
public static function stockRoutes()
|
||||
{
|
||||
public static function stockRoutes() {
|
||||
self::$routes = [];
|
||||
self::routeIterator(G_APP_PATH_ROUTES);
|
||||
self::routeIterator(G_APP_PATH_ROUTES_OVERRIDES);
|
||||
|
@ -197,8 +181,8 @@ class Handler
|
|||
/**
|
||||
* Process the dynamic request
|
||||
*/
|
||||
private function processRequest()
|
||||
{
|
||||
private function processRequest() {
|
||||
|
||||
if(is_null(self::$routes)) { // Route array is not set
|
||||
$route = $this->getRouteFn(self::$base_request);
|
||||
if(is_callable($route)) {
|
||||
|
@ -212,12 +196,12 @@ class Handler
|
|||
|
||||
// Autoset some magic
|
||||
$magic = array(
|
||||
'post' => $_POST ? $_POST : null,
|
||||
'get' => $_GET ? $_GET : null,
|
||||
'request' => $_REQUEST ? $_REQUEST : null,
|
||||
'safe_post' => $_POST ? safe_html($_POST) : null,
|
||||
'safe_get' => $_GET ? safe_html($_GET) : null,
|
||||
'safe_request' => $_REQUEST ? safe_html($_REQUEST) : null,
|
||||
'post' => $_POST ? $_POST : NULL,
|
||||
'get' => $_GET ? $_GET : NULL,
|
||||
'request' => $_REQUEST ? $_REQUEST : NULL,
|
||||
'safe_post' => $_POST ? safe_html($_POST) : NULL,
|
||||
'safe_get' => $_GET ? safe_html($_GET) : NULL,
|
||||
'safe_request' => $_REQUEST ? safe_html($_REQUEST) : NULL,
|
||||
'auth_token' => self::getAuthToken()
|
||||
);
|
||||
|
||||
|
@ -231,6 +215,7 @@ class Handler
|
|||
if(!self::$prevented_route and is_callable($routes[self::$base_request])) {
|
||||
$routes[self::$base_request]($this);
|
||||
}
|
||||
|
||||
} else {
|
||||
$this->issue404();
|
||||
$this->request = $this->request_array;
|
||||
|
@ -250,13 +235,13 @@ class Handler
|
|||
}
|
||||
|
||||
self::$template_used = $this->template;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind route var to global functions
|
||||
*/
|
||||
public function bindGetFn($var, $value)
|
||||
{
|
||||
public function bindGetFn($var, $value) {
|
||||
$fn_name = strtolower(str_replace('-', '_', $var));
|
||||
if(!function_exists('get_' . $fn_name)) {
|
||||
eval('function get_' . $fn_name . '(){ return G\Handler::$vars["' . $var . '"]; }');
|
||||
|
@ -266,8 +251,7 @@ class Handler
|
|||
/**
|
||||
* Bind route conditional to global functions
|
||||
*/
|
||||
public function bindIsFn($var, $value)
|
||||
{
|
||||
public function bindIsFn($var, $value) {
|
||||
$fn_name = strtolower(str_replace('-', '_', $var));
|
||||
if(!function_exists('is_' . $fn_name)) {
|
||||
eval('function is_' . $fn_name . '(){ return G\Handler::$conds["' . $var . '"]; }');
|
||||
|
@ -277,22 +261,19 @@ class Handler
|
|||
/**
|
||||
* Inject the 404 page
|
||||
*/
|
||||
public function issue404()
|
||||
{
|
||||
public function issue404() {
|
||||
set_status_header(404);
|
||||
if($this->getCond('mapped_route')) {
|
||||
self::$base_request = self::$route_request[0];
|
||||
self::$route_name = 404;
|
||||
}
|
||||
$this->is404 = true;
|
||||
$this->template = 404;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevent the rest of the execution loading the target view
|
||||
*/
|
||||
public function preventRoute($tpl=null)
|
||||
{
|
||||
public function preventRoute($tpl=NULL) {
|
||||
if($tpl) {
|
||||
$this->template = $tpl;
|
||||
}
|
||||
|
@ -303,8 +284,7 @@ class Handler
|
|||
* Get the route fn for a given route
|
||||
* If the route doesn't exists it will add it to the routes stack
|
||||
*/
|
||||
public function getRouteFn($route_name)
|
||||
{
|
||||
public function getRouteFn($route_name) {
|
||||
// Route is already in the stack
|
||||
if(is_array(self::$routes) and array_key_exists($route_name, Handler::$routes)) {
|
||||
return self::$routes[$route_name];
|
||||
|
@ -330,8 +310,7 @@ class Handler
|
|||
/**
|
||||
* Maps the current route which is useful to make route aliases
|
||||
*/
|
||||
public function mapRoute($route_name, $args=null)
|
||||
{
|
||||
public function mapRoute($route_name, $args=NULL) {
|
||||
$this->template = $route_name;
|
||||
self::$base_request = $route_name;
|
||||
self::setCond('mapped_route', true);
|
||||
|
@ -344,16 +323,14 @@ class Handler
|
|||
/**
|
||||
* Return (bool) the request level of the current request
|
||||
*/
|
||||
public function isRequestLevel($level)
|
||||
{
|
||||
public function isRequestLevel($level) {
|
||||
return isset($this->request_array[$level - 1]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Redirect to the base url/request
|
||||
*/
|
||||
public function baseRedirection($request)
|
||||
{
|
||||
public function baseRedirection($request) {
|
||||
$request = trim(sanitize_path_slashes($request), '/');
|
||||
$url = preg_replace('{'.$this->relative_root.'}', '/', $this->base_url, 1) . $request;
|
||||
redirect($url, 301);
|
||||
|
@ -362,8 +339,7 @@ class Handler
|
|||
/**
|
||||
* Return (bool) if the request is handled by index.php
|
||||
*/
|
||||
private function isIndex()
|
||||
{
|
||||
private function isIndex() {
|
||||
return preg_match('{/index.php$}', $this->script_name);
|
||||
}
|
||||
|
||||
|
@ -371,8 +347,7 @@ class Handler
|
|||
* Hook code for loadTemplate()
|
||||
* @args ['code' => '<code>', 'where' => 'before|after']
|
||||
*/
|
||||
public function hookTemplate($args=[])
|
||||
{
|
||||
public function hookTemplate($args=[]) {
|
||||
if(in_array($args['where'], ['before', 'after']) and $args['code']) {
|
||||
if(!isset($this->hook_template)) {
|
||||
$this->hook_template = [];
|
||||
|
@ -384,8 +359,7 @@ class Handler
|
|||
/**
|
||||
* load the setted (or argument) template view
|
||||
*/
|
||||
private function loadTemplate($template=null)
|
||||
{
|
||||
private function loadTemplate($template=NULL) {
|
||||
if(!is_null($template)) {
|
||||
$this->template = $template;
|
||||
}
|
||||
|
@ -448,8 +422,7 @@ class Handler
|
|||
/**
|
||||
* Returns the 40 char length safe request token
|
||||
*/
|
||||
public static function getAuthToken()
|
||||
{
|
||||
public static function getAuthToken() {
|
||||
$token = isset($_SESSION['G_auth_token']) ? $_SESSION['G_auth_token'] : random_string(40);
|
||||
$_SESSION['G_auth_token'] = $token;
|
||||
return $token;
|
||||
|
@ -458,27 +431,22 @@ class Handler
|
|||
/**
|
||||
* Checks the integrity and validation of the given request token
|
||||
*/
|
||||
public static function checkAuthToken($token)
|
||||
{
|
||||
if (strlen($token) < 40) {
|
||||
return false;
|
||||
}
|
||||
public static function checkAuthToken($token) {
|
||||
if(strlen($token) < 40) return false;
|
||||
return timing_safe_compare($_SESSION['G_auth_token'], $token);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a Handler::$var > get_var() binding
|
||||
*/
|
||||
public static function setVar($var, $value)
|
||||
{
|
||||
public static function setVar($var, $value) {
|
||||
self::$vars[$var] = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a multiple Handler::$var > get_var() binding
|
||||
*/
|
||||
public static function setVars($array)
|
||||
{
|
||||
public static function setVars($array) {
|
||||
foreach((array)$array as $var => $value) {
|
||||
self::$vars[$var] = $value;
|
||||
}
|
||||
|
@ -487,16 +455,14 @@ class Handler
|
|||
/**
|
||||
* Sets a Handler::$conds -> is_cond() binding
|
||||
*/
|
||||
public static function setCond($conds, $bool)
|
||||
{
|
||||
public static function setCond($conds, $bool) {
|
||||
self::$conds[$conds] = !$bool ? false : true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a multiple Handler::$conds -> is_cond() binding
|
||||
*/
|
||||
public static function setConds($array=[])
|
||||
{
|
||||
public static function setConds($array=[]) {
|
||||
foreach((array)$array as $conds => $bool) {
|
||||
self::$conds[$conds] = !$bool ? false : true;
|
||||
}
|
||||
|
@ -505,40 +471,35 @@ class Handler
|
|||
/**
|
||||
* Get a Handler::$vars[var]
|
||||
*/
|
||||
public static function getVar($var)
|
||||
{
|
||||
public static function getVar($var) {
|
||||
return self::getVars()[$var];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all Handler::$vars
|
||||
*/
|
||||
public static function getVars()
|
||||
{
|
||||
public static function getVars() {
|
||||
return self::$vars;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a Handler::$condss[cond]
|
||||
*/
|
||||
public static function getCond($cond)
|
||||
{
|
||||
public static function getCond($cond) {
|
||||
return self::getConds()[$cond];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all Handler::$conds
|
||||
*/
|
||||
public static function getConds()
|
||||
{
|
||||
public static function getConds() {
|
||||
return self::$conds;
|
||||
}
|
||||
|
||||
/**
|
||||
* Smart update a Handler::$vars
|
||||
*/
|
||||
public static function updateVar($var, $value)
|
||||
{
|
||||
public static function updateVar($var, $value) {
|
||||
if(is_array(self::$vars[$var]) and is_array($value)) {
|
||||
//self::$vars[$var] = array_merge(self::$vars[$var], $value);
|
||||
$value += self::$vars[$var]; // replacement + replaced
|
||||
|
@ -550,16 +511,14 @@ class Handler
|
|||
/**
|
||||
* Unset a given var
|
||||
*/
|
||||
public static function unsetVar($var)
|
||||
{
|
||||
public static function unsetVar($var) {
|
||||
unset(self::$vars[$var]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the template file basename used
|
||||
*/
|
||||
public static function getTemplateUsed()
|
||||
{
|
||||
public static function getTemplateUsed() {
|
||||
return self::$template_used;
|
||||
}
|
||||
|
||||
|
@ -567,8 +526,7 @@ class Handler
|
|||
* Get the current route path
|
||||
* @args $full (bool true) outputs the full route 'like/this' or 'this'
|
||||
*/
|
||||
public static function getRoutePath($full=true)
|
||||
{
|
||||
public static function getRoutePath($full=true) {
|
||||
if(is_array(self::$route)) {
|
||||
return $full ? implode('/', self::$route) : self::$route[0];
|
||||
} else {
|
||||
|
@ -579,12 +537,10 @@ class Handler
|
|||
/**
|
||||
* Get the current route name from route.name.php
|
||||
*/
|
||||
public static function getRouteName()
|
||||
{
|
||||
public static function getRouteName() {
|
||||
return self::$route_name;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
class HandlerException extends Exception
|
||||
{
|
||||
}
|
||||
class HandlerException extends Exception {}
|
|
@ -310,12 +310,9 @@ namespace G {
|
|||
*/
|
||||
function abbreviate_number($number)
|
||||
{
|
||||
if ($number === null) {
|
||||
$number = 0;
|
||||
} else {
|
||||
|
||||
// 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">»</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">«</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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -15,7 +15,6 @@
|
|||
--------------------------------------------------------------------- */
|
||||
|
||||
namespace G\Render;
|
||||
|
||||
use G;
|
||||
|
||||
/**
|
||||
|
@ -23,8 +22,7 @@ use G;
|
|||
* ---------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
function include_theme_file($filename, $args=[])
|
||||
{
|
||||
function include_theme_file($filename, $args=[]) {
|
||||
$file = G_APP_PATH_THEME . $filename;
|
||||
$override = G_APP_PATH_THEME . 'overrides/' . $filename;
|
||||
if(!file_exists($file)) {
|
||||
|
@ -41,18 +39,15 @@ function include_theme_file($filename, $args=[])
|
|||
}
|
||||
}
|
||||
|
||||
function include_theme_header()
|
||||
{
|
||||
function include_theme_header() {
|
||||
include_theme_file('header');
|
||||
}
|
||||
|
||||
function include_theme_footer()
|
||||
{
|
||||
function include_theme_footer() {
|
||||
include_theme_file('footer');
|
||||
}
|
||||
|
||||
function get_theme_file_contents($filename)
|
||||
{
|
||||
function get_theme_file_contents($filename) {
|
||||
$file = G_APP_PATH_THEME . $filename;
|
||||
return file_exists($file) ? file_get_contents($file) : null;
|
||||
}
|
||||
|
@ -62,8 +57,7 @@ function get_theme_file_contents($filename)
|
|||
* ---------------------------------------------------------------------
|
||||
*/
|
||||
|
||||
function get_theme_file_url($string)
|
||||
{
|
||||
function get_theme_file_url($string) {
|
||||
return BASE_URL_THEME . $string;
|
||||
}
|
||||
|
||||
|
@ -73,14 +67,12 @@ 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')
|
||||
{
|
||||
function get_input_auth_token($name='auth_token') {
|
||||
return '<input type="hidden" name="'.$name.'" value="'.G\Handler::getAuthToken().'">';
|
||||
}
|
||||
|
||||
|
@ -91,8 +83,7 @@ function get_input_auth_token($name='auth_token')
|
|||
*/
|
||||
|
||||
// Outputs the REST_API array to xml
|
||||
function xml_output($array=array())
|
||||
{
|
||||
function xml_output($array=array()) {
|
||||
error_reporting(0);
|
||||
//@ini_set('display_errors', false);
|
||||
if(ob_get_level() === 0 and !ob_start('ob_gzhandler')) {
|
||||
|
@ -118,13 +109,10 @@ function xml_output($array=array())
|
|||
}
|
||||
|
||||
// Procedural function to output an array to json
|
||||
function json_output($data=[], $callback=null)
|
||||
{
|
||||
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();
|
||||
}
|
||||
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');
|
||||
|
@ -138,7 +126,7 @@ function json_output($data=[], $callback=null)
|
|||
'status_txt' => G\get_set_status_header_desc(400),
|
||||
'error' => [
|
||||
'message' => 'no request data present',
|
||||
'code' => null
|
||||
'code' => NULL
|
||||
]
|
||||
];
|
||||
die(json_encode($json_fail));
|
||||
|
@ -158,7 +146,7 @@ function json_output($data=[], $callback=null)
|
|||
'status_txt' => G\get_set_status_header_desc(500),
|
||||
'error' => [
|
||||
'message' => "data couldn't be encoded into json",
|
||||
'code' => null
|
||||
'code' => NULL
|
||||
]
|
||||
];
|
||||
die(json_encode($json_fail));
|
||||
|
|
Loading…
Reference in New Issue