parent
f33b7e1a50
commit
c9998cfb06
|
@ -1,6 +1,6 @@
|
||||||
<?php
|
<?php
|
||||||
define('G_APP_NAME', 'Chevereto Free');
|
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_OWNER', 'Chevereto');
|
||||||
define('G_APP_GITHUB_REPO', 'Chevereto-Free');
|
define('G_APP_GITHUB_REPO', 'Chevereto-Free');
|
||||||
define('G_APP_GITHUB_REPO_URL', 'https://github.com/' . G_APP_GITHUB_OWNER . '/' . G_APP_GITHUB_REPO);
|
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.1' => NULL,
|
||||||
'1.1.2' => NULL,
|
'1.1.2' => NULL,
|
||||||
|
'1.1.3' => NULL,
|
||||||
];
|
];
|
||||||
// Settings that must be renamed from NAME to NEW NAME and DELETE old NAME
|
// Settings that must be renamed from NAME to NEW NAME and DELETE old NAME
|
||||||
$settings_rename = [];
|
$settings_rename = [];
|
||||||
|
|
94
lib/G/G.php
94
lib/G/G.php
|
@ -16,14 +16,12 @@
|
||||||
|
|
||||||
namespace G;
|
namespace G;
|
||||||
|
|
||||||
if (!defined('access') or !access) {
|
if(!defined('access') or !access) die("This file cannot be directly accessed.");
|
||||||
die("This file cannot be directly accessed.");
|
|
||||||
}
|
|
||||||
|
|
||||||
define('G_VERSION', '1.0.42');
|
define('G_VERSION', '1.0.42');
|
||||||
|
|
||||||
// Error reporting setup
|
// Error reporting setup
|
||||||
@ini_set('log_errors', true);
|
@ini_set('log_errors', TRUE);
|
||||||
error_reporting(E_ALL ^ E_NOTICE);
|
error_reporting(E_ALL ^ E_NOTICE);
|
||||||
|
|
||||||
// Set default locale
|
// Set default locale
|
||||||
|
@ -33,7 +31,7 @@ setlocale(LC_ALL, 'en_US.UTF8');
|
||||||
@ini_set('default_charset', 'utf-8');
|
@ini_set('default_charset', 'utf-8');
|
||||||
|
|
||||||
// Set G\ paths and files
|
// 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_PATH_RELATIVE', rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/') . '/');
|
||||||
define('G_ROOT_LIB_PATH', G_ROOT_PATH . 'lib/');
|
define('G_ROOT_LIB_PATH', G_ROOT_PATH . 'lib/');
|
||||||
define('G_PATH', G_ROOT_LIB_PATH . 'G/');
|
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
|
// 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");
|
(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()) {
|
if(headers_sent()) die(str_replace('%%FILE%%', 'app/settings.php', G_APP_SETTINGS_FILE_ERROR)); // Stop on premature headers
|
||||||
die(str_replace('%%FILE%%', 'app/settings.php', G_APP_SETTINGS_FILE_ERROR));
|
|
||||||
} // Stop on premature headers
|
|
||||||
|
|
||||||
// TZ failover
|
// TZ failover
|
||||||
$tz = @date_default_timezone_get();
|
$tz = @date_default_timezone_get();
|
||||||
$dtz = @date_default_timezone_set($tz);
|
$dtz = @date_default_timezone_set($tz);
|
||||||
if (!$dtz && !@date_default_timezone_set('America/Santiago')) {
|
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']));
|
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
|
// Session hack
|
||||||
if ($settings['session.save_path']) {
|
if($settings['session.save_path']) {
|
||||||
session_save_path($settings['session.save_path']);
|
session_save_path($settings['session.save_path']);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Can work with sessions?
|
// Can work with sessions?
|
||||||
if (!@session_start()) {
|
if(!@session_start()) die("G\: Sessions are not working on this server (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!)
|
// Is session save path OK? (you won't believe how many people has session issues!)
|
||||||
$session_save_path = @realpath(session_save_path());
|
$session_save_path = @realpath(session_save_path());
|
||||||
if ($session_save_path) { // realpath on this needs pre-webroot directories access
|
if($session_save_path) { // realpath on this needs pre-webroot directories access
|
||||||
foreach (['write'] as $k) {
|
foreach(['write'] as $k) {
|
||||||
$fn = 'is_' . $k . 'able';
|
$fn = 'is_' . $k . 'able';
|
||||||
if (!$fn($session_save_path)) {
|
if(!$fn($session_save_path)) $session_errors[] = $k;
|
||||||
$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 (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?
|
// Are sessions working properly?
|
||||||
$_SESSION['G'] = true;
|
$_SESSION['G'] = TRUE;
|
||||||
if (!$_SESSION['G']) {
|
if(!$_SESSION['G']) die("G\: Sessions are not working properly. Check for any conflicting server setting.");
|
||||||
die("G\: Sessions are not working properly. Check for any conflicting server setting.");
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set the starting execution time
|
// Set the starting execution time
|
||||||
define('G_APP_TIME_EXECUTION_START', microtime(true));
|
define('G_APP_TIME_EXECUTION_START', microtime(true));
|
||||||
|
|
||||||
// Include G\ core functions
|
// 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.');
|
(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')) {
|
if(file_exists(__DIR__ . '/functions.render.php')) {
|
||||||
require_once(__DIR__ . '/functions.render.php');
|
require_once(__DIR__ . '/functions.render.php');
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isset($settings) && $settings['error_reporting'] === false) {
|
if(isset($settings) && $settings['error_reporting'] === false) {
|
||||||
error_reporting(0);
|
error_reporting(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the default timezone
|
// Set the default timezone
|
||||||
if (isset($settings['default_timezone']) && is_valid_timezone($settings['default_timezone'])) {
|
if(isset($settings['default_timezone']) && is_valid_timezone($settings['default_timezone'])) {
|
||||||
if (!@date_default_timezone_set($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]));
|
die(strtr("G\: Can't set %s timezone on line %l", ['%s' => $settings['default_timezone'], '%l' => __LINE__ - 1]));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the system environment
|
// Set the system environment
|
||||||
if (isset($settings['environment'])) {
|
if(isset($settings['environment'])) {
|
||||||
define('G_APP_ENV', $settings['environment']);
|
define('G_APP_ENV', $settings['environment']);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the HTTP definitions
|
// Set the HTTP definitions
|
||||||
define('G_HTTP_HOST', $_SERVER['HTTP_HOST']);
|
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
|
// 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_FILENAME'] = forward_slash($_SERVER['SCRIPT_FILENAME']);
|
||||||
$_SERVER['SCRIPT_NAME'] = forward_slash($_SERVER['SCRIPT_NAME']);
|
$_SERVER['SCRIPT_NAME'] = forward_slash($_SERVER['SCRIPT_NAME']);
|
||||||
// Fix CloudFlare REMOTE_ADDR
|
// Fix CloudFlare REMOTE_ADDR
|
||||||
if (isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
|
if(isset($_SERVER['HTTP_CF_CONNECTING_IP'])) {
|
||||||
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
|
$_SERVER['REMOTE_ADDR'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Inherit application definitions
|
// Inherit application definitions
|
||||||
if (file_exists(G_APP_PATH . 'app.php')) {
|
if(file_exists(G_APP_PATH . 'app.php')) {
|
||||||
require_once(G_APP_PATH . 'app.php');
|
require_once(G_APP_PATH . 'app.php');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the DB constants
|
// Set the DB constants
|
||||||
foreach (['host', 'port', 'name', 'user', 'pass', 'driver', 'pdo_attrs'] as $k) {
|
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
|
// 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.');
|
(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)) {
|
if(file_exists(G_APP_FILE_FUNCTIONS_RENDER)) {
|
||||||
require_once(G_APP_FILE_FUNCTIONS_RENDER);
|
require_once(G_APP_FILE_FUNCTIONS_RENDER);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set the URLs
|
// Set the URLs
|
||||||
|
@ -157,11 +145,11 @@ define("G_APP_LIB_URL", absolute_to_url(G_APP_PATH_LIB));
|
||||||
|
|
||||||
// Define the app theme
|
// Define the app theme
|
||||||
define('G_APP_PATH_THEMES', G_APP_PATH . 'themes/');
|
define('G_APP_PATH_THEMES', G_APP_PATH . 'themes/');
|
||||||
if (!file_exists(G_APP_PATH_THEMES)) {
|
if(!file_exists(G_APP_PATH_THEMES)) {
|
||||||
die("G\: Theme path doesn't exists!");
|
die("G\: Theme path doesn't exists!");
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isset($settings['theme']) and file_exists(G_APP_PATH_THEMES . $settings['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('G_APP_PATH_THEME', G_APP_PATH_THEMES . $settings['theme'].'/');
|
||||||
define('BASE_URL_THEME', absolute_to_url(G_APP_PATH_THEME));
|
define('BASE_URL_THEME', absolute_to_url(G_APP_PATH_THEME));
|
||||||
}
|
}
|
|
@ -20,550 +20,528 @@
|
||||||
*/
|
*/
|
||||||
|
|
||||||
namespace G;
|
namespace G;
|
||||||
|
use PDO, PDOException, Exception;
|
||||||
|
|
||||||
use PDO;
|
class DB {
|
||||||
use PDOException;
|
|
||||||
use Exception;
|
|
||||||
|
|
||||||
class DB
|
private static $instance;
|
||||||
{
|
|
||||||
private static $instance;
|
|
||||||
|
|
||||||
private $host = G_APP_DB_HOST;
|
private $host = G_APP_DB_HOST;
|
||||||
private $port = G_APP_DB_PORT;
|
private $port = G_APP_DB_PORT;
|
||||||
private $name = G_APP_DB_NAME;
|
private $name = G_APP_DB_NAME;
|
||||||
private $user = G_APP_DB_USER;
|
private $user = G_APP_DB_USER;
|
||||||
private $pass = G_APP_DB_PASS;
|
private $pass = G_APP_DB_PASS;
|
||||||
private $driver = G_APP_DB_DRIVER;
|
private $driver = G_APP_DB_DRIVER;
|
||||||
private $pdo_attrs = G_APP_DB_PDO_ATTRS;
|
private $pdo_attrs = G_APP_DB_PDO_ATTRS;
|
||||||
|
|
||||||
public static $dbh;
|
static $dbh;
|
||||||
public $query;
|
public $query;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Connect to the DB server
|
* Connect to the DB server
|
||||||
* Throws an Exception on error (tay weando? en serio?)
|
* 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!empty($conn)) {
|
try {
|
||||||
// Inject connection info
|
// PDO already connected
|
||||||
foreach (['host', 'user', 'name', 'pass', 'port', 'driver', 'pdo_attrs'] as $k) {
|
if(empty($conn) and isset(self::$dbh) and get_class(self::$dbh) == 'PDO') {
|
||||||
$this->{$k} = $conn[$k];
|
return TRUE;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
$pdo_connect = $this->driver . ':host=' . $this->host . ';dbname=' . $this->name;
|
if(!empty($conn)) {
|
||||||
if ($this->port) {
|
// Inject connection info
|
||||||
$pdo_connect .= ';port=' . $this->port;
|
foreach(['host', 'user', 'name', 'pass', 'port', 'driver', 'pdo_attrs'] as $k) {
|
||||||
}
|
$this->{$k} = $conn[$k];
|
||||||
// $pdo_connect .= ';charset=UTF8';
|
}
|
||||||
|
}
|
||||||
|
|
||||||
$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_attrs = @unserialize($this->pdo_attrs) ?: $this->pdo_attrs;
|
||||||
$this->pdo_default_attrs = [
|
|
||||||
PDO::ATTR_TIMEOUT => 30,
|
|
||||||
];
|
|
||||||
|
|
||||||
// Override PDO defaults ?
|
// PDO defaults
|
||||||
$this->pdo_attrs = (is_array($this->pdo_attrs) ? $this->pdo_attrs : []) + $this->pdo_default_attrs;
|
$this->pdo_default_attrs = [
|
||||||
|
PDO::ATTR_TIMEOUT => 30,
|
||||||
|
//PDO::ATTR_PERSISTENT => FALSE
|
||||||
|
];
|
||||||
|
|
||||||
// PDO hard overrides
|
// Override PDO defaults ?
|
||||||
$this->pdo_attrs[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
|
$this->pdo_attrs = (is_array($this->pdo_attrs) ? $this->pdo_attrs : []) + $this->pdo_default_attrs;
|
||||||
$this->pdo_attrs[PDO::MYSQL_ATTR_INIT_COMMAND] = "SET time_zone = '+00:00', NAMES 'UTF8'"; // UTC for timestamps
|
|
||||||
|
|
||||||
// Turn off PHP error reporting just for the connection here (invalid host names will trigger a PHP warning)
|
// PDO hard overrides
|
||||||
$error_reporting = error_reporting();
|
$this->pdo_attrs[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
|
||||||
error_reporting(0);
|
$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
|
// Turn off PHP error reporting just for the connection here (invalid host names will trigger a PHP warning)
|
||||||
self::$dbh = new PDO($pdo_connect, $this->user, $this->pass, $this->pdo_attrs);
|
$error_reporting = error_reporting();
|
||||||
|
error_reporting(0);
|
||||||
|
|
||||||
// Re-enable the error_reporting level
|
// Note that PDO::ERRMODE_SILENT has no effect on connection. Connections always throw an exception if it fails
|
||||||
error_reporting($error_reporting);
|
self::$dbh = new PDO($pdo_connect, $this->user, $this->pass, $this->pdo_attrs);
|
||||||
|
|
||||||
// PDO emulate prepares if needed
|
// Re-enable the error_reporting level
|
||||||
if (version_compare(self::$dbh->getAttribute(PDO::ATTR_SERVER_VERSION), '5.1.17', '<')) {
|
error_reporting($error_reporting);
|
||||||
self::$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
|
|
||||||
}
|
|
||||||
|
|
||||||
self::$instance = $this;
|
// PDO emulate prepares if needed
|
||||||
} catch (Exception $e) {
|
if(version_compare(self::$dbh->getAttribute(PDO::ATTR_SERVER_VERSION), '5.1.17', '<')) {
|
||||||
self::$dbh = null;
|
self::$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
|
||||||
throw new DBException($e->getMessage(), 400);
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
self::$instance = $this;
|
||||||
* 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;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
} catch(Exception $e) {
|
||||||
* Populates the class DB own PDO attributes array with an entire array
|
self::$dbh = NULL;
|
||||||
* Attribute list here: http://php.net/manual/en/pdo.setattribute.php
|
throw new DBException($e->getMessage(), 400);
|
||||||
*/
|
}
|
||||||
public function setPDOAttrs($attributes)
|
|
||||||
{
|
|
||||||
$this->pdo_attrs = $attributes;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
}
|
||||||
* 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)
|
/**
|
||||||
{
|
* Singleton instance handler
|
||||||
return self::$dbh->getAttribute($attr);
|
* 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
|
* Populates the class DB own PDO attributes array with an entire array
|
||||||
* http://php.net/manual/en/pdo.prepare.php
|
* Attribute list here: http://php.net/manual/en/pdo.setattribute.php
|
||||||
*/
|
*/
|
||||||
public function query($query)
|
public function setPDOAttrs($attributes) {
|
||||||
{
|
$this->pdo_attrs = $attributes;
|
||||||
$this->query = self::$dbh->prepare($query);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public function errorInfo()
|
/**
|
||||||
{
|
* Populates the class DB own PDO attributes array with a single key
|
||||||
return self::$dbh->errorInfo();
|
* 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) {
|
||||||
* Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement
|
return self::$dbh->getAttribute($attr);
|
||||||
* 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 exec()
|
/**
|
||||||
{
|
* Prepares an SQL statement to be executed by the PDOStatement::execute() method
|
||||||
return $this->query->execute();
|
* http://php.net/manual/en/pdo.prepare.php
|
||||||
}
|
*/
|
||||||
|
public function query($query) {
|
||||||
|
$this->query = self::$dbh->prepare($query);
|
||||||
|
}
|
||||||
|
|
||||||
public function fetchColumn()
|
public function errorInfo() {
|
||||||
{
|
return self::$dbh->errorInfo();
|
||||||
return $this->query->fetchColumn();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
public function closeCursor()
|
/**
|
||||||
{
|
* Binds a value to a corresponding named or question mark placeholder in the SQL statement that was used to prepare the statement
|
||||||
return $this->query->closeCursor();
|
* 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)
|
public function exec() {
|
||||||
{
|
return $this->query->execute();
|
||||||
$this->exec();
|
}
|
||||||
return $this->query->fetchAll(is_int($mode) ? $mode : PDO::FETCH_ASSOC);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
public function fetchColumn() {
|
||||||
* Execute and returns the single result from the prepared statement
|
return $this->query->fetchColumn();
|
||||||
* 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 closeCursor() {
|
||||||
* Query and exec, return number of affected rows or FALSE
|
return $this->query->closeCursor();
|
||||||
*/
|
}
|
||||||
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 fetchAll($mode=PDO::FETCH_ASSOC) {
|
||||||
* Query and fetch single record
|
$this->exec();
|
||||||
*/
|
return $this->query->fetchAll(is_int($mode) ? $mode : PDO::FETCH_ASSOC);
|
||||||
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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query and fetch all records
|
* Execute and returns the single result from the prepared statement
|
||||||
*/
|
* http://php.net/manual/en/pdostatement.fetch.php
|
||||||
public static function queryFetchAll($query, $fetch_style=null)
|
*/
|
||||||
{
|
public function fetchSingle($mode=PDO::FETCH_ASSOC) {
|
||||||
try {
|
$this->exec();
|
||||||
return self::queryFetch($query, null, $fetch_style);
|
return $this->query->fetch(is_int($mode) ? $mode : PDO::FETCH_ASSOC);
|
||||||
} catch (Exception $e) {
|
}
|
||||||
throw new DBException($e->getMessage(), 400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Query fetch (core version)
|
* Query and exec, return number of affected rows or FALSE
|
||||||
*/
|
*/
|
||||||
public static function queryFetch($query, $limit=1, $fetch_style=null)
|
public static function queryExec($query) {
|
||||||
{
|
try {
|
||||||
try {
|
$db = self::getInstance();
|
||||||
$db = self::getInstance();
|
$db->query($query);
|
||||||
$db->query($query);
|
return $db->exec() ? $db->rowCount() : FALSE;
|
||||||
return $limit == 1 ? $db->fetchSingle($fetch_style) : $db->fetchAll($fetch_style);
|
} catch(Exception $e) {
|
||||||
} catch (Exception $e) {
|
throw new DBException($e->getMessage(), 400);
|
||||||
throw new DBException($e->getMessage(), 400);
|
}
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed
|
* Query and fetch single record
|
||||||
* http://php.net/manual/en/pdostatement.rowcount.php
|
*/
|
||||||
*/
|
public static function queryFetchSingle($query, $fetch_style=NULL) {
|
||||||
public function rowCount()
|
try {
|
||||||
{
|
return self::queryFetch($query, 1, $fetch_style);
|
||||||
return $this->query->rowCount();
|
} 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
|
* Query and fetch all records
|
||||||
* http://php.net/manual/en/pdo.lastinsertid.php
|
*/
|
||||||
*/
|
public static function queryFetchAll($query, $fetch_style=NULL) {
|
||||||
public function lastInsertId()
|
try {
|
||||||
{
|
return self::queryFetch($query, NULL, $fetch_style);
|
||||||
return self::$dbh->lastInsertId();
|
} catch(Exception $e) {
|
||||||
}
|
throw new DBException($e->getMessage(), 400);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Turns off autocommit mode
|
* Query fetch (core version)
|
||||||
* http://php.net/manual/en/pdo.begintransaction.php
|
*/
|
||||||
*/
|
public static function queryFetch($query, $limit=1, $fetch_style=NULL) {
|
||||||
public function beginTransaction()
|
try {
|
||||||
{
|
$db = self::getInstance();
|
||||||
return self::$dbh->beginTransaction();
|
$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
|
* Returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed
|
||||||
* http://php.net/manual/en/pdo.commit.php
|
* http://php.net/manual/en/pdostatement.rowcount.php
|
||||||
*/
|
*/
|
||||||
public function endTransaction()
|
public function rowCount() {
|
||||||
{
|
return $this->query->rowCount();
|
||||||
return self::$dbh->commit();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Rolls back the current transaction, as initiated by PDO::beginTransaction()
|
* 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.rollback.php
|
* http://php.net/manual/en/pdo.lastinsertid.php
|
||||||
*/
|
*/
|
||||||
public function cancelTransaction()
|
public function lastInsertId() {
|
||||||
{
|
return self::$dbh->lastInsertId();
|
||||||
return self::$dbh->rollBack();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Dumps the informations contained by a prepared statement directly on the output
|
* Turns off autocommit mode
|
||||||
* http://php.net/manual/en/pdostatement.debugdumpparams.php
|
* http://php.net/manual/en/pdo.begintransaction.php
|
||||||
*/
|
*/
|
||||||
public function debugDumpParams()
|
public function beginTransaction(){
|
||||||
{
|
return self::$dbh->beginTransaction();
|
||||||
return $this->query->debugDumpParams();
|
}
|
||||||
}
|
|
||||||
|
|
||||||
/* 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
|
* Rolls back the current transaction, as initiated by PDO::beginTransaction()
|
||||||
*/
|
* http://php.net/manual/en/pdo.rollback.php
|
||||||
public static function getTable($table)
|
*/
|
||||||
{
|
public function cancelTransaction(){
|
||||||
return get_app_setting('db_table_prefix') . $table;
|
return self::$dbh->rollBack();
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Get values from DB
|
* Dumps the informations contained by a prepared statement directly on the output
|
||||||
*/
|
* http://php.net/manual/en/pdostatement.debugdumpparams.php
|
||||||
public static function get($table, $values, $clause='AND', $sort=[], $limit=null, $fetch_style=null)
|
*/
|
||||||
{
|
public function debugDumpParams(){
|
||||||
if (!is_array($values) and $values !== 'all') {
|
return $this->query->debugDumpParams();
|
||||||
throw new DBException('Expecting array values, '.gettype($values).' given in ' . __METHOD__, 100);
|
}
|
||||||
}
|
|
||||||
|
|
||||||
self::validateClause($clause, __METHOD__);
|
/* Now the G\ fast DB methods, presented by Chevereto */
|
||||||
|
|
||||||
if (is_array($table)) {
|
/**
|
||||||
$join = $table['join'];
|
* Get the table with its prefix
|
||||||
$table = $table['table'];
|
*/
|
||||||
}
|
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) {
|
self::validateClause($clause, __METHOD__);
|
||||||
$query .= ' ' . $join . ' ';
|
|
||||||
}
|
|
||||||
|
|
||||||
if (is_array($values) and !empty($values)) {
|
if(is_array($table)) {
|
||||||
$query .= ' WHERE ';
|
$join = $table['join'];
|
||||||
foreach ($values as $k => $v) {
|
$table = $table['table'];
|
||||||
if (is_null($v)) {
|
}
|
||||||
$query .= '`'.$k.'` IS :'.$k.' '.$clause.' ';
|
|
||||||
} else {
|
|
||||||
$query .= '`'.$k.'`=:'.$k.' '.$clause.' ';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$query = rtrim($query, $clause . ' ');
|
$table = DB::getTable($table);
|
||||||
|
|
||||||
if (is_array($sort) and !empty($sort)) {
|
$query = 'SELECT * FROM '.$table;
|
||||||
if (!$sort['field']) {
|
|
||||||
$sort['field'] = 'date';
|
|
||||||
}
|
|
||||||
if (!$sort['order']) {
|
|
||||||
$sort['order'] = 'desc';
|
|
||||||
}
|
|
||||||
$query .= ' ORDER BY '.$sort['field'].' '.strtoupper($sort['order']).' ';
|
|
||||||
}
|
|
||||||
|
|
||||||
if ($limit and is_int($limit)) {
|
if($join) {
|
||||||
$query .= " LIMIT $limit";
|
$query .= ' ' . $join . ' ';
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
if(is_array($values) and !empty($values)) {
|
||||||
$db = self::getInstance();
|
$query .= ' WHERE ';
|
||||||
$db->query($query);
|
foreach($values as $k => $v) {
|
||||||
if (is_array($values)) {
|
if(is_null($v)) {
|
||||||
foreach ($values as $k => $v) {
|
$query .= '`'.$k.'` IS :'.$k.' '.$clause.' ';
|
||||||
$db->bind(':'.$k, $v);
|
} else {
|
||||||
}
|
$query .= '`'.$k.'`=:'.$k.' '.$clause.' ';
|
||||||
}
|
}
|
||||||
return $limit == 1 ? $db->fetchSingle($fetch_style) : $db->fetchAll($fetch_style);
|
}
|
||||||
} catch (Exception $e) {
|
}
|
||||||
throw new DBException($e->getMessage(), 400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
$query = rtrim($query, $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);
|
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
* Update target table row(s)
|
||||||
$query .= '`' . $k . '`=:value_' . $k . ',';
|
* Returns the number of affected rows or false
|
||||||
}
|
*/
|
||||||
$query = rtrim($query, ',') . ' WHERE ';
|
public static function update($table, $values, $wheres, $clause='AND') {
|
||||||
|
|
||||||
// Set the where pairs
|
if(!is_array($values)) {
|
||||||
foreach ($wheres as $k => $v) {
|
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
|
||||||
$query .= '`'.$k.'`=:where_'.$k.' '.$clause.' ';
|
}
|
||||||
}
|
if(!is_array($wheres)) {
|
||||||
$query = rtrim($query, $clause.' ');
|
throw new DBException('Expecting array values, '.gettype($wheres).' given in '. __METHOD__, 100);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
self::validateClause($clause, __METHOD__);
|
||||||
$db = self::getInstance();
|
|
||||||
$db->query($query);
|
|
||||||
|
|
||||||
// Bind the values
|
$table = DB::getTable($table);
|
||||||
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;
|
$query = 'UPDATE `'.$table.'` SET ';
|
||||||
} catch (Exception $e) {
|
|
||||||
throw new DBException($e->getMessage(), 400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
// Set the value pairs
|
||||||
* Insert single row to the table
|
foreach($values as $k => $v) {
|
||||||
*/
|
$query .= '`' . $k . '`=:value_' . $k . ',';
|
||||||
public static function insert($table, $values)
|
}
|
||||||
{
|
$query = rtrim($query, ',') . ' WHERE ';
|
||||||
if (!is_array($values)) {
|
|
||||||
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
|
|
||||||
}
|
|
||||||
|
|
||||||
$table = DB::getTable($table);
|
// Set the where pairs
|
||||||
|
foreach($wheres as $k => $v) {
|
||||||
|
$query .= '`'.$k.'`=:where_'.$k.' '.$clause.' ';
|
||||||
|
}
|
||||||
|
$query = rtrim($query, $clause.' ');
|
||||||
|
|
||||||
$table_fields = [];
|
try {
|
||||||
foreach ($values as $k => $v) {
|
$db = self::getInstance();
|
||||||
$table_fields[] = $k;
|
$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), '`,`') . '`)
|
`'.$table.'` (`' . ltrim(implode('`,`', $table_fields), '`,`') . '`)
|
||||||
VALUES (' . ':' . str_replace(':', ',:', implode(':', $table_fields)) . ')';
|
VALUES (' . ':' . str_replace(':', ',:', implode(':', $table_fields)) . ')';
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$db = self::getInstance();
|
$db = self::getInstance();
|
||||||
$db->query($query);
|
$db->query($query);
|
||||||
foreach ($values as $k => $v) {
|
foreach($values as $k => $v) {
|
||||||
$db->bind(':'.$k, $v);
|
$db->bind(':'.$k, $v);
|
||||||
}
|
}
|
||||||
return $db->exec() ? $db->lastInsertId() : false;
|
return $db->exec() ? $db->lastInsertId() : FALSE;
|
||||||
} catch (Exception $e) {
|
} catch(Exception $e) {
|
||||||
throw new DBException($e->getMessage(), 400);
|
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) {
|
foreach(['values', 'wheres'] as $k) {
|
||||||
if (preg_match('/^([+-]{1})\s*([\d]+)$/', $v, $matches)) { // 1-> op 2-> number
|
if(!is_array(${$k})) {
|
||||||
$query .= '`' . $k . '`=';
|
throw new DBException('Expecting array values, '.gettype(${$k}).' given in '. __METHOD__, 100);
|
||||||
if ($matches[1] == '+') {
|
}
|
||||||
$query .= '`' . $k . '`' . $matches[1] . $matches[2] . ',';
|
}
|
||||||
}
|
|
||||||
if ($matches[1] == '-') {
|
|
||||||
$query .= 'GREATEST(cast(`'.$k.'` AS SIGNED) - '.$matches[2].', 0),';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
$query = rtrim($query, ',') . ' WHERE ';
|
$table = DB::getTable($table);
|
||||||
|
$query = 'UPDATE `'.$table.'` SET ';
|
||||||
|
|
||||||
// Set the where pairs
|
foreach($values as $k => $v) {
|
||||||
foreach ($wheres as $k => $v) {
|
if(preg_match('/^([+-]{1})\s*([\d]+)$/', $v, $matches)) { // 1-> op 2-> number
|
||||||
$query .= '`'.$k.'`=:where_'.$k.' '.$clause.' ';
|
$query .= '`' . $k . '`=';
|
||||||
}
|
if($matches[1] == '+') {
|
||||||
$query = rtrim($query, $clause.' ');
|
$query .= '`' . $k . '`' . $matches[1] . $matches[2] . ',';
|
||||||
|
}
|
||||||
|
if($matches[1] == '-') {
|
||||||
|
$query .= 'GREATEST(cast(`'.$k.'` AS SIGNED) - '.$matches[2].', 0),';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
$query = rtrim($query, ',') . ' WHERE ';
|
||||||
$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);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
// Set the where pairs
|
||||||
* Delete row(s) from table
|
foreach($wheres as $k => $v) {
|
||||||
* Returns the number of affected rows or false
|
$query .= '`'.$k.'`=:where_'.$k.' '.$clause.' ';
|
||||||
*/
|
}
|
||||||
public static function delete($table, $values, $clause='AND')
|
$query = rtrim($query, $clause.' ');
|
||||||
{
|
|
||||||
if (!is_array($values)) {
|
|
||||||
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
|
|
||||||
}
|
|
||||||
|
|
||||||
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) {
|
* Delete row(s) from table
|
||||||
$query .= '`'.$k.'`=:'.$k.' '.$clause.' ';
|
* Returns the number of affected rows or false
|
||||||
}
|
*/
|
||||||
$query = rtrim($query, $clause.' ');
|
public static function delete($table, $values, $clause='AND') {
|
||||||
|
|
||||||
try {
|
if(!is_array($values)) {
|
||||||
$db = self::getInstance();
|
throw new DBException('Expecting array values, '.gettype($values).' given in '. __METHOD__, 100);
|
||||||
$db->query($query);
|
}
|
||||||
foreach ($values as $k => $v) {
|
|
||||||
$db->bind(':'.$k, $v);
|
self::validateClause($clause, __METHOD__);
|
||||||
}
|
|
||||||
return $db->exec() ? $db->rowCount() : false;
|
$table = DB::getTable($table);
|
||||||
} catch (Exception $e) {
|
$query = 'DELETE FROM `'.$table.'` WHERE ';
|
||||||
throw new DBException($e->getMessage(), 400);
|
|
||||||
}
|
$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
|
// DB class own Exception
|
||||||
class DBException extends Exception
|
class DBException extends Exception {}
|
||||||
{
|
|
||||||
}
|
|
File diff suppressed because it is too large
Load Diff
|
@ -310,12 +310,9 @@ namespace G {
|
||||||
*/
|
*/
|
||||||
function abbreviate_number($number)
|
function abbreviate_number($number)
|
||||||
{
|
{
|
||||||
if ($number === null) {
|
|
||||||
$number = 0;
|
// strip any formatting
|
||||||
} else {
|
$number = (0+str_replace(',', '', $number));
|
||||||
// strip any formatting
|
|
||||||
$number = (0+str_replace(',', '', $number));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Not a number, keep it "as is"
|
// Not a number, keep it "as is"
|
||||||
if (!is_numeric($number) or $number == 0) {
|
if (!is_numeric($number) or $number == 0) {
|
||||||
|
@ -563,7 +560,7 @@ namespace G {
|
||||||
function exception_to_error($e, $die=true)
|
function exception_to_error($e, $die=true)
|
||||||
{
|
{
|
||||||
$internal_code = 500;
|
$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);
|
set_status_header($internal_code);
|
||||||
|
|
||||||
|
@ -819,20 +816,18 @@ namespace G {
|
||||||
|
|
||||||
function get_client_ip()
|
function get_client_ip()
|
||||||
{
|
{
|
||||||
if(isset($_SERVER['G_CLIENT_IP'])) {
|
$client_ip = !empty($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : (!empty($_ENV['REMOTE_ADDR']) ? $_ENV['REMOTE_ADDR'] : null);
|
||||||
return $_SERVER['G_CLIENT_IP'];
|
|
||||||
|
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'];
|
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
|
||||||
} 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']) {
|
|
||||||
$entries = preg_split('/[\s,]/', $_SERVER['HTTP_X_FORWARDED_FOR'], -1, PREG_SPLIT_NO_EMPTY);
|
$entries = preg_split('/[\s,]/', $_SERVER['HTTP_X_FORWARDED_FOR'], -1, PREG_SPLIT_NO_EMPTY);
|
||||||
|
|
||||||
reset($entries);
|
reset($entries);
|
||||||
|
|
||||||
foreach ($entries as $entry) {
|
while (list(, $entry) = each($entries)) {
|
||||||
$entry = trim($entry);
|
$entry = trim($entry);
|
||||||
if (preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/', $entry, $ip_list)) {
|
if (preg_match('/^([0-9]+\.[0-9]+\.[0-9]+\.[0-9]+)/', $entry, $ip_list)) {
|
||||||
$private_ip = array(
|
$private_ip = array(
|
||||||
|
@ -843,6 +838,7 @@ namespace G {
|
||||||
'/^10\..*/');
|
'/^10\..*/');
|
||||||
|
|
||||||
$found_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);
|
$found_ip = preg_replace($private_ip, $client_ip, $ip_list[1]);
|
||||||
|
|
||||||
if ($client_ip != $found_ip) { // and !isset($_SERVER['HTTP_CF_CONNECTING_IP']
|
if ($client_ip != $found_ip) { // and !isset($_SERVER['HTTP_CF_CONNECTING_IP']
|
||||||
$client_ip = $found_ip;
|
$client_ip = $found_ip;
|
||||||
break;
|
break;
|
||||||
|
@ -850,7 +846,7 @@ namespace G {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
$_SERVER['G_CLIENT_IP'] = $client_ip;
|
|
||||||
return $client_ip;
|
return $client_ip;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1133,23 +1129,6 @@ namespace G {
|
||||||
return $path;
|
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
|
* Returns a sanitized string, typically for URLs
|
||||||
* This function was borrowed from chyrp.net (MIT License)
|
* This function was borrowed from chyrp.net (MIT License)
|
||||||
|
@ -1459,7 +1438,7 @@ namespace G {
|
||||||
function relative_to_url($filepath, $root_url=null)
|
function relative_to_url($filepath, $root_url=null)
|
||||||
{
|
{
|
||||||
if (!check_value($root_url)) {
|
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));
|
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)
|
function url_to_relative($url, $root_url=null)
|
||||||
{
|
{
|
||||||
if (!check_value($root_url)) {
|
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);
|
return str_replace($root_url, G_ROOT_PATH_RELATIVE, $url);
|
||||||
}
|
}
|
||||||
|
@ -1483,7 +1462,7 @@ namespace G {
|
||||||
function absolute_to_url($filepath, $root_url=null)
|
function absolute_to_url($filepath, $root_url=null)
|
||||||
{
|
{
|
||||||
if (!check_value($root_url)) {
|
if (!check_value($root_url)) {
|
||||||
$root_url = get_root_url();
|
$root_url = G_ROOT_URL;
|
||||||
}
|
}
|
||||||
if (G_ROOT_PATH === G_ROOT_PATH_RELATIVE) {
|
if (G_ROOT_PATH === G_ROOT_PATH_RELATIVE) {
|
||||||
return $root_url . ltrim($filepath, '/');
|
return $root_url . ltrim($filepath, '/');
|
||||||
|
@ -1495,7 +1474,7 @@ namespace G {
|
||||||
function url_to_absolute($url, $root_url=null)
|
function url_to_absolute($url, $root_url=null)
|
||||||
{
|
{
|
||||||
if (!check_value($root_url)) {
|
if (!check_value($root_url)) {
|
||||||
$root_url = get_root_url();
|
$root_url = G_ROOT_URL;
|
||||||
}
|
}
|
||||||
return str_replace($root_url, G_ROOT_PATH, $url);
|
return str_replace($root_url, G_ROOT_PATH, $url);
|
||||||
}
|
}
|
||||||
|
@ -1529,43 +1508,21 @@ namespace G {
|
||||||
return get_global('settings')[$key];
|
return get_global('settings')[$key];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function get_domain()
|
||||||
|
{
|
||||||
|
return HTTP_HOST;
|
||||||
|
}
|
||||||
|
|
||||||
function get_base_url($path='')
|
function get_base_url($path='')
|
||||||
{
|
{
|
||||||
$path = sanitize_relative_path($path);
|
$path = sanitize_relative_path($path);
|
||||||
$return = get_root_url() . ltrim($path, '/');
|
$return = G_ROOT_URL . ltrim($path, '/');
|
||||||
return rtrim($return, '/');
|
return rtrim($return, '/');
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_host()
|
function get_current_url()
|
||||||
{
|
{
|
||||||
return defined('APP_G_HTTP_HOST') ? APP_G_HTTP_HOST : G_HTTP_HOST;
|
return get_base_url(preg_replace('#'.G_ROOT_PATH_RELATIVE.'#', '', $_SERVER['REQUEST_URI'], 1));
|
||||||
}
|
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function settings_has_db_info()
|
function settings_has_db_info()
|
||||||
|
@ -1937,26 +1894,9 @@ namespace G {
|
||||||
return basename($file);
|
return basename($file);
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_basename_without_extension($filename)
|
function get_filename_without_extension($file)
|
||||||
{
|
{
|
||||||
$extension = pathinfo($filename, PATHINFO_EXTENSION);
|
return preg_replace('/\\.[^.\\s]{2,4}$/', '', basename($file));
|
||||||
$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";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -2262,9 +2202,9 @@ namespace G {
|
||||||
// https://github.com/Chevereto/Chevereto-Free/pull/35
|
// https://github.com/Chevereto/Chevereto-Free/pull/35
|
||||||
function imagecreatefrombmp($file)
|
function imagecreatefrombmp($file)
|
||||||
{
|
{
|
||||||
// if (function_exists('imagecreatefrombmp')) {
|
if (function_exists('imagecreatefrombmp')) {
|
||||||
// return imagecreatefrombmp($file);
|
return imagecreatefrombmp($file);
|
||||||
// }
|
}
|
||||||
// version 1.00
|
// version 1.00
|
||||||
if (!($fh = fopen($file, 'rb'))) {
|
if (!($fh = fopen($file, 'rb'))) {
|
||||||
trigger_error('imagecreatefrombmp: Can not open ' . $file, E_USER_WARNING);
|
trigger_error('imagecreatefrombmp: Can not open ' . $file, E_USER_WARNING);
|
||||||
|
@ -2585,126 +2525,6 @@ namespace G {
|
||||||
return trim(preg_replace('/\s*(?:\*\/|\?>).*/', '', $string));
|
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
|
} // G Namespace
|
||||||
|
|
||||||
// Global namespace
|
// Global namespace
|
||||||
|
@ -2947,4 +2767,5 @@ namespace {
|
||||||
return $status === 0;
|
return $status === 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
|
@ -15,7 +15,6 @@
|
||||||
--------------------------------------------------------------------- */
|
--------------------------------------------------------------------- */
|
||||||
|
|
||||||
namespace G\Render;
|
namespace G\Render;
|
||||||
|
|
||||||
use G;
|
use G;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -23,38 +22,34 @@ use G;
|
||||||
* ---------------------------------------------------------------------
|
* ---------------------------------------------------------------------
|
||||||
*/
|
*/
|
||||||
|
|
||||||
function include_theme_file($filename, $args=[])
|
function include_theme_file($filename, $args=[]) {
|
||||||
{
|
$file = G_APP_PATH_THEME . $filename;
|
||||||
$file = G_APP_PATH_THEME . $filename;
|
$override = G_APP_PATH_THEME . 'overrides/' . $filename;
|
||||||
$override = G_APP_PATH_THEME . 'overrides/' . $filename;
|
if(!file_exists($file)) {
|
||||||
if (!file_exists($file)) {
|
$file .= '.php';
|
||||||
$file .= '.php';
|
$override .= '.php';
|
||||||
$override .= '.php';
|
}
|
||||||
}
|
if(file_exists($override)) {
|
||||||
if (file_exists($override)) {
|
$file = $override;
|
||||||
$file = $override;
|
}
|
||||||
}
|
if(file_exists($file)) {
|
||||||
if (file_exists($file)) {
|
$GLOBALS['theme_include_args'] = $args;
|
||||||
$GLOBALS['theme_include_args'] = $args;
|
include($file);
|
||||||
include($file);
|
unset($GLOBALS['theme_include_args']);
|
||||||
unset($GLOBALS['theme_include_args']);
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function include_theme_header()
|
function include_theme_header() {
|
||||||
{
|
include_theme_file('header');
|
||||||
include_theme_file('header');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function include_theme_footer()
|
function include_theme_footer() {
|
||||||
{
|
include_theme_file('footer');
|
||||||
include_theme_file('footer');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function get_theme_file_contents($filename)
|
function get_theme_file_contents($filename) {
|
||||||
{
|
$file = G_APP_PATH_THEME . $filename;
|
||||||
$file = G_APP_PATH_THEME . $filename;
|
return file_exists($file) ? file_get_contents($file) : null;
|
||||||
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)
|
function get_theme_file_url($string) {
|
||||||
{
|
return BASE_URL_THEME . $string;
|
||||||
return BASE_URL_THEME . $string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
@ -73,15 +67,13 @@ function get_theme_file_url($string)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Return app lib file url
|
// Return app lib file url
|
||||||
function get_app_lib_file_url($string)
|
function get_app_lib_file_url($string){
|
||||||
{
|
return G_APP_LIB_URL . $string;
|
||||||
return (defined('APP_G_APP_LIB_URL') ? APP_G_APP_LIB_URL : G_APP_LIB_URL) . $string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Returns the HTML input with the auth token
|
// 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().'">';
|
||||||
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
|
// Outputs the REST_API array to xml
|
||||||
function xml_output($array=array())
|
function xml_output($array=array()) {
|
||||||
{
|
error_reporting(0);
|
||||||
error_reporting(0);
|
//@ini_set('display_errors', false);
|
||||||
//@ini_set('display_errors', false);
|
if(ob_get_level() === 0 and !ob_start('ob_gzhandler')) {
|
||||||
if (ob_get_level() === 0 and !ob_start('ob_gzhandler')) {
|
ob_start();
|
||||||
ob_start();
|
}
|
||||||
}
|
header("Last-Modified: ".gmdate("D, d M Y H:i:s")."GMT");
|
||||||
header("Last-Modified: ".gmdate("D, d M Y H:i:s")."GMT");
|
header("Cache-Control: no-cache, must-revalidate");
|
||||||
header("Cache-Control: no-cache, must-revalidate");
|
header("Pragma: no-cache");
|
||||||
header("Pragma: no-cache");
|
header("Content-Type:text/xml; charset=UTF-8");
|
||||||
header("Content-Type:text/xml; charset=UTF-8");
|
$out = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
|
||||||
$out = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
|
$out .= "<response>\n";
|
||||||
$out .= "<response>\n";
|
$out .= " <status_code>$array[status_code]</status_code>\n";
|
||||||
$out .= " <status_code>$array[status_code]</status_code>\n";
|
$out .= " <status_txt>$array[status_txt]</status_txt>\n";
|
||||||
$out .= " <status_txt>$array[status_txt]</status_txt>\n";
|
if(count($array["data"])>0) {
|
||||||
if (count($array["data"])>0) {
|
$out .= " <data>\n";
|
||||||
$out .= " <data>\n";
|
foreach($array["data"] as $key => $value) {
|
||||||
foreach ($array["data"] as $key => $value) {
|
$out .= " <$key>$value</$key>\n";
|
||||||
$out .= " <$key>$value</$key>\n";
|
}
|
||||||
}
|
$out .= " </data>\n";
|
||||||
$out .= " </data>\n";
|
}
|
||||||
}
|
$out .= "</response>";
|
||||||
$out .= "</response>";
|
echo $out;
|
||||||
echo $out;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Procedural function to output an array to json
|
// Procedural function to output an array to json
|
||||||
function json_output($data=[], $callback=null)
|
function json_output($data=[], $callback=NULL) {
|
||||||
{
|
error_reporting(0);
|
||||||
error_reporting(0);
|
//@ini_set('display_errors', false);
|
||||||
//@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')) {
|
header('Last-Modified: '.gmdate('D, d M Y H:i:s').'GMT');
|
||||||
ob_start();
|
header('Cache-Control: no-cache, must-revalidate');
|
||||||
}
|
header('Pragma: no-cache');
|
||||||
header('Last-Modified: '.gmdate('D, d M Y H:i:s').'GMT');
|
header('Content-type: application/json; charset=UTF-8');
|
||||||
header('Cache-Control: no-cache, must-revalidate');
|
|
||||||
header('Pragma: no-cache');
|
|
||||||
header('Content-type: application/json; charset=UTF-8');
|
|
||||||
|
|
||||||
// Invalid json request
|
// Invalid json request
|
||||||
if (!G\check_value($data) || (G\check_value($callback) and preg_match('/\W/', $callback))) {
|
if(!G\check_value($data) || (G\check_value($callback) and preg_match('/\W/', $callback))) {
|
||||||
G\set_status_header(400);
|
G\set_status_header(400);
|
||||||
$json_fail = [
|
$json_fail = [
|
||||||
'status_code' => 400,
|
'status_code' => 400,
|
||||||
'status_txt' => G\get_set_status_header_desc(400),
|
'status_txt' => G\get_set_status_header_desc(400),
|
||||||
'error' => [
|
'error' => [
|
||||||
'message' => 'no request data present',
|
'message' => 'no request data present',
|
||||||
'code' => null
|
'code' => NULL
|
||||||
]
|
]
|
||||||
];
|
];
|
||||||
die(json_encode($json_fail));
|
die(json_encode($json_fail));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Populate missing values
|
// Populate missing values
|
||||||
if ($data['status_code'] && !$data['status_txt']) {
|
if($data['status_code'] && !$data['status_txt']){
|
||||||
$data['status_txt'] = G\get_set_status_header_desc($data['status_code']);
|
$data['status_txt'] = G\get_set_status_header_desc($data['status_code']);
|
||||||
}
|
}
|
||||||
|
|
||||||
$json_encode = json_encode($data);
|
$json_encode = json_encode($data);
|
||||||
|
|
||||||
if (!$json_encode) { // Json failed
|
if(!$json_encode) { // Json failed
|
||||||
G\set_status_header(500);
|
G\set_status_header(500);
|
||||||
$json_fail = [
|
$json_fail = [
|
||||||
'status_code' => 500,
|
'status_code' => 500,
|
||||||
'status_txt' => G\get_set_status_header_desc(500),
|
'status_txt' => G\get_set_status_header_desc(500),
|
||||||
'error' => [
|
'error' => [
|
||||||
'message' => "data couldn't be encoded into json",
|
'message' => "data couldn't be encoded into json",
|
||||||
'code' => null
|
'code' => NULL
|
||||||
]
|
]
|
||||||
];
|
];
|
||||||
die(json_encode($json_fail));
|
die(json_encode($json_fail));
|
||||||
}
|
}
|
||||||
G\set_status_header($data['status_code']);
|
G\set_status_header($data['status_code']);
|
||||||
|
|
||||||
if (!is_null($callback)) {
|
if(!is_null($callback)) {
|
||||||
print sprintf('%s(%s);', $callback, $json_encode);
|
print sprintf('%s(%s);', $callback, $json_encode);
|
||||||
} else {
|
} else {
|
||||||
print $json_encode;
|
print $json_encode;
|
||||||
}
|
}
|
||||||
die();
|
die();
|
||||||
}
|
}
|
Loading…
Reference in New Issue