1
0
mirror of https://github.com/monstra-cms/monstra.git synced 2025-08-02 19:27:52 +02:00

Monstra Library: basic core improvments

This commit is contained in:
Awilum
2013-01-04 21:08:04 +02:00
parent 7437cc6abb
commit ef12b7492e
289 changed files with 16265 additions and 17155 deletions

View File

@@ -19,7 +19,7 @@ Options -Indexes
# Setting rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /%siteurlhere%/
RewriteBase /projects/monstra-cms/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

View File

@@ -1,161 +1,159 @@
<?php
/**
* Admin module
*
* @package Monstra
* @author Romanenko Sergey / Awilum [awilum@msn.com]
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
*/
/**
* Admin module
*
* @package Monstra
* @author Romanenko Sergey / Awilum [awilum@msn.com]
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
*/
// Main engine defines
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', rtrim(str_replace(array('admin'), array(''), dirname(__FILE__)), '\\/'));
// Main engine defines
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', rtrim(str_replace(array('admin'), array(''), dirname(__FILE__)), '\\/'));
define('BACKEND', true);
define('MONSTRA_ACCESS', true);
define('BACKEND', true);
define('MONSTRA_ACCESS', true);
// Load bootstrap file
require_once(ROOT . DS . 'monstra' . DS . 'bootstrap.php');
// Load bootstrap file
require_once(ROOT.'/libraries/engine/_init.php');
// Errors var when users login failed
$login_error = '';
// Errors var when users login failed
$login_error = '';
// Get users Table
$users = new Table('users');
// Get users Table
$users = new Table('users');
// Admin login
if (Request::post('login_submit')) {
// Admin login
if (Request::post('login_submit')) {
$user = $users->select("[login='" . trim(Request::post('login')) . "']", null);
if (count($user) !== 0) {
if ($user['login'] == Request::post('login')) {
if (trim($user['password']) == Security::encryptPassword(Request::post('password'))) {
if ($user['role'] == 'admin' || $user['role'] == 'editor') {
Session::set('admin', true);
Session::set('user_id', (int)$user['id']);
Session::set('user_login', (string)$user['login']);
Session::set('user_role', (string)$user['role']);
Request::redirect('index.php');
}
} else {
$login_error = __('Wrong <b>username</b> or <b>password</b>', 'users');
$user = $users->select("[login='" . trim(Request::post('login')) . "']", null);
if (count($user) !== 0) {
if ($user['login'] == Request::post('login')) {
if (trim($user['password']) == Security::encryptPassword(Request::post('password'))) {
if ($user['role'] == 'admin' || $user['role'] == 'editor') {
Session::set('admin', true);
Session::set('user_id', (int) $user['id']);
Session::set('user_login', (string) $user['login']);
Session::set('user_role', (string) $user['role']);
Request::redirect('index.php');
}
} else {
$login_error = __('Wrong <b>username</b> or <b>password</b>', 'users');
}
} else {
$login_error = __('Wrong <b>username</b> or <b>password</b>', 'users');
}
}
// Errors
$errors = array();
$site_url = Option::get('siteurl');
$site_name = Option::get('sitename');
$user_login = trim(Request::post('login'));
// Reset Password Form Submit
if (Request::post('reset_password_submit')) {
if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) $errors['users_captcha_wrong'] = __('Captcha code is wrong', 'users');
if ($user_login == '') $errors['users_empty_field'] = __('Required field', 'users');
if ($user_login != '' && ! $users->select("[login='".$user_login."']")) $errors['users_user_doesnt_exists'] = __('This user doesnt exist', 'users');
if (count($errors) == 0) {
// Get user
$user = $users->select("[login='" . $user_login . "']", null);
// Generate new hash
$new_hash = Text::random('alnum', 12);
// Update user hash
$users->updateWhere("[login='" . $user_login . "']", array('hash' => $new_hash));
// Message
$message = View::factory('box/users/views/frontend/reset_password_email')
->assign('site_url', $site_url)
->assign('site_name', $site_name)
->assign('user_id', $user['id'])
->assign('user_login', $user['login'])
->assign('new_hash', $new_hash)
->render();
// Send
@mail($user['email'], __('Your login details for :site_name', 'users', array(':site_name' => $site_name)), $message);
// Set notification
Notification::set('success', __('Your login details for :site_name has been sent', 'users', array(':site_name' => $site_name)));
Notification::set('reset_password', 'reset_password');
// Redirect to password-reset page
Request::redirect(Site::url().'admin');
}
Notification::setNow('reset_password', 'reset_password');
}
// If admin user is login = true then set is_admin = true
if (Session::exists('admin') && Session::get('admin') == true) {
$is_admin = true;
} else {
$is_admin = false;
$login_error = __('Wrong <b>username</b> or <b>password</b>', 'users');
}
}
// Errors
$errors = array();
$site_url = Option::get('siteurl');
$site_name = Option::get('sitename');
$user_login = trim(Request::post('login'));
// Reset Password Form Submit
if (Request::post('reset_password_submit')) {
if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) $errors['users_captcha_wrong'] = __('Captcha code is wrong', 'users');
if ($user_login == '') $errors['users_empty_field'] = __('Required field', 'users');
if ($user_login != '' && ! $users->select("[login='".$user_login."']")) $errors['users_user_doesnt_exists'] = __('This user doesnt exist', 'users');
if (count($errors) == 0) {
// Get user
$user = $users->select("[login='" . $user_login . "']", null);
// Generate new hash
$new_hash = Text::random('alnum', 12);
// Update user hash
$users->updateWhere("[login='" . $user_login . "']", array('hash' => $new_hash));
// Message
$message = View::factory('box/users/views/frontend/reset_password_email')
->assign('site_url', $site_url)
->assign('site_name', $site_name)
->assign('user_id', $user['id'])
->assign('user_login', $user['login'])
->assign('new_hash', $new_hash)
->render();
// Send
@mail($user['email'], __('Your login details for :site_name', 'users', array(':site_name' => $site_name)), $message);
// Set notification
Notification::set('success', __('Your login details for :site_name has been sent', 'users', array(':site_name' => $site_name)));
Notification::set('reset_password', 'reset_password');
// Redirect to password-reset page
Request::redirect(Site::url().'admin');
}
// Logout user from system
if (Request::get('logout') && Request::get('logout') == 'do') {
Session::destroy();
}
Notification::setNow('reset_password', 'reset_password');
}
// If is admin then load admin area
if ($is_admin) {
// If admin user is login = true then set is_admin = true
if (Session::exists('admin') && Session::get('admin') == true) {
$is_admin = true;
} else {
$is_admin = false;
}
// If id is empty then redirect to default plugin PAGES
if (Request::get('id')) {
$area = Request::get('id');
} else {
Request::redirect('index.php?id=pages');
}
// Logout user from system
if (Request::get('logout') && Request::get('logout') == 'do') {
Session::destroy();
}
$plugins_registered = Plugin::$plugins;
foreach ($plugins_registered as $plugin) {
$plugins_registered_areas[] = $plugin['id'];
}
// Show plugins admin area only for registered plugins
if (in_array($area, $plugins_registered_areas)) {
$plugin_admin_area = true;
} else {
$plugin_admin_area = false;
}
// Backend pre render
Action::run('admin_pre_render');
// Display admin template
require('themes' . DS . Option::get('theme_admin_name') . DS . 'index.template.php');
// Backend post render
Action::run('admin_post_render');
// If is admin then load admin area
if ($is_admin) {
// If id is empty then redirect to default plugin PAGES
if (Request::get('id')) {
$area = Request::get('id');
} else {
// Display login template
require('themes' . DS . Option::get('theme_admin_name') . DS . 'login.template.php');
Request::redirect('index.php?id=pages');
}
// Flush (send) the output buffer and turn off output buffering
ob_end_flush();
$plugins_registered = Plugin::$plugins;
foreach ($plugins_registered as $plugin) {
$plugins_registered_areas[] = $plugin['id'];
}
// Show plugins admin area only for registered plugins
if (in_array($area, $plugins_registered_areas)) {
$plugin_admin_area = true;
} else {
$plugin_admin_area = false;
}
// Backend pre render
Action::run('admin_pre_render');
// Display admin template
require 'themes'. DS . Option::get('theme_admin_name') . DS . 'index.template.php';
// Backend post render
Action::run('admin_post_render');
} else {
// Display login template
require 'themes'. DS . Option::get('theme_admin_name') . DS . 'login.template.php';
}
// Flush (send) the output buffer and turn off output buffering
ob_end_flush();

View File

@@ -41,7 +41,6 @@
});
</script>
<?php Action::run('admin_header'); ?>
<!--[if lt IE 9]>
@@ -89,7 +88,7 @@
<br>
<?php
if (count($errors) > 0) {
foreach($errors as $error) {
foreach ($errors as $error) {
Alert::error($error);
}
}

View File

@@ -1,117 +1,93 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra CMS Defines
*/
/**
* Monstra CMS Defines
*/
/**
* The filesystem path to the site 'themes' folder
*/
define('THEMES_SITE', ROOT . DS . 'public' . DS . 'themes');
/**
* The filesystem path to the 'monstra' folder
*/
define('MONSTRA', ROOT . DS . 'monstra');
/**
* The filesystem path to the admin 'themes' folder
*/
define('THEMES_ADMIN', ROOT . DS . 'admin' . DS . 'themes');
/**
* The filesystem path to the site 'themes' folder
*/
define('THEMES_SITE', ROOT . DS . 'public' . DS . 'themes');
/**
* The filesystem path to the 'plugins' folder
*/
define('PLUGINS', ROOT . DS . 'plugins');
/**
* The filesystem path to the admin 'themes' folder
*/
define('THEMES_ADMIN', ROOT . DS . 'admin' . DS . 'themes');
/**
* The filesystem path to the 'box' folder which is contained within
* the 'plugins' folder
*/
define('PLUGINS_BOX', PLUGINS . DS . 'box');
/**
* The filesystem path to the 'plugins' folder
*/
define('PLUGINS', ROOT . DS . 'plugins');
/**
* The filesystem path to the 'storage' folder
*/
define('STORAGE', ROOT . DS . 'storage');
/**
* The filesystem path to the 'box' folder which is contained within
* the 'plugins' folder
*/
define('PLUGINS_BOX', PLUGINS . DS . 'box');
/**
* The filesystem path to the 'xmldb' folder
*/
define('XMLDB', STORAGE . DS . 'database');
/**
* The filesystem path to the 'helpers' folder which is contained within
* the 'monstra' folder
*/
define('HELPERS', MONSTRA . DS . 'helpers');
/**
* The filesystem path to the 'cache' folder
*/
define('CACHE', ROOT . DS . 'tmp' . DS . 'cache');
/**
* The filesystem path to the 'engine' folder which is contained within
* the 'monstra' folder
*/
define('ENGINE', MONSTRA . DS . 'engine');
/**
* The filesystem path to the 'minify' folder
*/
define('MINIFY', ROOT . DS . 'tmp' . DS . 'minify');
/**
* The filesystem path to the 'boot' folder which is contained within
* the 'monstra' folder
*/
define('BOOT', MONSTRA . DS . 'boot');
/**
* The filesystem path to the 'logs' folder
*/
define('LOGS', ROOT . DS . 'tmp' . DS . 'logs');
/**
* The filesystem path to the 'storage' folder
*/
define('STORAGE', ROOT . DS . 'storage');
/**
* The filesystem path to the 'assets' folder
*/
define('ASSETS', ROOT . DS . 'public' . DS . 'assets');
/**
* The filesystem path to the 'xmldb' folder
*/
define('XMLDB', STORAGE . DS . 'database');
/**
* The filesystem path to the 'uploads' folder
*/
define('UPLOADS', ROOT . DS . 'public' . DS . 'uploads');
/**
* The filesystem path to the 'cache' folder
*/
define('CACHE', ROOT . DS . 'tmp' . DS . 'cache');
/**
* Set password salt
*/
define('MONSTRA_PASSWORD_SALT', 'YOUR_SALT_HERE');
/**
* The filesystem path to the 'minify' folder
*/
define('MINIFY', ROOT . DS . 'tmp' . DS . 'minify');
/**
* Set date format
*/
define('MONSTRA_DATE_FORMAT', 'Y-m-d / H:i:s');
/**
* The filesystem path to the 'logs' folder
*/
define('LOGS', ROOT . DS . 'tmp' . DS . 'logs');
/**
* Set eval php
*/
define('MONSTRA_EVAL_PHP', false);
/**
* The filesystem path to the 'assets' folder
*/
define('ASSETS', ROOT . DS . 'public' . DS . 'assets');
/**
* Check Monstra CMS version
*/
define('CHECK_MONSTRA_VERSION', true);
/**
* The filesystem path to the 'uploads' folder
*/
define('UPLOADS', ROOT . DS . 'public' . DS . 'uploads');
/**
* Set gzip output
*/
define('MONSTRA_GZIP', false);
/**
* Set password salt
*/
define('MONSTRA_PASSWORD_SALT', 'YOUR_SALT_HERE');
/**
* Set date format
*/
define('MONSTRA_DATE_FORMAT', 'Y-m-d / H:i:s');
/**
* Set eval php
*/
define('MONSTRA_EVAL_PHP', false);
/**
* Check Monstra CMS version
*/
define('CHECK_MONSTRA_VERSION', true);
/**
* Set gzip output
*/
define('MONSTRA_GZIP', false);
/**
* Monstra database settings
*/
//define('MONSTRA_DB_DSN', 'mysql:dbname=monstra;host=localhost;port=3306');
//define('MONSTRA_DB_USER', 'root');
//define('MONSTRA_DB_PASSWORD', 'password');
/**
* Monstra database settings
*/
//define('MONSTRA_DB_DSN', 'mysql:dbname=monstra;host=localhost;port=3306');
//define('MONSTRA_DB_USER', 'root');
//define('MONSTRA_DB_PASSWORD', 'password');

117
index.php
View File

@@ -1,67 +1,66 @@
<?php
/**
* Main CMS module
*
* @package Monstra
* @author Romanenko Sergey / Awilum [awilum@msn.com]
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
*/
/**
* Main CMS module
*
* @package Monstra
* @author Romanenko Sergey / Awilum [awilum@msn.com]
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
*/
// Main engine defines
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', rtrim(dirname(__FILE__), '\\/'));
// Main engine defines
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', rtrim(dirname(__FILE__), '\\/'));
define('BACKEND', false);
define('MONSTRA_ACCESS', true);
define('BACKEND', false);
define('MONSTRA_ACCESS', true);
// First check for installer then go
if (file_exists('install.php')) {
if (isset($_GET['install'])) {
if ($_GET['install'] == 'done') {
// Try to delete install file if not delete manually
@unlink('install.php');
// Redirect to main page
header('location: index.php');
}
} else {
include 'install.php';
// First check for installer then go
if (file_exists('install.php')) {
if (isset($_GET['install'])) {
if ($_GET['install'] == 'done') {
// Try to delete install file if not delete manually
@unlink('install.php');
// Redirect to main page
header('location: index.php');
}
} else {
// Load bootstrap file
require_once(ROOT . DS . 'monstra' . DS . 'bootstrap.php');
// Check for maintenance mod
if ('on' == Option::get('maintenance_status')) {
// Set maintenance mode for all except admin and editor
if ((Session::exists('user_role')) and (Session::get('user_role') == 'admin' or Session::get('user_role') == 'editor')) {
// Monstra show this page :)
} else {
die (Text::toHtml(Option::get('maintenance_message')));
}
}
// Frontend pre render
Action::run('frontend_pre_render');
// Load site template
require(MINIFY . DS . 'theme.' . Site::theme() . '.' . Site::template() . '.template.php');
// Frontend pre render
Action::run('frontend_post_render');
// Flush (send) the output buffer and turn off output buffering
ob_end_flush();
include 'install.php';
}
} else {
// Load bootstrap file
require_once(ROOT.'/libraries/engine/_init.php');
// Check for maintenance mod
if ('on' == Option::get('maintenance_status')) {
// Set maintenance mode for all except admin and editor
if ((Session::exists('user_role')) and (Session::get('user_role') == 'admin' or Session::get('user_role') == 'editor')) {
// Monstra show this page :)
} else {
die (Text::toHtml(Option::get('maintenance_message')));
}
}
// Frontend pre render
Action::run('frontend_pre_render');
// Load site template
require(MINIFY . DS . 'theme.' . Site::theme() . '.' . Site::template() . '.template.php');
// Frontend pre render
Action::run('frontend_post_render');
// Flush (send) the output buffer and turn off output buffering
ob_end_flush();
}

View File

@@ -1,455 +0,0 @@
<?php
/**
* Monstra :: Installator
*/
// Main engine defines
if ( ! defined('DS')) define('DS', DIRECTORY_SEPARATOR);
if ( ! defined('ROOT')) define('ROOT', rtrim(dirname(__FILE__), '\\/'));
if ( ! defined('BACKEND')) define('BACKEND', false);
if ( ! defined('MONSTRA_ACCESS')) define('MONSTRA_ACCESS', true);
// Set default timezone
$system_timezone = date_default_timezone_get();
// Load bootstrap file
require_once(ROOT . DS . 'monstra' . DS . 'bootstrap.php');
// Get array with the names of all modules compiled and loaded
$php_modules = get_loaded_extensions();
// Get site URL
$site_url = 'http://'.$_SERVER["SERVER_NAME"].str_replace(array("index.php", "install.php"), "", $_SERVER['PHP_SELF']);
// Rewrite base
$rewrite_base = str_replace(array("index.php", "install.php"), "", $_SERVER['PHP_SELF']);
// Errors array
$errors = array();
// Directories to check
$dir_array = array('public', 'storage', 'backups', 'tmp');
// Languages array
$languages_array = array('en', 'ru', 'lt', 'it', 'de', 'pt-br', 'uk');
// Select Monstra language
if (Request::get('language')) {
if (in_array(Request::get('language'), $languages_array)) {
if (Option::update('language', Request::get('language'))) {
Request::redirect($site_url);
}
} else {
Request::redirect($site_url);
}
}
// If pressed <Install> button then try to install
if (Request::post('install_submit')) {
if (Request::post('sitename') == '') $errors['sitename'] = __('Field "Site name" is empty', 'system');
if (Request::post('siteurl') == '') $errors['siteurl'] = __('Field "Site url" is empty', 'system');
if (Request::post('login') == '') $errors['login'] = __('Field "Username" is empty', 'system');
if (Request::post('password') == '') $errors['password'] = __('Field "Password" is empty', 'system');
if (Request::post('email') == '') $errors['email'] = __('Field "Email" is empty', 'system');
if ( ! Valid::email(Request::post('email'))) $errors['email_valid'] = __('Email not valid', 'system');
if (trim(Request::post('php') !== '')) $errors['php'] = true;
if (trim(Request::post('simplexml') !== '')) $errors['simplexml'] = true;
if (trim(Request::post('mod_rewrite') !== '')) $errors['mod_rewrite'] = true;
if (trim(Request::post('htaccess') !== '')) $errors['htaccess'] = true;
if (trim(Request::post('sitemap') !== '')) $errors['sitemap'] = true;
if (trim(Request::post('install') !== '')) $errors['install'] = true;
if (trim(Request::post('public') !== '')) $errors['public'] = true;
if (trim(Request::post('storage') !== '')) $errors['storage'] = true;
if (trim(Request::post('backups') !== '')) $errors['backups'] = true;
if (trim(Request::post('tmp') !== '')) $errors['tmp'] = true;
// If errors is 0 then install cms
if (count($errors) == 0) {
// Update options
Option::update(array('maintenance_status' => 'off',
'sitename' => Request::post('sitename'),
'siteurl' => Request::post('siteurl'),
'description' => __('Site description', 'system'),
'keywords' => __('Site keywords', 'system'),
'slogan' => __('Site slogan', 'system'),
'defaultpage' => 'home',
'timezone' => Request::post('timezone'),
'theme_site_name' => 'default',
'theme_admin_name' => 'default'));
// Get users table
$users = new Table('users');
// Insert new user with role = admin
$users->insert(array('login' => Security::safeName(Request::post('login')),
'password' => Security::encryptPassword(Request::post('password')),
'email' => Request::post('email'),
'hash' => Text::random('alnum', 12),
'date_registered' => time(),
'role' => 'admin'));
// Write .htaccess
$htaccess = file_get_contents('.htaccess');
$save_htaccess_content = str_replace("/%siteurlhere%/", $rewrite_base, $htaccess);
$handle = fopen ('.htaccess', "w");
fwrite($handle, $save_htaccess_content);
fclose($handle);
// Installation done :)
header("location: index.php?install=done");
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Monstra :: Install</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Monstra Install Area">
<link rel="icon" href="<?php echo $site_url; ?>favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="<?php echo $site_url; ?>favicon.ico" type="image/x-icon" />
<link rel="stylesheet" href="<?php echo $site_url; ?>public/assets/css/bootstrap.css" media="all" type="text/css" />
<link rel="stylesheet" href="<?php echo $site_url; ?>public/assets/css/bootstrap-responsive.css" media="all" type="text/css" />
<link rel="stylesheet" href="<?php echo $site_url; ?>admin/themes/default/css/default.css" media="all" type="text/css" />
<style>
.input-xlarge {
width: 285px;
}
.install-languages {
margin: 0 auto;
float: none!important;
margin-bottom:5px;
padding-right:20px;
max-width: 300px;
}
.install-block {
margin: 0 auto;
float: none!important;
max-width: 300px;
padding: 19px 29px 29px;
background: none repeat scroll 0 0 #fff;
-webkit-box-shadow: 0 1px 5px rgba(0,0,0,.15);
-moz-box-shadow: 0 1px 5px rgba(0,0,0,.15);
box-shadow: 0 1px 5px rgba(0,0,0,.15);
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.install-block-footer {
margin: 0 auto;
float: none!important;
margin-top:10px;
margin-bottom:10px;
max-width: 300px;
}
.install-body {
background-color: #FBFBFB;
padding-top:40px;
}
.error {
color:#8E0505;
}
.ok {
color:#00853F;
}
.warn {
color: #F74C18;
}
.language-link {
color:#7A7A7C;
}
.language-link+.language-link:before {
color: #ccc;
content: ' | ';
}
.language-link:hover {
color:#000;
text-decoration: none;
}
.language-link-current {
color:#000;
font-weight: 700;
}
</style>
</head>
<body class="install-body">
<?php
if (version_compare(PHP_VERSION, "5.2.0", "<")) {
$errors['php'] = 'error';
} else {
$errors['php'] = '';
}
if (in_array('SimpleXML', $php_modules)) {
$errors['simplexml'] = '';
} else {
$errors['simplexml'] = 'error';
}
if (function_exists('apache_get_modules')) {
if ( ! in_array('mod_rewrite', apache_get_modules())) {
$errors['mod_rewrite'] = 'error';
} else {
$errors['mod_rewrite'] = '';
}
} else {
$errors['mod_rewrite'] = '';
}
if (is_writable(__FILE__)) {
$errors['install'] = '';
} else {
$errors['install'] = 'error';
}
if (is_writable('sitemap.xml')){
$errors['sitemap'] = '';
} else {
$errors['sitemap'] = 'error';
}
if (is_writable('.htaccess')){
$errors['htaccess'] = '';
} else {
$errors['htaccess'] = 'error';
}
// Dirs 'public', 'storage', 'backups', 'tmp'
foreach ($dir_array as $dir) {
if (is_writable($dir.'/')) {
$errors[$dir] = '';
} else {
$errors[$dir] = 'error';
}
}
?>
<div class="install-languages">
<?php foreach($languages_array as $lang_code){?>
<a class="language-link<?php if (Option::get('language') == $lang_code) echo ' language-link-current';?>" href="<?php echo $site_url.'?language=' . $lang_code; ?>"><?php echo $lang_code?></a>
<?php } ?>
</div>
<div class="install-block">
<div style="text-align:center;"><a class="brand" href="<?php echo Html::toText($site_url); ?>"><img src="<?php echo $site_url; ?>public/assets/img/monstra-logo.png" height="27" width="171" alt="Monstra"></a></div>
<hr>
<div>
<form action="install.php" method="post">
<input type="hidden" name="php" value="<?php echo $errors['php']; ?>" />
<input type="hidden" name="simplexml" value="<?php echo $errors['simplexml']; ?>" />
<input type="hidden" name="mod_rewrite" value="<?php echo $errors['mod_rewrite']; ?>" />
<input type="hidden" name="install" value="<?php echo $errors['install']; ?>" />
<input type="hidden" name="sitemap" value="<?php echo $errors['sitemap']; ?>" />
<input type="hidden" name="htaccess" value="<?php echo $errors['htaccess']; ?>" />
<input type="hidden" name="public" value="<?php echo $errors['public']; ?>" />
<input type="hidden" name="storage" value="<?php echo $errors['storage']; ?>" />
<input type="hidden" name="backups" value="<?php echo $errors['backups']; ?>" />
<input type="hidden" name="tmp" value="<?php echo $errors['tmp']; ?>" />
<label><?php echo __('Site name', 'system'); ?></label>
<input class="input-xlarge" name="sitename" type="text" value="<?php if (Request::post('sitename')) echo Html::toText(Request::post('sitename')); ?>" />
<br />
<label><?php echo __('Site url', 'system'); ?></label>
<input class="input-xlarge" name="siteurl" type="text" value="<?php echo Html::toText($site_url); ?>" />
<br />
<label><?php echo __('Username', 'users'); ?></label>
<input class="input-xlarge" class="login" name="login" value="<?php if(Request::post('login')) echo Html::toText(Request::post('login')); ?>" type="text" />
<br />
<label><?php echo __('Password', 'users'); ?></label>
<input class="input-xlarge" name="password" type="password" />
<br />
<label><?php echo __('Time zone', 'system'); ?></label>
<select class="input-xlarge" name="timezone">
<option value="Kwajalein">(GMT-12:00) International Date Line West</option>
<option value="Pacific/Samoa">(GMT-11:00) Midway Island, Samoa</option>
<option value="Pacific/Honolulu">(GMT-10:00) Hawaii</option>
<option value="America/Anchorage">(GMT-09:00) Alaska</option>
<option value="America/Los_Angeles">(GMT-08:00) Pacific Time (US &amp; Canada)</option>
<option value="America/Tijuana">(GMT-08:00) Tijuana, Baja California</option>
<option value="America/Denver">(GMT-07:00) Mountain Time (US &amp; Canada)</option>
<option value="America/Chihuahua">(GMT-07:00) Chihuahua, La Paz, Mazatlan</option>
<option value="America/Phoenix">(GMT-07:00) Arizona</option>
<option value="America/Regina">(GMT-06:00) Saskatchewan</option>
<option value="America/Tegucigalpa">(GMT-06:00) Central America</option>
<option value="America/Chicago">(GMT-06:00) Central Time (US &amp; Canada)</option>
<option value="America/Mexico_City">(GMT-06:00) Guadalajara, Mexico City, Monterrey</option>
<option value="America/New_York">(GMT-05:00) Eastern Time (US &amp; Canada)</option>
<option value="America/Bogota">(GMT-05:00) Bogota, Lima, Quito, Rio Branco</option>
<option value="America/Indiana/Indianapolis">(GMT-05:00) Indiana (East)</option>
<option value="America/Caracas">(GMT-04:30) Caracas</option>
<option value="America/Halifax">(GMT-04:00) Atlantic Time (Canada)</option>
<option value="America/Manaus">(GMT-04:00) Manaus</option>
<option value="America/Santiago">(GMT-04:00) Santiago</option>
<option value="America/La_Paz">(GMT-04:00) La Paz</option>
<option value="America/St_Johns">(GMT-03:30) Newfoundland</option>
<option value="America/Argentina/Buenos_Aires">(GMT-03:00) Buenos Aires</option>
<option value="America/Sao_Paulo">(GMT-03:00) Brasilia</option>
<option value="America/Godthab">(GMT-03:00) Greenland</option>
<option value="America/Montevideo">(GMT-03:00) Montevideo</option>
<option value="America/Argentina/Buenos_Aires">(GMT-03:00) Georgetown</option>
<option value="Atlantic/South_Georgia">(GMT-02:00) Mid-Atlantic</option>
<option value="Atlantic/Azores">(GMT-01:00) Azores</option>
<option value="Atlantic/Cape_Verde">(GMT-01:00) Cape Verde Is.</option>
<option value="Europe/London">(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London</option>
<option value="Atlantic/Reykjavik">(GMT) Monrovia, Reykjavik</option>
<option value="Africa/Casablanca">(GMT) Casablanca</option>
<option value="Europe/Belgrade">(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague</option>
<option value="Europe/Sarajevo">(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb</option>
<option value="Europe/Brussels">(GMT+01:00) Brussels, Copenhagen, Madrid, Paris</option>
<option value="Africa/Algiers">(GMT+01:00) West Central Africa</option>
<option value="Europe/Amsterdam">(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna</option>
<option value="Africa/Cairo">(GMT+02:00) Cairo</option>
<option value="Europe/Helsinki">(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius</option>
<option value="Europe/Athens">(GMT+02:00) Athens, Bucharest, Istanbul</option>
<option value="Asia/Jerusalem">(GMT+02:00) Jerusalem</option>
<option value="Asia/Amman">(GMT+02:00) Amman</option>
<option value="Asia/Beirut">(GMT+02:00) Beirut</option>
<option value="Africa/Windhoek">(GMT+02:00) Windhoek</option>
<option value="Africa/Harare">(GMT+02:00) Harare, Pretoria</option>
<option value="Asia/Kuwait">(GMT+03:00) Kuwait, Riyadh</option>
<option value="Asia/Baghdad">(GMT+03:00) Baghdad</option>
<option value="Europe/Minsk">(GMT+03:00) Minsk</option>
<option value="Africa/Nairobi">(GMT+03:00) Nairobi</option>
<option value="Asia/Tbilisi">(GMT+03:00) Tbilisi</option>
<option value="Asia/Tehran">(GMT+03:30) Tehran</option>
<option value="Asia/Muscat">(GMT+04:00) Abu Dhabi, Muscat</option>
<option value="Asia/Baku">(GMT+04:00) Baku</option>
<option value="Europe/Moscow">(GMT+04:00) Moscow, St. Petersburg, Volgograd</option>
<option value="Asia/Yerevan">(GMT+04:00) Yerevan</option>
<option value="Asia/Karachi">(GMT+05:00) Islamabad, Karachi</option>
<option value="Asia/Tashkent">(GMT+05:00) Tashkent</option>
<option value="Asia/Kolkata">(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi</option>
<option value="Asia/Colombo">(GMT+05:30) Sri Jayawardenepura</option>
<option value="Asia/Katmandu">(GMT+05:45) Kathmandu</option>
<option value="Asia/Dhaka">(GMT+06:00) Astana, Dhaka</option>
<option value="Asia/Yekaterinburg">(GMT+06:00) Ekaterinburg</option>
<option value="Asia/Rangoon">(GMT+06:30) Yangon (Rangoon)</option>
<option value="Asia/Novosibirsk">(GMT+07:00) Almaty, Novosibirsk</option>
<option value="Asia/Bangkok">(GMT+07:00) Bangkok, Hanoi, Jakarta</option>
<option value="Asia/Beijing">(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi</option>
<option value="Asia/Krasnoyarsk">(GMT+08:00) Krasnoyarsk</option>
<option value="Asia/Ulaanbaatar">(GMT+08:00) Irkutsk, Ulaan Bataar</option>
<option value="Asia/Kuala_Lumpur">(GMT+08:00) Kuala Lumpur, Singapore</option>
<option value="Asia/Taipei">(GMT+08:00) Taipei</option>
<option value="Australia/Perth">(GMT+08:00) Perth</option>
<option value="Asia/Seoul">(GMT+09:00) Seoul</option>
<option value="Asia/Tokyo">(GMT+09:00) Osaka, Sapporo, Tokyo</option>
<option value="Australia/Darwin">(GMT+09:30) Darwin</option>
<option value="Australia/Adelaide">(GMT+09:30) Adelaide</option>
<option value="Australia/Sydney">(GMT+10:00) Canberra, Melbourne, Sydney</option>
<option value="Australia/Brisbane">(GMT+10:00) Brisbane</option>
<option value="Australia/Hobart">(GMT+10:00) Hobart</option>
<option value="Asia/Yakutsk">(GMT+10:00) Yakutsk</option>
<option value="Pacific/Guam">(GMT+10:00) Guam, Port Moresby</option>
<option value="Asia/Vladivostok">(GMT+11:00) Vladivostok</option>
<option value="Pacific/Fiji">(GMT+12:00) Fiji, Kamchatka, Marshall Is.</option>
<option value="Asia/Magadan">(GMT+12:00) Magadan, Solomon Is., New Caledonia</option>
<option value="Pacific/Auckland">(GMT+12:00) Auckland, Wellington</option>
<option value="Pacific/Tongatapu">(GMT+13:00) Nukualofa</option>
</select>
<label><?php echo __('Email', 'users'); ?></label>
<input name="email" class="input-xlarge" value="<?php if (Request::post('email')) echo Html::toText(Request::post('email')); ?>" type="text" />
<br /><br />
<input type="submit" class="btn" name="install_submit" value="<?php echo __('Install', 'system'); ?>" />
</form>
</div>
<hr>
<p align="center"><strong><?php echo __('...Monstra says...', 'system'); ?></strong></p>
<div>
<ul>
<?php
if (version_compare(PHP_VERSION, "5.2.0", "<")) {
echo '<span class="error"><li>'.__('PHP 5.2 or greater is required', 'system').'</li></span>';
} else {
echo '<span class="ok"><li>'.__('PHP Version', 'system').' '.PHP_VERSION.'</li></span>';
}
if (in_array('SimpleXML', $php_modules)) {
echo '<span class="ok"><li>'.__('Module SimpleXML is installed', 'system').'</li></span>';
} else {
echo '<span class="error"><li>'.__('SimpleXML module is required', 'system').'</li></span>';
}
if (in_array('dom', $php_modules)) {
echo '<span class="ok"><li>'.__('Module DOM is installed', 'system').'</li></span>';
} else {
echo '<span class="error"><li>'.__('Module DOM is required', 'system').'</li></span>';
}
if (function_exists('apache_get_modules')) {
if ( ! in_array('mod_rewrite',apache_get_modules())) {
echo '<span class="error"><li>'.__('Apache Mod Rewrite is required', 'system').'</li></span>';
} else {
echo '<span class="ok"><li>'.__('Module Mod Rewrite is installed', 'system').'</li></span>';
}
} else {
echo '<span class="ok"><li>'.__('Module Mod Rewrite is installed', 'system').'</li></span>';
}
foreach ($dir_array as $dir) {
if (is_writable($dir.'/')) {
echo '<span class="ok"><li>'.__('Directory: <b> :dir </b> writable', 'system', array(':dir' => $dir)).'</li></span>';
} else {
echo '<span class="error"><li>'.__('Directory: <b> :dir </b> not writable', 'system', array(':dir' => $dir)).'</li></span>';
}
}
if (is_writable(__FILE__)){
echo '<span class="ok"><li>'.__('Install script writable', 'system').'</li></span>';
} else {
echo '<span class="error"><li>'.__('Install script not writable', 'system').'</li></span>';
}
if (is_writable('sitemap.xml')){
echo '<span class="ok"><li>'.__('Sitemap file writable', 'system').'</li></span>';
} else {
echo '<span class="error"><li>'.__('Sitemap file not writable', 'system').'</li></span>';
}
if (is_writable('.htaccess')){
echo '<span class="ok"><li>'.__('Main .htaccess file writable', 'system').'</li></span>';
} else {
echo '<span class="error"><li>'.__('Main .htaccess file not writable', 'system').'</li></span>';
}
if (isset($errors['sitename'])) echo '<span class="error"><li>'.$errors['sitename'].'</li></span>';
if (isset($errors['siteurl'])) echo '<span class="error"><li>'.$errors['siteurl'].'</li></span>';
if (isset($errors['login'])) echo '<span class="error"><li>'.$errors['login'].'</li></span>';
if (isset($errors['password'])) echo '<span class="error"><li>'.$errors['password'].'</li></span>';
if (isset($errors['email'])) echo '<span class="error"><li>'.$errors['email'].'</li></span>';
if (isset($errors['email_valid'])) echo '<span class="error"><li>'.$errors['email_valid'].'</li></span>';
?>
</ul>
</div>
</div>
<div class="install-block-footer">
<div style="text-align:center">
<span class="small-grey-text">© 2012 <a href="http://monstra.org" class="small-grey-text" target="_blank">Monstra</a> <?php echo __('Version', 'system'); ?> <?php echo Core::VERSION; ?></span>
</div>
</div>
</body>
</html>

489
libraries/engine/Core.php Normal file
View File

@@ -0,0 +1,489 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Main Monstra engine module. Core module.
*
* Monstra - Content Management System.
* Site: mostra.org
* Copyright (C) 2012 Romanenko Sergey / Awilum [awilum@msn.com]
*
* @package Monstra
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
*/
class Core
{
/**
* An instance of the Core class
*
* @var core
*/
protected static $instance = null;
/**
* Common environment type constants for consistency and convenience
*/
const PRODUCTION = 1;
const STAGING = 2;
const TESTING = 3;
const DEVELOPMENT = 4;
/**
* The version of Monstra
*/
const VERSION = '2.1.3';
/**
* Monstra environment
*
* @var string
*/
public static $environment = Core::PRODUCTION;
/**
* Protected clone method to enforce singleton behavior.
*
* @access protected
*/
protected function __clone()
{
// Nothing here.
}
/**
* Construct
*/
protected function __construct()
{
// Load core defines
Core::loadDefines();
/**
* Compress HTML with gzip
*/
if (MONSTRA_GZIP) {
if ( ! ob_start("ob_gzhandler")) ob_start();
} else {
ob_start();
}
/**
* Send default header and set internal encoding
*/
header('Content-Type: text/html; charset=UTF-8');
function_exists('mb_language') AND mb_language('uni');
function_exists('mb_regex_encoding') AND mb_regex_encoding('UTF-8');
function_exists('mb_internal_encoding') AND mb_internal_encoding('UTF-8');
/**
* Gets the current configuration setting of magic_quotes_gpc
* and kill magic quotes
*/
if (get_magic_quotes_gpc()) {
function stripslashesGPC(&$value) { $value = stripslashes($value); }
array_walk_recursive($_GET, 'stripslashesGPC');
array_walk_recursive($_POST, 'stripslashesGPC');
array_walk_recursive($_COOKIE, 'stripslashesGPC');
array_walk_recursive($_REQUEST, 'stripslashesGPC');
}
// Error handling for Developers only.
if (Core::$environment != Core::PRODUCTION) {
// Set error handler
set_error_handler('Core::errorHandler');
// Set fatal error handler
register_shutdown_function('Core::fatalErrorHandler');
// Set exception handler
set_exception_handler('Core::exceptionHandler');
}
// Start session
Session::start();
// Init ORM
if (defined('MONSTRA_DB_DSN')) {
ORM::configure(MONSTRA_DB_DSN);
ORM::configure('username', MONSTRA_DB_USER);
ORM::configure('password', MONSTRA_DB_PASSWORD);
}
// Auto cleanup if MONSTRA_DEBUG is true
if (Core::$environment == Core::DEVELOPMENT) {
// Cleanup minify
if (count($files = File::scan(MINIFY, array('css', 'js', 'php'))) > 0) foreach ($files as $file) File::delete(MINIFY . DS . $file);
// Cleanup cache
if (count($namespaces = Dir::scan(CACHE)) > 0) foreach ($namespaces as $namespace) Dir::delete(CACHE . DS . $namespace);
}
// Load URI module
require_once(ROOT . '/libraries/engine/Uri.php');
// Load XMLDB API module
require_once(ROOT . '/libraries/engine/Xmldb.php');
// Load Options API module
require_once(ROOT . '/libraries/engine/Options.php');
// Init Options API module
Option::init();
// Set default timezone
@ini_set('date.timezone', Option::get('timezone'));
if (function_exists('date_default_timezone_set')) date_default_timezone_set(Option::get('timezone')); else putenv('TZ='.Option::get('timezone'));
// Sanitize URL to prevent XSS - Cross-site scripting
Security::runSanitizeURL();
// Load Plugins API module
require_once(ROOT . '/libraries/engine/Plugins.php');
// Load Shortcodes API module
require_once(ROOT . '/libraries/engine/Shortcodes.php');
// Load default
Core::loadPluggable();
// Init I18n
I18n::init(Option::get('language'));
// Init Plugins API
Plugin::init();
// Init Notification service
Notification::init();
// Load Site module
require_once(ROOT . '/libraries/engine/Site.php');
// Init site module
if( ! BACKEND) Site::init();
}
/**
* Autoload helpers
*
* @param string $class_name Class name
*/
/*protected static function autoloadHelpers($class_name) {
if (file_exists($path = HELPERS . DS . strtolower($class_name) . '.php')) include $path;
}*/
/**
* Load Defines
*/
protected static function loadDefines()
{
$environments = array(1 => 'production',
2 => 'staging',
3 => 'testing',
4 => 'development');
$root_defines = ROOT . DS . 'boot' . DS . 'defines.php';
$environment_defines = ROOT . DS . 'boot' . DS . $environments[Core::$environment] . DS . 'defines.php';
$monstra_defines = ROOT . DS . 'libraries/engine' . DS . 'boot' . DS . 'defines.php';
if (file_exists($root_defines)) {
include $root_defines;
} elseif (file_exists($environment_defines)) {
include $environment_defines;
} elseif (file_exists($monstra_defines)) {
include $monstra_defines;
} else {
throw new RuntimeException("The defines file does not exist.");
}
}
/**
* Load Pluggable
*/
protected static function loadPluggable()
{
$environments = array(1 => 'production',
2 => 'staging',
3 => 'testing',
4 => 'development');
$root_pluggable = ROOT . DS . 'boot';
$environment_pluggable = ROOT . DS . 'boot' . DS . $environments[Core::$environment];
$monstra_pluggable = ROOT . DS . 'libraries/engine' . DS . 'boot';
if (file_exists($root_pluggable . DS . 'filters.php')) {
include $root_pluggable . DS . 'filters.php';
} elseif (file_exists($environment_pluggable . DS . 'filters.php')) {
include $environment_pluggable . DS . 'filters.php';
} elseif (file_exists($monstra_pluggable . DS . 'filters.php')) {
include $monstra_pluggable . DS . 'filters.php';
} else {
throw new RuntimeException("The pluggable file does not exist.");
}
if (file_exists($root_pluggable . DS . 'actions.php')) {
include $root_pluggable . DS . 'actions.php';
} elseif (file_exists($environment_pluggable . DS . 'actions.php')) {
include $environment_pluggable . DS . 'actions.php';
} elseif (file_exists($monstra_pluggable . DS . 'actions.php')) {
include $monstra_pluggable . DS . 'actions.php';
} else {
throw new RuntimeException("The pluggable file does not exist.");
}
if (file_exists($root_pluggable . DS . 'shortcodes.php')) {
include $root_pluggable . DS . 'shortcodes.php';
} elseif (file_exists($environment_pluggable . DS . 'shortcodes.php')) {
include $environment_pluggable . DS . 'shortcodes.php';
} elseif (file_exists($monstra_pluggable . DS . 'shortcodes.php')) {
include $monstra_pluggable . DS . 'shortcodes.php';
} else {
throw new RuntimeException("The pluggable file does not exist.");
}
}
/**
* Exception Handler
*
* @param object $exception An exception object
*/
public static function exceptionHandler($exception)
{
// Empty output buffers
while (ob_get_level() > 0) ob_end_clean();
// Send headers and output
@header('Content-Type: text/html; charset=UTF-8');
@header('HTTP/1.1 500 Internal Server Error');
// Get highlighted code
$code = Core::highlightCode($exception->getFile(), $exception->getLine());
// Determine error type
if ($exception instanceof ErrorException) {
$error_type = 'ErrorException: ';
$codes = array (
E_ERROR => 'Fatal Error',
E_PARSE => 'Parse Error',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_STRICT => 'Strict Mode Error',
E_NOTICE => 'Notice',
E_WARNING => 'Warning',
E_RECOVERABLE_ERROR => 'Recoverable Error',
/*E_DEPRECATED => 'Deprecated',*/ /* PHP 5.3 */
E_USER_NOTICE => 'Notice',
E_USER_WARNING => 'Warning',
E_USER_ERROR => 'Error',
/*E_USER_DEPRECATED => 'Deprecated'*/ /* PHP 5.3 */
);
$error_type .= in_array($exception->getCode(), array_keys($codes)) ? $codes[$exception->getCode()] : 'Unknown Error';
} else {
$error_type = get_class($exception);
}
// Show exception if core environment is DEVELOPMENT
if (Core::$environment == Core::DEVELOPMENT) {
// Development
echo ("
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Monstra</title>
<style>
* { margin: 0; padding: 0; }
body { background-color: #EEE; }
h1,h2,h3,p{font-family:Verdana;font-weight:lighter;margin:10px;}
.exception {border: 1px solid #CCC; padding: 10px; background-color: #FFF; color: #333; margin:10px;}
pre, .code {font-family: Courier, monospace; font-size:12px;margin:0px;padding:0px;}
.highlighted {background-color: #f0eb96; font-weight: bold; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc;}
.code {background:#fff;border:1px solid #ccc;overflow:auto;}
.line {display: inline-block; background-color: #EFEFEF; padding: 4px 8px 4px 8px; margin-right:10px; }
</style>
</head>
<body>
<div class='exception'>
<h1>Monstra - ".$error_type."</h1>
<p>".$exception->getMessage()."</p>
<h2>Location</h2>
<p>Exception thrown on line <code>".$exception->getLine()."</code> in <code>".$exception->getFile()."</code></p>
");
if ( ! empty($code)) {
echo '<div class="code">';
foreach ($code as $line) {
echo '<pre '; if ($line['highlighted']) { echo 'class="highlighted"'; } echo '><span class="line">' . $line['number'] . '</span>' . $line['code'] . '</pre>';
}
echo '</div>';
}
echo '</div></body></html>';
} else {
// Production
echo ("
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Monstra</title>
<style>
* { margin: 0; padding: 0; }
.exception {border: 1px solid #CCC; padding: 10px; background-color: #FFF; color: #333; margin:10px;}
body { background-color: #EEE; font-family: sans-serif; font-size: 16px; line-height: 20px; margin: 40px; }
h1,h2,h3,p{font-family:Verdana;font-weight:lighter;margin:10px;}
</style>
</head>
<body>
<div class='exception'>
<h1>Oops!</h1>
<p>An unexpected error has occurred.</p>
</div>
</body>
</html>
");
}
// Writes message to log
@file_put_contents(LOGS . DS . gmdate('Y_m_d') . '.log',
gmdate('Y/m/d H:i:s') . ' --- ' . '['.$error_type.']' . ' --- ' . $exception->getMessage() . ' --- ' . 'Exception thrown on line '.$exception->getLine().' in '.$exception->getFile() . "\n",
FILE_APPEND);
exit(1);
}
/**
* Converts errors to ErrorExceptions.
*
* @param integer $code The error code
* @param string $message The error message
* @param string $file The filename where the error occurred
* @param integer $line The line number where the error occurred
* @return boolean
*/
public static function errorHandler($code, $message, $file, $line)
{
// If isset error_reporting and $code then throw new error exception
if ((error_reporting() & $code) !== 0) {
throw new ErrorException($message, $code, 0, $file, $line);
}
// Don't execute PHP internal error handler
return true;
}
/**
* Returns an array of lines from a file.
*
* @param string $file File in which you want to highlight a line
* @param integer $line Line number to highlight
* @param integer $padding Number of padding lines
* @return array
*/
protected static function highlightCode($file, $line, $padding = 5)
{
// Is file readable ?
if ( ! is_readable($file)) {
return false;
}
// Init vars
$lines = array();
$current_line = 0;
// Open file
$handle = fopen($file, 'r');
// Read file
while ( ! feof($handle)) {
$current_line++;
$temp = fgets($handle);
if ($current_line > $line + $padding) {
break; // Exit loop after we have found what we were looking for
}
if ($current_line >= ($line - $padding) && $current_line <= ($line + $padding)) {
$lines[] = array (
'number' => str_pad($current_line, 4, ' ', STR_PAD_LEFT),
'highlighted' => ($current_line === $line),
'code' => Core::highlightString($temp),
);
}
}
// Close
fclose($handle);
// Return lines
return $lines;
}
/**
* Highlight string
*
* @param string $string String
* @return string
*/
protected static function highlightString($string)
{
return str_replace(array("\n", '<code>', '</code>', '<span style="color: #0000BB">&lt;?php&nbsp;', '#$@r4!/*'),
array('', '', '', '<span style="color: #0000BB">', '/*'),
highlight_string('<?php ' . str_replace('/*', '#$@r4!/*', $string), true));
}
/**
* Convert errors not caught by the errorHandler to ErrorExceptions.
*/
public static function fatalErrorHandler()
{
// Get last error
$error = error_get_last();
// If isset error then throw new error exception
if (isset($error) && ($error['type'] === E_ERROR)) {
Core::exceptionHandler(new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']));
exit(1);
}
}
/**
* Initialize Monstra engine
*
* @return Core
*/
public static function init()
{
if ( ! isset(self::$instance)) self::$instance = new Core();
return self::$instance;
}
}

View File

@@ -0,0 +1,183 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra Options API module
*
* @package Monstra
* @subpackage Engine
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Option
{
/**
* Options
*
* @var array
*/
protected static $options = null;
/**
* An instance of the Option class
*
* @var option
*/
protected static $instance = null;
/**
* Initializing options
*
* @param string $name Options file
*/
public static function init()
{
if ( ! isset(self::$instance)) self::$instance = new Option();
return self::$instance;
}
/**
* Protected clone method to enforce singleton behavior.
*
* @access protected
*/
protected function __clone()
{
// Nothing here.
}
/**
* Construct
*/
protected function __construct()
{
Option::$options = new Table('options');
}
/**
* Add a new option
*
* <code>
* Option::add('pages_limit', 10);
* Option::add(array('pages_count' => 10, 'pages_default' => 'home'));
* </code>
*
* @param mixed $option Name of option to add.
* @param mixed $value Option value.
* @return boolean
*/
public static function add($option, $value = null)
{
if (is_array($option)) {
foreach ($option as $k => $v) {
$_option = Option::$options->select('[name="'.$k.'"]', null);
if (count($_option) == 0) {
Option::$options->insert(array('name' => $k, 'value' => $v));
}
}
} else {
$_option = Option::$options->select('[name="'.$option.'"]', null);
if (count($_option) == 0) {
return Option::$options->insert(array('name' => $option, 'value' => $value));
}
}
}
/**
* Update option value
*
* <code>
* Option::update('pages_limit', 12);
* Option::update(array('pages_count' => 10, 'pages_default' => 'home'));
* </code>
*
* @param mixed $option Name of option to update.
* @param mixed $value Option value.
* @return boolean
*/
public static function update($option, $value = null)
{
if (is_array($option)) {
foreach ($option as $k => $v) {
Option::$options->updateWhere('[name="'.$k.'"]', array('value' => $v));
}
} else {
return Option::$options->updateWhere('[name="'.$option.'"]', array('value' => $value));
}
}
/**
* Get option value
*
* <code>
* $pages_limit = Option::get('pages_limit');
* if ($pages_limit == '10') {
* // do something...
* }
* </code>
*
* @param string $option Name of option to get.
* @return string
*/
public static function get($option)
{
// Redefine vars
$option = (string) $option;
// Select specific option
$option_name = Option::$options->select('[name="'.$option.'"]', null);
// Return specific option value
return isset($option_name['value']) ? $option_name['value'] : '';
}
/**
* Delete option
*
* <code>
* Option::delete('pages_limit');
* </code>
*
* @param string $option Name of option to delete.
* @return boolean
*/
public static function delete($option)
{
// Redefine vars
$option = (string) $option;
// Delete specific option
return Option::$options->deleteWhere('[name="'.$option.'"]');
}
/**
* Check if option exist
*
* <code>
* if (Option::exists('pages_limit')) {
* // do something...
* }
* </code>
*
* @param string $option Name of option to check.
* @return boolean
*/
public static function exists($option)
{
// Redefine vars
$option = (string) $option;
// Check if option exists
return (count(Option::$options->select('[name="'.$option.'"]', null)) > 0) ? true : false;
}
}

1228
libraries/engine/Plugins.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,180 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra Shortcodes API
*
* The Shortcode API s a simple regex based parser that allows you to replace simple bbcode-like tags
* within a HTMLText or HTMLVarchar field when rendered into a content.
*
* Examples of shortcode tags:
*
* {shortcode}
* {shortcode parameter="value"}
* {shortcode parameter="value"}Enclosed Content{/shortcode}
*
*
* Example of escaping shortcodes:
*
* {{shortcode}}
*
*
* @package Monstra
* @subpackage Engine
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Shortcode
{
/**
* Shortcode tags array
*
* @var shortcode_tags
*/
protected static $shortcode_tags = array();
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Add new shortcode
*
* <code>
* function returnSiteUrl() {
* return Option::get('siteurl');
* }
*
* // Add shortcode {siteurl}
* Shortcode::add('siteurl', 'returnSiteUrl');
* </code>
*
* @param string $shortcode Shortcode tag to be searched in content.
* @param string $callback_function The callback function to replace the shortcode with.
*/
public static function add($shortcode, $callback_function)
{
// Redefine vars
$shortcode = (string) $shortcode;
// Add new shortcode
if (is_callable($callback_function)) Shortcode::$shortcode_tags[$shortcode] = $callback_function;
}
/**
* Remove a specific registered shortcode.
*
* <code>
* Shortcode::delete('shortcode_name');
* </code>
*
* @param string $shortcode Shortcode tag.
*/
public static function delete($shortcode)
{
// Redefine vars
$shortcode = (string) $shortcode;
// Delete shortcode
if (Shortcode::exists($shortcode)) unset(Shortcode::$shortcode_tags[$shortcode]);
}
/**
* Remove all registered shortcodes.
*
* <code>
* Shortcode::clear();
* </code>
*
*/
public static function clear()
{
Shortcode::$shortcode_tags = array();
}
/**
* Check if a shortcode has been registered.
*
* <code>
* if (Shortcode::exists('shortcode_name')) {
* // do something...
* }
* </code>
*
* @param string $shortcode Shortcode tag.
*/
public static function exists($shortcode)
{
// Redefine vars
$shortcode = (string) $shortcode;
// Check shortcode
return array_key_exists($shortcode, Shortcode::$shortcode_tags);
}
/**
* Parse a string, and replace any registered shortcodes within it with the result of the mapped callback.
*
* <code>
* $content = Shortcode::parse($content);
* </code>
*
* @param string $content Content
* @return string
*/
public static function parse($content)
{
if ( ! Shortcode::$shortcode_tags) return $content;
$shortcodes = implode('|', array_map('preg_quote', array_keys(Shortcode::$shortcode_tags)));
$pattern = "/(.?)\{([$shortcodes]+)(.*?)(\/)?\}(?(4)|(?:(.+?)\{\/\s*\\2\s*\}))?(.?)/s";
return preg_replace_callback($pattern, 'Shortcode::_handle', $content);
}
/**
* _handle()
*/
protected static function _handle($matches)
{
$prefix = $matches[1];
$suffix = $matches[6];
$shortcode = $matches[2];
// Allow for escaping shortcodes by enclosing them in {{shortcode}}
if ($prefix == '{' && $suffix == '}') {
return substr($matches[0], 1, -1);
}
$attributes = array(); // Parse attributes into into this array.
if (preg_match_all('/(\w+) *= *(?:([\'"])(.*?)\\2|([^ "\'>]+))/', $matches[3], $match, PREG_SET_ORDER)) {
foreach ($match as $attribute) {
if ( ! empty($attribute[4])) {
$attributes[strtolower($attribute[1])] = $attribute[4];
} elseif ( ! empty($attribute[3])) {
$attributes[strtolower($attribute[1])] = $attribute[3];
}
}
}
// Check if this shortcode realy exists then call user function else return empty string
return (isset(Shortcode::$shortcode_tags[$shortcode])) ? $prefix . call_user_func(Shortcode::$shortcode_tags[$shortcode], $attributes, $matches[5], $shortcode) . $suffix : '';
}
}

227
libraries/engine/Site.php Normal file
View File

@@ -0,0 +1,227 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra Site module
*
* @package Monstra
* @subpackage Engine
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Site
{
/**
* An instance of the Site class
*
* @var site
*/
protected static $instance = null;
/**
* Initializing site
*
* @return Site
*/
public static function init()
{
if ( ! isset(self::$instance)) self::$instance = new Site();
return self::$instance;
}
/**
* Protected clone method to enforce singleton behavior.
*
* @access protected
*/
protected function __clone()
{
// Nothing here.
}
/**
* Construct
*/
protected function __construct()
{
call_user_func(ucfirst(Uri::command()).'::main');
}
/**
* Get site name
*
* <code>
* echo Site::name();
* </code>
*
* @return string
*/
public static function name()
{
return Option::get('sitename');
}
/**
* Get site theme
*
* <code>
* echo Site::theme();
* </code>
*
* @return string
*/
public static function theme()
{
return Option::get('theme_site_name');
}
/**
* Get Page title
*
* <code>
* echo Site::title();
* </code>
*
* @return string
*/
public static function title()
{
return call_user_func(ucfirst(Uri::command()).'::title');
}
/**
* Get page description
*
* <code>
* echo Site::description();
* </code>
*
* @return string
*/
public static function description()
{
return (($description = trim(call_user_func(ucfirst(Uri::command()).'::description'))) == '') ? Html::toText(Option::get('description')) : Html::toText($description);
}
/**
* Get page keywords
*
* <code>
* echo Site::keywords();
* </code>
*
* @return string
*/
public static function keywords()
{
return (($keywords = trim(call_user_func(ucfirst(Uri::command()).'::keywords'))) == '') ? Html::toText(Option::get('keywords')) : Html::toText($keywords);
}
/**
* Get site slogan
*
* <code>
* echo Site::slogan();
* </code>
*
* @return string
*/
public static function slogan()
{
return Option::get('slogan');
}
/**
* Get page content
*
* <code>
* echo Site::content();
* </code>
*
* @return string
*/
public static function content()
{
return Filter::apply('content', call_user_func(ucfirst(Uri::command()).'::content'));
}
/**
* Get compressed template
*
* <code>
* echo Site::template();
* </code>
*
* @param string $theme Theme name
* @return mixed
*/
public static function template($theme = null)
{
// Get specific theme or current theme
$current_theme = ($theme == null) ? Option::get('theme_site_name') : $theme ;
// Get template
$template = call_user_func(ucfirst(Uri::command()).'::template');
// Check whether is there such a template in the current theme
// else return default template: index
// also compress template file :)
if (File::exists(THEMES_SITE . DS . $current_theme . DS . $template . '.template.php')) {
if ( ! file_exists(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php') or
filemtime(THEMES_SITE . DS . $current_theme . DS . $template .'.template.php') > filemtime(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php')) {
$buffer = file_get_contents(THEMES_SITE. DS . $current_theme . DS . $template .'.template.php');
$buffer = Minify::html($buffer);
file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php', $buffer);
}
return 'minify.'.$template;
} else {
if ( ! File::exists(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php') or
filemtime(THEMES_SITE . DS . $current_theme . DS . 'index.template.php') > filemtime(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php')) {
$buffer = file_get_contents(THEMES_SITE . DS . $current_theme . DS . 'index.template.php');
$buffer = Minify::html($buffer);
file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php', $buffer);
}
return 'minify.index';
}
}
/**
* Get site url
*
* <code>
* echo Site::url();
* </code>
*
* @return string
*/
public static function url()
{
return Option::get('siteurl');
}
/**
* Get copyright information
*
* <code>
* echo Site::powered();
* </code>
*
* @return string
*/
public static function powered()
{
return __('Powered by', 'system').' <a href="http://monstra.org" target="_blank">Monstra</a> ' . Core::VERSION;
}
}

163
libraries/engine/Uri.php Normal file
View File

@@ -0,0 +1,163 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Uri
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Default component
*
* @var string
*/
public static $default_component = 'pages';
/**
* Get uri and explode command/param1/param2
*
* <code>
* $segments = Uri::segments();
* </code>
*
* @return array
*/
public static function segments()
{
// Get request uri and current script path
$request_uri = explode('/', $_SERVER['REQUEST_URI']);
$script_name = explode('/', $_SERVER['SCRIPT_NAME']);
// Delete script name
for ($i = 0; $i < sizeof($script_name); $i++) {
if ($request_uri[$i] == $script_name[$i]) {
unset($request_uri[$i]);
}
}
// Get all the values of an array
$uri = array_values($request_uri);
// Ability to pass parameters
foreach ($uri as $i => $u) {
if (isset($uri[$i])) { $pos = strrpos($uri[$i], "?"); if ($pos === false) { $uri[$i] = Security::sanitizeURL($uri[$i]); } else { $uri[$i] = Security::sanitizeURL(substr($uri[$i], 0, $pos)); } }
}
// Return uri segments
return $uri;
}
/**
* Get uri segment
*
* <code>
* $segment = Uri::segment(1);
* </code>
*
* @param integer $segment Segment
* @return mixed
*/
public static function segment($segment)
{
$segments = Uri::segments();
return isset($segments[$segment]) ? $segments[$segment] : null;
}
/**
* Get command/component from registed components
*
* <code>
* $command = Uri::command();
* </code>
*
* @return array
*/
public static function command()
{
// Get uri segments
$uri = Uri::segments();
if ( ! isset($uri[0])) {
$uri[0] = Uri::$default_component;
} else {
if ( ! in_array($uri[0], Plugin::$components) ) {
$uri[0] = Uri::$default_component;
} else {
$uri[0] = $uri[0];
}
}
return $uri[0];
}
/**
* Get uri parammeters
*
* <code>
* $params = Uri::params();
* </code>
*
* @return array
*/
public static function params()
{
//Init data array
$data = array();
// Get URI
$uri = Uri::segments();
// http://site.com/ and http://site.com/index.php same main home pages
if ( ! isset($uri[0])) {
$uri[0] = '';
}
// param1/param2
if ($uri[0] !== Uri::$default_component) {
if (isset($uri[1])) {
$data[0] = $uri[0];
$data[1] = $uri[1];
// Some more uri parts :)
// site.ru/part1/part2/part3/part4/part5/part6/
if (isset($uri[2])) $data[2] = $uri[2];
if (isset($uri[3])) $data[3] = $uri[3];
if (isset($uri[4])) $data[4] = $uri[4];
if (isset($uri[5])) $data[5] = $uri[5];
} else { // default
$data[0] = $uri[0];
}
} else {
// This is good for box plugin Pages
// parent/child
if (isset($uri[2])) {
$data[0] = $uri[1];
$data[1] = $uri[2];
} else { // default
$data[0] = $uri[1];
}
}
return $data;
}
}

1036
libraries/engine/Xmldb.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,10 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Include engine core
*/
include ROOT . DS . 'monstra' . DS . 'engine' . DS . 'core.php';
include ROOT . '/libraries/monstra/Monstra.php';
include ROOT . '/libraries/engine/Core.php';
/**
* Set core environment
@@ -18,7 +17,6 @@ include ROOT . DS . 'monstra' . DS . 'engine' . DS . 'core.php';
*/
Core::$environment = Core::DEVELOPMENT;
/**
* Monstra requires PHP 5.2.0 or greater
*/
@@ -26,7 +24,6 @@ if (version_compare(PHP_VERSION, "5.2.0", "<")) {
exit("Monstra requires PHP 5.2.0 or greater.");
}
/**
* Report Errors
*/
@@ -50,7 +47,6 @@ if (Core::$environment == Core::PRODUCTION) {
}
/**
* Initialize core
*/

View File

@@ -0,0 +1,7 @@
<?php
/**
* Set meta generator
*/
Action::add('theme_meta', 'setMetaGenerator');
function setMetaGenerator() { echo '<meta name="generator" content="Powered by Monstra '.Core::VERSION.'" />'; }

View File

@@ -0,0 +1,93 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra CMS Defines
*/
/**
* The filesystem path to the site 'themes' folder
*/
define('THEMES_SITE', ROOT . DS . 'public' . DS . 'themes');
/**
* The filesystem path to the admin 'themes' folder
*/
define('THEMES_ADMIN', ROOT . DS . 'admin' . DS . 'themes');
/**
* The filesystem path to the 'plugins' folder
*/
define('PLUGINS', ROOT . DS . 'plugins');
/**
* The filesystem path to the 'box' folder which is contained within
* the 'plugins' folder
*/
define('PLUGINS_BOX', PLUGINS . DS . 'box');
/**
* The filesystem path to the 'storage' folder
*/
define('STORAGE', ROOT . DS . 'storage');
/**
* The filesystem path to the 'xmldb' folder
*/
define('XMLDB', STORAGE . DS . 'database');
/**
* The filesystem path to the 'cache' folder
*/
define('CACHE', ROOT . DS . 'tmp' . DS . 'cache');
/**
* The filesystem path to the 'minify' folder
*/
define('MINIFY', ROOT . DS . 'tmp' . DS . 'minify');
/**
* The filesystem path to the 'logs' folder
*/
define('LOGS', ROOT . DS . 'tmp' . DS . 'logs');
/**
* The filesystem path to the 'assets' folder
*/
define('ASSETS', ROOT . DS . 'public' . DS . 'assets');
/**
* The filesystem path to the 'uploads' folder
*/
define('UPLOADS', ROOT . DS . 'public' . DS . 'uploads');
/**
* Set password salt
*/
define('MONSTRA_PASSWORD_SALT', 'YOUR_SALT_HERE');
/**
* Set date format
*/
define('MONSTRA_DATE_FORMAT', 'Y-m-d / H:i:s');
/**
* Set eval php
*/
define('MONSTRA_EVAL_PHP', false);
/**
* Check Monstra CMS version
*/
define('CHECK_MONSTRA_VERSION', true);
/**
* Set gzip output
*/
define('MONSTRA_GZIP', false);
/**
* Monstra database settings
*/
//define('MONSTRA_DB_DSN', 'mysql:dbname=monstra;host=localhost;port=3306');
//define('MONSTRA_DB_USER', 'root');
//define('MONSTRA_DB_PASSWORD', 'password');

View File

@@ -0,0 +1,21 @@
<?php
/**
* Evaluate a string as PHP code
*/
if (MONSTRA_EVAL_PHP) Filter::add('content', 'evalPHP');
function obEval($mathes)
{
ob_start();
eval($mathes[1]);
$mathes = ob_get_contents();
ob_end_clean();
return $mathes;
}
function evalPHP($str) { return preg_replace_callback('/\[php\](.*?)\[\/php\]/ms','obEval', $str); }
/**
* Add shortcode parser filter
*/
Filter::add('content', 'Shortcode::parse', 11);

View File

@@ -0,0 +1,7 @@
<?php
/**
* Add new shortcode {siteurl}
*/
Shortcode::add('siteurl', 'returnSiteUrl');
function returnSiteUrl() { return Option::get('siteurl'); }

162
libraries/monstra/Agent.php Normal file
View File

@@ -0,0 +1,162 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Agent
{
/**
* Mobiles
*
* @var array
*/
public static $mobiles = array (
'ipad',
'iphone',
'ipod',
'android',
'windows ce',
'windows phone',
'mobileexplorer',
'opera mobi',
'opera mini',
'fennec',
'blackberry',
'nokia',
'kindle',
'ericsson',
'motorola',
'minimo',
'iemobile',
'symbian',
'webos',
'hiptop',
'palmos',
'palmsource',
'xiino',
'avantgo',
'docomo',
'up.browser',
'vodafone',
'portable',
'pocket',
'mobile',
'phone',
);
/**
* Robots
*
* @var array
*/
public static $robots = array(
'googlebot',
'msnbot',
'slurp',
'yahoo',
'askjeeves',
'fastcrawler',
'infoseek',
'lycos',
'ia_archiver',
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Searches for a string in the user agent string.
*
* @param array $agents Array of strings to look for
* @return boolean
*/
protected static function find($agents)
{
// If isset HTTP_USER_AGENT ?
if (isset($_SERVER['HTTP_USER_AGENT'])) {
// Loop through $agents array
foreach ($agents as $agent) {
// If current user agent == agents[agent] then return true
if (stripos($_SERVER['HTTP_USER_AGENT'], $agent) !== false) {
return true;
}
}
}
// Else return false
return false;
}
/**
* Returns true if the user agent that made the request is identified as a mobile device.
*
* <code>
* if (Agent::isMobile()) {
* // Do something...
* }
* </code>
*
* @return boolean
*/
public static function isMobile()
{
return Agent::find(Agent::$mobiles);
}
/**
* Returns true if the user agent that made the request is identified as a robot/crawler.
*
* <code>
* if (Agent::isRobot()) {
* // Do something...
* }
* </code>
*
* @return boolean
*/
public static function isRobot()
{
return Agent::find(Agent::$robots);
}
/**
* Returns TRUE if the string you're looking for exists in the user agent string and FALSE if not.
*
* <code>
* if (Agent::is('iphone')) {
* // Do something...
* }
*
* if (Agent::is(array('iphone', 'ipod'))) {
* // Do something...
* }
* </code>
*
* @param mixed $device String or array of strings you're looking for
* @return boolean
*/
public static function is($device)
{
return Agent::find((array) $device);
}
}

View File

@@ -0,0 +1,88 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Alert
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Show success message
*
* <code>
* Alert::success('Message here...');
* </code>
*
* @param string $message Message
* @param integer $time Time
*/
public static function success($message, $time = 3000)
{
// Redefine vars
$message = (string) $message;
$time = (int) $time;
echo '<div class="alert alert-info">'.$message.'</div>
<script type="text/javascript">setTimeout(\'$(".alert").slideUp("slow")\', '.$time.'); </script>';
}
/**
* Show warning message
*
* <code>
* Alert::warning('Message here...');
* </code>
*
* @param string $message Message
* @param integer $time Time
*/
public static function warning($message, $time = 3000)
{
// Redefine vars
$message = (string) $message;
$time = (int) $time;
echo '<div class="alert alert-warning">'.$message.'</div>
<script type="text/javascript">setTimeout(\'$(".alert").slideUp("slow")\', '.$time.'); </script>';
}
/**
* Show error message
*
* <code>
* Alert::error('Message here...');
* </code>
*
* @param string $message Message
* @param integer $time Time
*/
public static function error($message, $time = 3000)
{
// Redefine vars
$message = (string) $message;
$time = (int) $time;
echo '<div class="alert alert-error">'.$message.'</div>
<script type="text/javascript">setTimeout(\'$(".alert").slideUp("slow")\', '.$time.'); </script>';
}
}

185
libraries/monstra/Arr.php Normal file
View File

@@ -0,0 +1,185 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Arr
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Subval sort
*
* <code>
* $new_array = Arr::subvalSort($old_array, 'sort');
* </code>
*
* @param array $a Array
* @param string $subkey Key
* @param string $order Order type DESC or ASC
* @return array
*/
public static function subvalSort($a, $subkey, $order = null)
{
if (count($a) != 0 || (!empty($a))) {
foreach ($a as $k => $v) $b[$k] = function_exists('mb_strtolower') ? mb_strtolower($v[$subkey]) : strtolower($v[$subkey]);
if ($order == null || $order == 'ASC') asort($b); else if ($order == 'DESC') arsort($b);
foreach ($b as $key => $val) $c[] = $a[$key];
return $c;
}
}
/**
* Returns value from array using "dot notation".
* If the key does not exist in the array, the default value will be returned instead.
*
* <code>
* $login = Arr::get($_POST, 'login');
*
* $array = array('foo' => 'bar');
* $foo = Arr::get($array, 'foo');
*
* $array = array('test' => array('foo' => 'bar'));
* $foo = Arr::get($array, 'test.foo');
* </code>
*
* @param array $array Array to extract from
* @param string $path Array path
* @param mixed $default Default value
* @return mixed
*/
public static function get($array, $path, $default = null)
{
// Get segments from path
$segments = explode('.', $path);
// Loop through segments
foreach ($segments as $segment) {
// Check
if ( ! is_array($array) || !isset($array[$segment])) {
return $default;
}
// Write
$array = $array[$segment];
}
// Return
return $array;
}
/**
* Deletes an array value using "dot notation".
*
* <code>
* Arr::delete($array, 'foo.bar');
* </code>
*
* @access public
* @param array $array Array you want to modify
* @param string $path Array path
* @return boolean
*/
public static function delete(&$array, $path)
{
// Get segments from path
$segments = explode('.', $path);
// Loop through segments
while (count($segments) > 1) {
$segment = array_shift($segments);
if ( ! isset($array[$segment]) || !is_array($array[$segment])) {
return false;
}
$array =& $array[$segment];
}
unset($array[array_shift($segments)]);
return true;
}
/**
* Checks if the given dot-notated key exists in the array.
*
* <code>
* if (Arr::keyExists($array, 'foo.bar')) {
* // Do something...
* }
* </code>
*
* @param array $array The search array
* @param mixed $path Array path
* @return boolean
*/
public static function keyExists($array, $path)
{
foreach (explode('.', $path) as $segment) {
if ( ! is_array($array) or ! array_key_exists($segment, $array)) {
return false;
}
$array = $array[$segment];
}
return true;
}
/**
* Returns a random value from an array.
*
* <code>
* Arr::random(array('php', 'js', 'css', 'html'));
* </code>
*
* @access public
* @param array $array Array path
* @return mixed
*/
public static function random($array)
{
return $array[array_rand($array)];
}
/**
* Returns TRUE if the array is associative and FALSE if not.
*
* <code>
* if (Arr::isAssoc($array)) {
* // Do something...
* }
* </code>
*
* @param array $array Array to check
* @return boolean
*/
public static function isAssoc($array)
{
return (bool) count(array_filter(array_keys($array), 'is_string'));
}
}

210
libraries/monstra/Cache.php Normal file
View File

@@ -0,0 +1,210 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Cache
{
/**
* Cache directory
*
* @var string
*/
public static $cache_dir = CACHE;
/**
* Cache file ext
*
* @var string
*/
public static $cache_file_ext = 'txt';
/**
* Cache life time (in seconds)
*
* @var int
*/
public static $cache_time = 31556926;
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Configure the settings of Cache
*
* <code>
* Cache::configure('cache_dir', 'path/to/cache/dir');
* </code>
*
* @param mixed $setting Setting name
* @param mixed $value Setting value
*/
public static function configure($setting, $value)
{
if (property_exists("cache", $setting)) Cache::$$setting = $value;
}
/**
* Get data from cache
*
* <code>
* $profile = Cache::get('profiles', 'profile');
* </code>
*
* @param string $namespace Namespace
* @param string $key Cache key
* @return boolean
*/
public static function get($namespace, $key)
{
// Redefine vars
$namespace = (string) $namespace;
// Get cache file id
$cache_file_id = Cache::getCacheFileID($namespace, $key);
// Is cache file exists ?
if (file_exists($cache_file_id)) {
// If cache file has not expired then fetch it
if ((time() - filemtime($cache_file_id)) < Cache::$cache_time) {
$handle = fopen($cache_file_id, 'r');
$cache = '';
while ( ! feof($handle)) {
$cache .= fgets($handle);
}
fclose($handle);
return unserialize($cache);
} else {
unlink($cache_file_id);
return false;
}
} else {
return false;
}
}
/**
* Create new cache file $key in namescapce $namespace with the given data $data
*
* <code>
* $profile = array('login' => 'Awilum',
* 'email' => 'awilum@msn.com');
* Cache::put('profiles', 'profile', $profile);
* </code>
*
* @param string $namespace Namespace
* @param string $key Cache key
* @param mixed $data The variable to store
* @return boolean
*/
public static function put($namespace, $key, $data)
{
// Redefine vars
$namespace = (string) $namespace;
// Is CACHE directory writable ?
if (file_exists(CACHE) === false || is_readable(CACHE) === false || is_writable(CACHE) === false) {
throw new RuntimeException(vsprintf("%s(): Cache directory ('%s') is not writable.", array(__METHOD__, CACHE)));
}
// Create namespace
if ( ! file_exists(Cache::getNamespaceID($namespace))) {
mkdir(Cache::getNamespaceID($namespace), 0775, true);
}
// Write cache to specific namespace
return file_put_contents(Cache::getCacheFileID($namespace, $key), serialize($data), LOCK_EX);
}
/**
* Deletes a cache in specific namespace
*
* <code>
* Cache::delete('profiles', 'profile');
* </code>
*
* @param string $namespace Namespace
* @param string $key Cache key
* @return boolean
*/
public static function delete($namespace, $key)
{
// Redefine vars
$namespace = (string) $namespace;
if (file_exists(Cache::getCacheFileID($namespace, $key))) unlink(Cache::getCacheFileID($namespace, $key)); else return false;
}
/**
* Clean specific cache namespace.
*
* <code>
* Cache::clean('profiles');
* </code>
*
* @param string $namespace Namespace
* @return null
*/
public static function clean($namespace)
{
// Redefine vars
$namespace = (string) $namespace;
array_map("unlink", glob(Cache::$cache_dir . DS . md5($namespace) . DS . "*." . Cache::$cache_file_ext));
}
/**
* Get cache file ID
*
* @param string $namespace Namespace
* @param string $key Cache key
* @return string
*/
protected static function getCacheFileID($namespace, $key)
{
// Redefine vars
$namespace = (string) $namespace;
return Cache::$cache_dir . DS . md5($namespace) . DS . md5($key) . '.' . Cache::$cache_file_ext;
}
/**
* Get namespace ID
*
* @param string $namespace Namespace
* @return string
*/
protected static function getNamespaceID($namespace)
{
// Redefine vars
$namespace = (string) $namespace;
return Cache::$cache_dir . DS . md5($namespace);
}
}

View File

@@ -0,0 +1,106 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Cookie
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Send a cookie
*
* <code>
* Cookie::set('limit', 10);
* </code>
*
* @param string $key A name for the cookie.
* @param mixed $value The value to be stored. Keep in mind that they will be serialized.
* @param integer $expire The number of seconds that this cookie will be available.
* @param string $path The path on the server in which the cookie will be availabe. Use / for the entire domain, /foo if you just want it to be available in /foo.
* @param string $domain The domain that the cookie is available on. Use .example.com to make it available on all subdomains of example.com.
* @param boolean $secure Should the cookie be transmitted over a HTTPS-connection? If true, make sure you use a secure connection, otherwise the cookie won't be set.
* @param boolean $httpOnly Should the cookie only be available through HTTP-protocol? If true, the cookie can't be accessed by Javascript, ...
* @return boolean
*/
public static function set($key, $value, $expire = 86400, $domain = '', $path = '/', $secure = false, $httpOnly = false)
{
// Redefine vars
$key = (string) $key;
$value = serialize($value);
$expire = time() + (int) $expire;
$path = (string) $path;
$domain = (string) $domain;
$secure = (bool) $secure;
$httpOnly = (bool) $httpOnly;
// Set cookie
return setcookie($key, $value, $expire, $path, $domain, $secure, $httpOnly);
}
/**
* Get a cookie
*
* <code>
* $limit = Cookie::get('limit');
* </code>
*
* @param string $key The name of the cookie that should be retrieved.
* @return mixed
*/
public static function get($key)
{
// Redefine key
$key = (string) $key;
// Cookie doesn't exist
if( ! isset($_COOKIE[$key])) return false;
// Fetch base value
$value = (get_magic_quotes_gpc()) ? stripslashes($_COOKIE[$key]) : $_COOKIE[$key];
// Unserialize
$actual_value = @unserialize($value);
// If unserialize failed
if($actual_value === false && serialize(false) != $value) return false;
// Everything is fine
return $actual_value;
}
/**
* Delete a cookie
*
* <code>
* Cookie::delete('limit');
* </code>
*
* @param string $name The name of the cookie that should be deleted.
*/
public static function delete($key)
{
unset($_COOKIE[$key]);
}
}

142
libraries/monstra/Curl.php Normal file
View File

@@ -0,0 +1,142 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Curl
{
/**
* Default curl options.
*
* @var array
*/
protected static $default_options = array(
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; Monstra CMS; +http://monstra.org)',
CURLOPT_RETURNTRANSFER => true
);
/**
* Information about the last transfer.
*
* @var array
*/
protected static $info;
/**
* Performs a curl GET request.
*
* <code>
* $res = Curl::get('http://site.com/');
* </code>
*
* @param string $url The URL to fetch
* @param array $options An array specifying which options to set and their values
* @return string
*/
public static function get($url, array $options = null)
{
// Redefine vars
$url = (string) $url;
// Check if curl is available
if ( ! function_exists('curl_init')) throw new RuntimeException(vsprintf("%s(): This method requires cURL (http://php.net/curl), it seems like the extension isn't installed.", array(__METHOD__)));
// Initialize a cURL session
$handle = curl_init($url);
// Merge options
$options = (array) $options + Curl::$default_options;
// Set multiple options for a cURL transfer
curl_setopt_array($handle, $options);
// Perform a cURL session
$response = curl_exec($handle);
// Set information regarding a specific transfer
Curl::$info = curl_getinfo($handle);
// Close a cURL session
curl_close($handle);
// Return response
return $response;
}
/**
* Performs a curl POST request.
*
* <code>
* $res = Curl::post('http://site.com/login');
* </code>
*
* @param string $url The URL to fetch
* @param array $data An array with the field name as key and field data as value
* @param boolean $multipart True to send data as multipart/form-data and false to send as application/x-www-form-urlencoded
* @param array $options An array specifying which options to set and their values
* @return string
*/
public static function post($url, array $data = null, $multipart = false, array $options = null)
{
// Redefine vars
$url = (string) $url;
// Check if curl is available
if ( ! function_exists('curl_init')) throw new RuntimeException(vsprintf("%s(): This method requires cURL (http://php.net/curl), it seems like the extension isn't installed.", array(__METHOD__)));
// Initialize a cURL session
$handle = curl_init($url);
// Merge options
$options = (array) $options + Curl::$default_options;
// Add options
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = ($multipart === true) ? (array) $data : http_build_query((array) $data);
// Set multiple options for a cURL transfer
curl_setopt_array($handle, $options);
// Perform a cURL session
$response = curl_exec($handle);
// Set information regarding a specific transfer
Curl::$info = curl_getinfo($handle);
// Close a cURL session
curl_close($handle);
// Return response
return $response;
}
/**
* Gets information about the last transfer.
*
* <code>
* $res = Curl::getInfo();
* </code>
*
* @param string $value Array key of the array returned by curl_getinfo()
* @return mixed
*/
public static function getInfo($value = null)
{
if (empty(Curl::$info)) {
return false;
}
return ($value === null) ? Curl::$info : Curl::$info[$value];
}
}

420
libraries/monstra/Date.php Normal file
View File

@@ -0,0 +1,420 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Date
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Get format date
*
* <code>
* echo Date::format($date, 'j.n.Y');
* </code>
*
* @param integer $date Unix timestamp
* @param string $format Date format
* @return integer
*/
public static function format($date, $format = '')
{
// Redefine vars
$format = (string) $format;
$date = (int) $date;
if ($format != '') { return date($format, $date); } else { return date(MONSTRA_DATE_FORMAT, $date); }
}
/**
* Get number of seconds in a minute, incrementing by a step.
*
* <code>
* $seconds = Date::seconds();
* </code>
*
* @param integer $step Amount to increment each step by, 1 to 30
* @param integer $start Start value
* @param integer $end End value
* @return array
*/
public static function seconds($step = 1, $start = 0, $end = 60)
{
// Redefine vars
$step = (int) $step;
$start = (int) $start;
$end = (int) $end;
return Date::_range($step, $start, $end);
}
/**
* Get number of minutes in a hour, incrementing by a step.
*
* <code>
* $minutes = Date::minutes();
* </code>
*
* @param integer $step Amount to increment each step by, 1 to 30
* @param integer $start Start value
* @param integer $end End value
* @return array
*/
public static function minutes($step = 5, $start = 0, $end = 60)
{
// Redefine vars
$step = (int) $step;
$start = (int) $start;
$end = (int) $end;
return Date::_range($step, $start, $end);
}
/**
* Get number of hours, incrementing by a step.
*
* <code>
* $hours = Date::hours();
* </code>
*
* @param integer $step Amount to increment each step by, 1 to 30
* @param integer $long Start value
* @param integer $start End value
* @return array
*/
public static function hours($step = 1, $long = false, $start = null)
{
// Redefine vars
$step = (int) $step;
$long = (bool) $long;
if ($start === null) $start = ($long === FALSE) ? 1 : 0;
$end = ($long === true) ? 23 : 12;
return Date::_range($step, $start, $end, true);
}
/**
* Get number of months.
*
* <code>
* $months = Date::months();
* </code>
*
* @return array
*/
public static function months()
{
return Date::_range(1, 1, 12, true);
}
/**
* Get number of days.
*
* <code>
* $months = Date::days();
* </code>
*
* @return array
*/
public static function days()
{
return Date::_range(1, 1, Date::daysInMonth((int) date('M')), true);
}
/**
* Returns the number of days in the requested month
*
* <code>
* $days = Date::daysInMonth(1);
* </code>
*
* @param integer $month Month as a number (1-12)
* @param integer $year The year
* @return integer
*/
public static function daysInMonth($month, $year = null)
{
// Redefine vars
$month = (int) $month;
$year = ! empty($year) ? (int) $year : (int) date('Y');
if ($month < 1 or $month > 12) {
return false;
} elseif ($month == 2) {
if ($year % 400 == 0 or ($year % 4 == 0 and $year % 100 != 0)) {
return 29;
}
}
$days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
return $days_in_month[$month-1];
}
/**
* Get number of years.
*
* <code>
* $years = Date::years();
* </code>
*
* @param integer $long Start value
* @param integer $start End value
* @return array
*/
public static function years($start = 1980, $end = 2024)
{
// Redefine vars
$start = (int) $start;
$end = (int) $end;
return Date::_range(1, $start, $end, true);
}
/**
* Get current season name
*
* <code>
* echo Date::season();
* </code>
*
* @return string
*/
public static function season()
{
$seasons = array("Winter", "Spring", "Summer", "Autumn");
return $seasons[(int) ((date("n") %12)/3)];
}
/**
* Get today date
*
* <code>
* echo Date::today();
* </code>
*
* @param string $format Date format
* @return string
*/
public static function today($format = '')
{
// Redefine vars
$format = (string) $format;
if ($format != '') { return date($format); } else { return date(MONSTRA_DATE_FORMAT); }
}
/**
* Get yesterday date
*
* <code>
* echo Date::yesterday();
* </code>
*
* @param string $format Date format
* @return string
*/
public static function yesterday($format = '')
{
// Redefine vars
$format = (string) $format;
if ($format != '') { return date($format, strtotime("-1 day")); } else { return date(MONSTRA_DATE_FORMAT, strtotime("-1 day")); }
}
/**
* Get tomorrow date
*
* <code>
* echo Date::tomorrow();
* </code>
*
* @param string $format Date format
* @return string
*/
public static function tomorrow($format = '')
{
// Redefine vars
$format = (string) $format;
if ($format != '') { return date($format, strtotime("+1 day")); } else { return date(MONSTRA_DATE_FORMAT, strtotime("-1 day")); }
}
/**
* Converts a UNIX timestamp to DOS format.
*
* <code>
* $dos = Date::unix2dos($unix);
* </code>
*
* @param integer $timestamp UNIX timestamp
* @return integer
*/
public static function unix2dos($timestamp = 0)
{
$timestamp = ($_timestamp == 0) ? getdate() : getdate($_timestamp);
if ($timestamp['year'] < 1980) return (1 << 21 | 1 << 16);
$timestamp['year'] -= 1980;
return ($timestamp['year'] << 25 | $timestamp['mon'] << 21 |
$timestamp['mday'] << 16 | $timestamp['hours'] << 11 |
$timestamp['minutes'] << 5 | $timestamp['seconds'] >> 1);
}
/**
* Converts a DOS timestamp to UNIX format.
*
* <code>
* $unix = Date::dos2unix($dos);
* </code>
*
* @param integer $timestamp DOS timestamp
* @return integer
*/
public static function dos2unix($timestamp)
{
$sec = 2 * ($timestamp & 0x1f);
$min = ($timestamp >> 5) & 0x3f;
$hrs = ($timestamp >> 11) & 0x1f;
$day = ($timestamp >> 16) & 0x1f;
$mon = (($timestamp >> 21) & 0x0f);
$year = (($timestamp >> 25) & 0x7f) + 1980;
return mktime($hrs, $min, $sec, $mon, $day, $year);
}
/**
* Get Time zones
*
* @return array
*/
public static function timezones()
{
return array('Kwajalein'=>'(GMT-12:00) International Date Line West',
'Pacific/Samoa'=>'(GMT-11:00) Midway Island, Samoa',
'Pacific/Honolulu'=>'(GMT-10:00) Hawaii',
'America/Anchorage'=>'(GMT-09:00) Alaska',
'America/Los_Angeles'=>'(GMT-08:00) Pacific Time (US &amp; Canada)',
'America/Tijuana'=>'(GMT-08:00) Tijuana, Baja California',
'America/Denver'=>'(GMT-07:00) Mountain Time (US &amp; Canada)',
'America/Chihuahua'=>'(GMT-07:00) Chihuahua, La Paz, Mazatlan',
'America/Phoenix'=>'(GMT-07:00) Arizona',
'America/Regina'=>'(GMT-06:00) Saskatchewan',
'America/Tegucigalpa'=>'(GMT-06:00) Central America',
'America/Chicago'=>'(GMT-06:00) Central Time (US &amp; Canada)',
'America/Mexico_City'=>'(GMT-06:00) Guadalajara, Mexico City, Monterrey',
'America/New_York'=>'(GMT-05:00) Eastern Time (US &amp; Canada)',
'America/Bogota'=>'(GMT-05:00) Bogota, Lima, Quito, Rio Branco',
'America/Indiana/Indianapolis'=>'(GMT-05:00) Indiana (East)',
'America/Caracas'=>'(GMT-04:30) Caracas',
'America/Halifax'=>'(GMT-04:00) Atlantic Time (Canada)',
'America/Manaus'=>'(GMT-04:00) Manaus',
'America/Santiago'=>'(GMT-04:00) Santiago',
'America/La_Paz'=>'(GMT-04:00) La Paz',
'America/St_Johns'=>'(GMT-03:30) Newfoundland',
'America/Argentina/Buenos_Aires'=>'(GMT-03:00) Buenos Aires',
'America/Sao_Paulo'=>'(GMT-03:00) Brasilia',
'America/Godthab'=>'(GMT-03:00) Greenland',
'America/Montevideo'=>'(GMT-03:00) Montevideo',
'America/Argentina/Buenos_Aires'=>'(GMT-03:00) Georgetown',
'Atlantic/South_Georgia'=>'(GMT-02:00) Mid-Atlantic',
'Atlantic/Azores'=>'(GMT-01:00) Azores',
'Atlantic/Cape_Verde'=>'(GMT-01:00) Cape Verde Is.',
'Europe/London'=>'(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London',
'Atlantic/Reykjavik'=>'(GMT) Monrovia, Reykjavik',
'Africa/Casablanca'=>'(GMT) Casablanca',
'Europe/Belgrade'=>'(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague',
'Europe/Sarajevo'=>'(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb',
'Europe/Brussels'=>'(GMT+01:00) Brussels, Copenhagen, Madrid, Paris',
'Africa/Algiers'=>'(GMT+01:00) West Central Africa',
'Europe/Amsterdam'=>'(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
'Africa/Cairo'=>'(GMT+02:00) Cairo',
'Europe/Helsinki'=>'(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius',
'Europe/Athens'=>'(GMT+02:00) Athens, Bucharest, Istanbul',
'Asia/Jerusalem'=>'(GMT+02:00) Jerusalem',
'Asia/Amman'=>'(GMT+02:00) Amman',
'Asia/Beirut'=>'(GMT+02:00) Beirut',
'Africa/Windhoek'=>'(GMT+02:00) Windhoek',
'Africa/Harare'=>'(GMT+02:00) Harare, Pretoria',
'Asia/Kuwait'=>'(GMT+03:00) Kuwait, Riyadh',
'Asia/Baghdad'=>'(GMT+03:00) Baghdad',
'Europe/Minsk'=>'(GMT+03:00) Minsk',
'Africa/Nairobi'=>'(GMT+03:00) Nairobi',
'Asia/Tbilisi'=>'(GMT+03:00) Tbilisi',
'Asia/Tehran'=>'(GMT+03:30) Tehran',
'Asia/Muscat'=>'(GMT+04:00) Abu Dhabi, Muscat',
'Asia/Baku'=>'(GMT+04:00) Baku',
'Europe/Moscow'=>'(GMT+04:00) Moscow, St. Petersburg, Volgograd',
'Asia/Yerevan'=>'(GMT+04:00) Yerevan',
'Asia/Karachi'=>'(GMT+05:00) Islamabad, Karachi',
'Asia/Tashkent'=>'(GMT+05:00) Tashkent',
'Asia/Kolkata'=>'(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi',
'Asia/Colombo'=>'(GMT+05:30) Sri Jayawardenepura',
'Asia/Katmandu'=>'(GMT+05:45) Kathmandu',
'Asia/Dhaka'=>'(GMT+06:00) Astana, Dhaka',
'Asia/Yekaterinburg'=>'(GMT+06:00) Ekaterinburg',
'Asia/Rangoon'=>'(GMT+06:30) Yangon (Rangoon)',
'Asia/Novosibirsk'=>'(GMT+07:00) Almaty, Novosibirsk',
'Asia/Bangkok'=>'(GMT+07:00) Bangkok, Hanoi, Jakarta',
'Asia/Beijing'=>'(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi',
'Asia/Ulaanbaatar'=>'(GMT+08:00) Irkutsk, Ulaan Bataar',
'Asia/Krasnoyarsk'=>'(GMT+08:00) Krasnoyarsk',
'Asia/Kuala_Lumpur'=>'(GMT+08:00) Kuala Lumpur, Singapore',
'Asia/Taipei'=>'(GMT+08:00) Taipei',
'Australia/Perth'=>'(GMT+08:00) Perth',
'Asia/Seoul'=>'(GMT+09:00) Seoul',
'Asia/Tokyo'=>'(GMT+09:00) Osaka, Sapporo, Tokyo',
'Australia/Darwin'=>'(GMT+09:30) Darwin',
'Australia/Adelaide'=>'(GMT+09:30) Adelaide',
'Australia/Sydney'=>'(GMT+10:00) Canberra, Melbourne, Sydney',
'Australia/Brisbane'=>'(GMT+10:00) Brisbane',
'Australia/Hobart'=>'(GMT+10:00) Hobart',
'Asia/Yakutsk'=>'(GMT+10:00) Yakutsk',
'Pacific/Guam'=>'(GMT+10:00) Guam, Port Moresby',
'Asia/Vladivostok'=>'(GMT+11:00) Vladivostok',
'Pacific/Fiji'=>'(GMT+12:00) Fiji, Kamchatka, Marshall Is.',
'Asia/Magadan'=>'(GMT+12:00) Magadan, Solomon Is., New Caledonia',
'Pacific/Auckland'=>'(GMT+12:00) Auckland, Wellington',
'Pacific/Tongatapu'=>'(GMT+13:00) Nukualofa'
);
}
/**
* _range()
*/
protected static function _range($step, $start, $end, $flag = false)
{
$result = array();
if ($flag) {
for ($i = $start; $i <= $end; $i += $step) $result[$i] = (string) $i;
} else {
for ($i = $start; $i < $end; $i += $step) $result[$i] = sprintf('%02d', $i);
}
return $result;
}
}

116
libraries/monstra/Debug.php Normal file
View File

@@ -0,0 +1,116 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Debug
{
/**
* Time
*
* @var array
*/
protected static $time = array();
/**
* Memory
*
* @var array
*/
protected static $memory = array();
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Save current time for current point
*
* <code>
* Debug::elapsedTimeSetPoint('point_name');
* </code>
*
* @param string $point_name Point name
*/
public static function elapsedTimeSetPoint($point_name)
{
Debug::$time[$point_name] = microtime(true);
}
/**
* Get elapsed time for current point
*
* <code>
* echo Debug::elapsedTime('point_name');
* </code>
*
* @param string $point_name Point name
* @return string
*/
public static function elapsedTime($point_name)
{
if (isset(Debug::$time[$point_name])) return sprintf("%01.4f", microtime(true) - Debug::$time[$point_name]);
}
/**
* Save current memory for current point
*
* <code>
* Debug::memoryUsageSetPoint('point_name');
* </code>
*
* @param string $point_name Point name
*/
public static function memoryUsageSetPoint($point_name)
{
Debug::$memory[$point_name] = memory_get_usage();
}
/**
* Get memory usage for current point
*
* <code>
* echo Debug::memoryUsage('point_name');
* </code>
*
* @param string $point_name Point name
* @return string
*/
public static function memoryUsage($point_name)
{
if (isset(Debug::$memory[$point_name])) return Number::byteFormat(memory_get_usage() - Debug::$memory[$point_name]);
}
/**
* Print the variable $data and exit if exit = true
*
* <code>
* Debug::dump($data);
* </code>
*
* @param mixed $data Data
* @param boolean $exit Exit
*/
public static function dump($data, $exit = false)
{
echo "<pre>dump \n---------------------- \n\n" . print_r($data, true) . "\n----------------------</pre>";
if ($exit) exit;
}
}

207
libraries/monstra/Dir.php Normal file
View File

@@ -0,0 +1,207 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
/**
* Dir class
*/
class Dir
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Creates a directory
*
* <code>
* Dir::create('folder1');
* </code>
*
* @param string $dir Name of directory to create
* @param integer $chmod Chmod
* @return boolean
*/
public static function create($dir, $chmod = 0775)
{
// Redefine vars
$dir = (string) $dir;
// Create new dir if $dir !exists
return ( ! Dir::exists($dir)) ? @mkdir($dir, $chmod, true) : true;
}
/**
* Checks if this directory exists.
*
* <code>
* if (Dir::exists('folder1')) {
* // Do something...
* }
* </code>
*
* @param string $dir Full path of the directory to check.
* @return boolean
*/
public static function exists($dir)
{
// Redefine vars
$dir = (string) $dir;
// Directory exists
if (file_exists($dir) && is_dir($dir)) return true;
// Doesn't exist
return false;
}
/**
* Check dir permission
*
* <code>
* echo Dir::checkPerm('folder1');
* </code>
*
* @param string $dir Directory to check
* @return string
*/
public static function checkPerm($dir)
{
// Redefine vars
$dir = (string) $dir;
// Clear stat cache
clearstatcache();
// Return perm
return substr(sprintf('%o', fileperms($dir)), -4);
}
/**
* Delete directory
*
* <code>
* Dir::delete('folder1');
* </code>
*
* @param string $dir Name of directory to delete
*/
public static function delete($dir)
{
// Redefine vars
$dir = (string) $dir;
// Delete dir
if (is_dir($dir)){$ob=scandir($dir);foreach ($ob as $o) {if ($o!='.'&&$o!='..') {if(filetype($dir.'/'.$o)=='dir')Dir::delete($dir.'/'.$o); else unlink($dir.'/'.$o);}}}
reset($ob); rmdir($dir);
}
/**
* Get list of directories
*
* <code>
* $dirs = Dir::scan('folders');
* </code>
*
* @param string $dir Directory
*/
public static function scan($dir)
{
// Redefine vars
$dir = (string) $dir;
// Scan dir
if (is_dir($dir)&&$dh=opendir($dir)){$f=array();while ($fn=readdir($dh)) {if($fn!='.'&&$fn!='..'&&is_dir($dir.DS.$fn))$f[]=$fn;}return$f;}
}
/**
* Check if a directory is writable.
*
* <code>
* if (Dir::writable('folder1')) {
* // Do something...
* }
* </code>
*
* @param string $path The path to check.
* @return booleans
*/
public static function writable($path)
{
// Redefine vars
$path = (string) $path;
// Create temporary file
$file = tempnam($path, 'writable');
// File has been created
if ($file !== false) {
// Remove temporary file
File::delete($file);
// Writable
return true;
}
// Else not writable
return false;
}
/**
* Get directory size.
*
* <code>
* echo Dir::size('folder1');
* </code>
*
* @param string $path The path to directory.
* @return integer
*/
public static function size($path)
{
// Redefine vars
$path = (string) $path;
$total_size = 0;
$files = scandir($path);
$clean_path = rtrim($path, '/') . '/';
foreach ($files as $t) {
if ($t <> "." && $t <> "..") {
$current_file = $clean_path . $t;
if (is_dir($current_file)) {
$total_size += Dir::size($current_file);
} else {
$total_size += filesize($current_file);
}
}
}
// Return total size
return $total_size;
}
}

575
libraries/monstra/File.php Normal file
View File

@@ -0,0 +1,575 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class File
{
/**
* Mime type list
*
* @var array
*/
public static $mime_types = array(
'aac' => 'audio/aac',
'atom' => 'application/atom+xml',
'avi' => 'video/avi',
'bmp' => 'image/x-ms-bmp',
'c' => 'text/x-c',
'class' => 'application/octet-stream',
'css' => 'text/css',
'csv' => 'text/csv',
'deb' => 'application/x-deb',
'dll' => 'application/x-msdownload',
'dmg' => 'application/x-apple-diskimage',
'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'exe' => 'application/octet-stream',
'flv' => 'video/x-flv',
'gif' => 'image/gif',
'gz' => 'application/x-gzip',
'h' => 'text/x-c',
'htm' => 'text/html',
'html' => 'text/html',
'ini' => 'text/plain',
'jar' => 'application/java-archive',
'java' => 'text/x-java',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'js' => 'text/javascript',
'json' => 'application/json',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mka' => 'audio/x-matroska',
'mkv' => 'video/x-matroska',
'mp3' => 'audio/mpeg',
'mp4' => 'application/mp4',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'odt' => 'application/vnd.oasis.opendocument.text',
'ogg' => 'audio/ogg',
'pdf' => 'application/pdf',
'php' => 'text/x-php',
'png' => 'image/png',
'psd' => 'image/vnd.adobe.photoshop',
'py' => 'application/x-python',
'ra' => 'audio/vnd.rn-realaudio',
'ram' => 'audio/vnd.rn-realaudio',
'rar' => 'application/x-rar-compressed',
'rss' => 'application/rss+xml',
'safariextz' => 'application/x-safari-extension',
'sh' => 'text/x-shellscript',
'shtml' => 'text/html',
'swf' => 'application/x-shockwave-flash',
'tar' => 'application/x-tar',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'torrent' => 'application/x-bittorrent',
'txt' => 'text/plain',
'wav' => 'audio/wav',
'webp' => 'image/webp',
'wma' => 'audio/x-ms-wma',
'xls' => 'application/vnd.ms-excel',
'xml' => 'text/xml',
'zip' => 'application/zip',
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Returns true if the File exists.
*
* <code>
* if (File::exists('filename.txt')) {
* // Do something...
* }
* </code>
*
* @param string $filename The file name
* @return boolean
*/
public static function exists($filename)
{
// Redefine vars
$filename = (string) $filename;
// Return
return (file_exists($filename) && is_file($filename));
}
/**
* Delete file
*
* <code>
* File::delete('filename.txt');
* </code>
*
* @param mixed $filename The file name or array of files
* @return boolean
*/
public static function delete($filename)
{
// Is array
if (is_array($filename)) {
// Delete each file in $filename array
foreach ($filename as $file) {
@unlink((string) $file);
}
} else {
// Is string
return @unlink((string) $filename);
}
}
/**
* Rename file
*
* <code>
* File::rename('filename1.txt', 'filename2.txt');
* </code>
*
* @param string $from Original file location
* @param string $to Desitination location of the file
* @return boolean
*/
public static function rename($from, $to)
{
// Redefine vars
$from = (string) $from;
$to = (string) $to;
// If file exists $to than rename it
if ( ! File::exists($to)) return rename($from, $to);
// Else return false
return false;
}
/**
* Copy file
*
* <code>
* File::copy('folder1/filename.txt', 'folder2/filename.txt');
* </code>
*
* @param string $from Original file location
* @param string $to Desitination location of the file
* @return boolean
*/
public static function copy($from, $to)
{
// Redefine vars
$from = (string) $from;
$to = (string) $to;
// If file !exists $from and exists $to then return false
if ( ! File::exists($from) || File::exists($to)) return false;
// Else copy file
return copy($from, $to);
}
/**
* Get the File extension.
*
* <code>
* echo File::ext('filename.txt');
* </code>
*
* @param string $filename The file name
* @return string
*/
public static function ext($filename)
{
// Redefine vars
$filename = (string) $filename;
// Return file extension
return substr(strrchr($filename, '.'), 1);
}
/**
* Get the File name
*
* <code>
* echo File::name('filename.txt');
* </code>
*
* @param string $filename The file name
* @return string
*/
public static function name($filename)
{
// Redefine vars
$filename = (string) $filename;
// Return filename
return basename($filename, '.'.File::ext($filename));
}
/**
* Get list of files in directory recursive
*
* <code>
* $files = File::scan('folder');
* $files = File::scan('folder', 'txt');
* $files = File::scan('folder', array('txt', 'log'));
* </code>
*
* @param string $folder Folder
* @param mixed $type Files types
* @return array
*/
public static function scan($folder, $type = null)
{
$data = array();
if (is_dir($folder)) {
$iterator = new RecursiveDirectoryIterator($folder);
foreach (new RecursiveIteratorIterator($iterator) as $file) {
if ($type !== null) {
if (is_array($type)) {
$file_ext = substr(strrchr($file->getFilename(), '.'), 1);
if (in_array($file_ext, $type)) {
if (strpos($file->getFilename(), $file_ext, 1)) {
$data[] = $file->getFilename();
}
}
} else {
if (strpos($file->getFilename(), $type, 1)) {
$data[] = $file->getFilename();
}
}
} else {
if ($file->getFilename() !== '.' && $file->getFilename() !== '..') $data[] = $file->getFilename();
}
}
return $data;
} else {
return false;
}
}
/**
* Fetch the content from a file or URL.
*
* <code>
* echo File::getContent('filename.txt');
* </code>
*
* @param string $filename The file name
* @return boolean
*/
public static function getContent($filename)
{
// Redefine vars
$filename = (string) $filename;
// If file exists load it
if (File::exists($filename)) {
return file_get_contents($filename);
}
}
/**
* Writes a string to a file.
*
* @param string $filename The path of the file.
* @param string $content The content that should be written.
* @param boolean $createFile Should the file be created if it doesn't exists?
* @param boolean $append Should the content be appended if the file already exists?
* @param integer $chmod Mode that should be applied on the file.
* @return boolean
*/
public static function setContent($filename, $content, $create_file = true, $append = false, $chmod = 0666)
{
// Redefine vars
$filename = (string) $filename;
$content = (string) $content;
$create_file = (bool) $create_file;
$append = (bool) $append;
// File may not be created, but it doesn't exist either
if ( ! $create_file && File::exists($filename)) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' doesn't exist", array(__METHOD__)));
// Create directory recursively if needed
Dir::create(dirname($filename));
// Create file & open for writing
$handler = ($append) ? @fopen($filename, 'a') : @fopen($filename, 'w');
// Something went wrong
if ($handler === false) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' could not be created. Check if PHP has enough permissions.", array(__METHOD__)));
// Store error reporting level
$level = error_reporting();
// Disable errors
error_reporting(0);
// Write to file
$write = fwrite($handler, $content);
// Validate write
if($write === false) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' could not be created. Check if PHP has enough permissions.", array(__METHOD__)));
// Close the file
fclose($handler);
// Chmod file
chmod($filename, $chmod);
// Restore error reporting level
error_reporting($level);
// Return
return true;
}
/**
* Get time(in Unix timestamp) the file was last changed
*
* <code>
* echo File::lastChange('filename.txt');
* </code>
*
* @param string $filename The file name
* @return boolean
*/
public static function lastChange($filename)
{
// Redefine vars
$filename = (string) $filename;
// If file exists return filemtime
if (File::exists($filename)) {
return filemtime($filename);
}
// Return
return false;
}
/**
* Get last access time
*
* <code>
* echo File::lastAccess('filename.txt');
* </code>
*
* @param string $filename The file name
* @return boolean
*/
public static function lastAccess($filename)
{
// Redefine vars
$filename = (string) $filename;
// If file exists return fileatime
if (File::exists($filename)) {
return fileatime($filename);
}
// Return
return false;
}
/**
* Returns the mime type of a file. Returns false if the mime type is not found.
*
* <code>
* echo File::mime('filename.txt');
* </code>
*
* @param string $file Full path to the file
* @param boolean $guess Set to false to disable mime type guessing
* @return string
*/
public static function mime($file, $guess = true)
{
// Redefine vars
$file = (string) $file;
$guess = (bool) $guess;
// Get mime using the file information functions
if (function_exists('finfo_open')) {
$info = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($info, $file);
finfo_close($info);
return $mime;
} else {
// Just guess mime by using the file extension
if ($guess === true) {
$mime_types = File::$mime_types;
$extension = pathinfo($file, PATHINFO_EXTENSION);
return isset($mime_types[$extension]) ? $mime_types[$extension] : false;
} else {
return false;
}
}
}
/**
* Forces a file to be downloaded.
*
* <code>
* File::download('filename.txt');
* </code>
*
* @param string $file Full path to file
* @param string $content_type Content type of the file
* @param string $filename Filename of the download
* @param integer $kbps Max download speed in KiB/s
*/
public static function download($file, $content_type = null, $filename = null, $kbps = 0)
{
// Redefine vars
$file = (string) $file;
$content_type = ($content_type === null) ? null : (string) $content_type;
$filename = ($filename === null) ? null : (string) $filename;
$kbps = (int) $kbps;
// Check that the file exists and that its readable
if (file_exists($file) === false || is_readable($file) === false) {
throw new RuntimeException(vsprintf("%s(): Failed to open stream.", array(__METHOD__)));
}
// Empty output buffers
while (ob_get_level() > 0) ob_end_clean();
// Send headers
if ($content_type === null) $content_type = File::mime($file);
if ($filename === null) $filename = basename($file);
header('Content-type: ' . $content_type);
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($file));
// Read file and write it to the output
@set_time_limit(0);
if ($kbps === 0) {
readfile($file);
} else {
$handle = fopen($file, 'r');
while ( ! feof($handle) && !connection_aborted()) {
$s = microtime(true);
echo fread($handle, round($kbps * 1024));
if (($wait = 1e6 - (microtime(true) - $s)) > 0) usleep($wait);
}
fclose($handle);
}
exit();
}
/**
* Display a file in the browser.
*
* <code>
* File::display('filename.txt');
* </code>
*
* @param string $file Full path to file
* @param string $content_type Content type of the file
* @param string $filename Filename of the download
*/
public static function display($file, $content_type = null, $filename = null)
{
// Redefine vars
$file = (string) $file;
$content_type = ($content_type === null) ? null : (string) $content_type;
$filename = ($filename === null) ? null : (string) $filename;
// Check that the file exists and that its readable
if (file_exists($file) === false || is_readable($file) === false) {
throw new RuntimeException(vsprintf("%s(): Failed to open stream.", array(__METHOD__)));
}
// Empty output buffers
while (ob_get_level() > 0) ob_end_clean();
// Send headers
if ($content_type === null) $content_type = File::mime($file);
if($filename === null) $filename = basename($file);
header('Content-type: ' . $content_type);
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Length: ' . filesize($file));
// Read file and write to output
readfile($file);
exit();
}
/**
* Tests whether a file is writable for anyone.
*
* <code>
* if (File::writable('filename.txt')) {
* // do something...
* }
* </code>
*
* @param string $file File to check
* @return boolean
*/
public static function writable($file)
{
// Redefine vars
$file = (string) $file;
// Is file exists ?
if ( ! file_exists($file)) throw new RuntimeException(vsprintf("%s(): The file '{$file}' doesn't exist", array(__METHOD__)));
// Gets file permissions
$perms = fileperms($file);
// Is writable ?
if (is_writable($file) || ($perms & 0x0080) || ($perms & 0x0010) || ($perms & 0x0002)) return true;
}
}

409
libraries/monstra/Form.php Normal file
View File

@@ -0,0 +1,409 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Form
{
/**
* The registered custom macros.
*
* @var array
*/
public static $macros = array();
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Registers a custom macro.
*
* <code>
*
* // Registering a Form macro
* Form::macro('my_field', function() {
* return '<input type="text" name="my_field">';
* });
*
* // Calling a custom Form macro
* echo Form::my_field();
*
*
* // Registering a Form macro with parameters
* Form::macro('my_field', function($value = '') {
* return '<input type="text" name="my_field" value="'.$value.'">';
* });
*
* // Calling a custom Form macro with parameters
* echo Form::my_field('Monstra');
*
* </code>
*
* @param string $name Name
* @param Closure $macro Macro
*/
public static function macro($name, $macro)
{
Form::$macros[$name] = $macro;
}
/**
* Create an opening HTML form tag.
*
* <code>
* // Form will submit back to the current page using POST
* echo Form::open();
*
* // Form will submit to 'search' using GET
* echo Form::open('search', array('method' => 'get'));
*
* // When "file" inputs are present, you must include the "enctype"
* echo Form::open(null, array('enctype' => 'multipart/form-data'));
* </code>
*
* @param mixed $action Form action, defaults to the current request URI.
* @param array $attributes HTML attributes.
* @uses Url::base
* @uses Html::attributes
* @return string
*/
public static function open($action = null, array $attributes = null)
{
if (! $action) {
// Submits back to the current url
$action = '';
} elseif (strpos($action, '://') === false) {
// Make the URI absolute
$action = Url::base() . '/' . $action;
}
// Add the form action to the attributes
$attributes['action'] = $action;
if ( ! isset($attributes['method'])) {
// Use POST method
$attributes['method'] = 'post';
}
return '<form'.Html::attributes($attributes).'>';
}
/**
* Create a form input.
* Text is default input type.
*
* <code>
* echo Form::input('username', $username);
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param array $attributes HTML attributes
* @uses Html::attributes
* @return string
*/
public static function input($name, $value = null, array $attributes = null)
{
// Set the input name
$attributes['name'] = $name;
// Set the input id
$attributes['id'] = (isset($attributes['id']))?$attributes['id']:$name;
// Set the input value
$attributes['value'] = $value;
if ( ! isset($attributes['type'])) {
// Default type is text
$attributes['type'] = 'text';
}
return '<input'.Html::attributes($attributes).' />';
}
/**
* Create a hidden form input.
*
* <code>
* echo Form::hidden('user_id', $user_id);
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function hidden($name, $value = null, array $attributes = null)
{
// Set the input type
$attributes['type'] = 'hidden';
return Form::input($name, $value, $attributes);
}
/**
* Creates a password form input.
*
* <code>
* echo Form::password('password');
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function password($name, $value = null, array $attributes = null)
{
// Set the input type
$attributes['type'] = 'password';
return Form::input($name, $value, $attributes);
}
/**
* Creates a file upload form input.
*
* <code>
* echo Form::file('image');
* </code>
*
* @param string $name Input name
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function file($name, array $attributes = null)
{
// Set the input type
$attributes['type'] = 'file';
return Form::input($name, null, $attributes);
}
/**
* Creates a checkbox form input.
*
* <code>
* echo Form::checkbox('i_am_not_a_robot');
* </code>
*
* @param string $name Input name
* @param string $input Input value
* @param boolean $checked Checked status
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function checkbox($name, $value = null, $checked = false, array $attributes = null)
{
// Set the input type
$attributes['type'] = 'checkbox';
if ($checked === true) {
// Make the checkbox active
$attributes['checked'] = 'checked';
}
return Form::input($name, $value, $attributes);
}
/**
* Creates a radio form input.
*
* <code>
* echo Form::radio('i_am_not_a_robot');
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param boolean $checked Checked status
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function radio($name, $value = null, $checked = null, array $attributes = null)
{
// Set the input type
$attributes['type'] = 'radio';
if ($checked === true) {
// Make the radio active
$attributes['checked'] = 'checked';
}
return Form::input($name, $value, $attributes);
}
/**
* Creates a textarea form input.
*
* <code>
* echo Form::textarea('text', $text);
* </code>
*
* @param string $name Name
* @param string $body Body
* @param array $attributes HTML attributes
* @uses Html::attributes
* @return string
*/
public static function textarea($name, $body = '', array $attributes = null)
{
// Set the input name
$attributes['name'] = $name;
// Set the input id
$attributes['id'] = (isset($attributes['id']))?$attributes['id']:$name;
return '<textarea'.Html::attributes($attributes).'>'.$body.'</textarea>';
}
/**
* Creates a select form input.
*
* <code>
* echo Form::select('themes', array('default', 'classic', 'modern'));
* </code>
*
* @param string $name Name
* @param array $options Options array
* @param string $selected Selected option
* @param array $attributes HTML attributes
* @uses Html::attributes
* @return string
*/
public static function select($name, array $options = null, $selected = null, array $attributes = null)
{
// Set the input name
$attributes['name'] = $name;
// Set the input id
$attributes['id'] = (isset($attributes['id']))?$attributes['id']:$name;
$options_output = '';
foreach ($options as $value => $name) {
if ($selected == $value) $current = ' selected '; else $current = '';
$options_output .= '<option value="'.$value.'" '.$current.'>'.$name.'</option>';
}
return '<select'.Html::attributes($attributes).'>'.$options_output.'</select>';
}
/**
* Creates a submit form input.
*
* <code>
* echo Form::submit('save', 'Save');
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function submit($name, $value, array $attributes = null)
{
// Set the input type
$attributes['type'] = 'submit';
return Form::input($name, $value, $attributes);
}
/**
* Creates a button form input.
*
* <code>
* echo Form::button('save', 'Save Profile', array('type' => 'submit'));
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param array $attributes HTML attributes
* @uses Html::attributes
* @return string
*/
public static function button($name, $body, array $attributes = null)
{
// Set the input name
$attributes['name'] = $name;
return '<button'.Html::attributes($attributes).'>'.$body.'</button>';
}
/**
* Creates a form label.
*
* <code>
* echo Form::label('username', 'Username');
* </code>
*
* @param string $input Target input
* @param string $text Label text
* @param array $attributes HTML attributes
* @uses Html::attributes
* @return string
*/
public static function label($input, $text, array $attributes = null)
{
// Set the label target
$attributes['for'] = $input;
return '<label'.Html::attributes($attributes).'>'.$text.'</label>';
}
/**
* Create closing form tag.
*
* <code>
* echo Form::close();
* </code>
*
* @return string
*/
public static function close()
{
return '</form>';
}
/**
* Dynamically handle calls to custom macros.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
if (isset(Form::$macros[$method])) {
return call_user_func_array(Form::$macros[$method], $parameters);
}
throw new RuntimeException("Method [$method] does not exist.");
}
}

314
libraries/monstra/Html.php Normal file
View File

@@ -0,0 +1,314 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Html
{
/**
* Preferred order of attributes
*
* @var array
*/
public static $attribute_order = array (
'action', 'method', 'type', 'id', 'name', 'value',
'href', 'src', 'width', 'height', 'cols', 'rows',
'size', 'maxlength', 'rel', 'media', 'accept-charset',
'accept', 'tabindex', 'accesskey', 'alt', 'title', 'class',
'style', 'selected', 'checked', 'readonly', 'disabled',
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Registers a custom macro.
*
* <code>
*
* // Registering a Htmlk macro
* Html::macro('my_element', function() {
* return '<element id="monstra">';
* });
*
* // Calling a custom Html macro
* echo Html::my_element();
*
*
* // Registering a Html macro with parameters
* Html::macro('my_element', function(id = '') {
* return '<element id="'.$id.'">';
* });
*
* // Calling a custom Html macro with parameters
* echo Html::my_element('monstra');
*
* </code>
*
* @param string $name Name
* @param Closure $macro Macro
*/
public static function macro($name, $macro)
{
Html::$macros[$name] = $macro;
}
/**
* Convert special characters to HTML entities. All untrusted content
* should be passed through this method to prevent XSS injections.
*
* <code>
* echo Html::chars($username);
* </code>
*
* @param string $value String to convert
* @param boolean $double_encode Encode existing entities
* @return string
*/
public static function chars($value, $double_encode = true)
{
return htmlspecialchars((string) $value, ENT_QUOTES, 'utf-8', $double_encode);
}
/**
* Compiles an array of HTML attributes into an attribute string.
* Attributes will be sorted using Html::$attribute_order for consistency.
*
* <code>
* echo '<div'.Html::attributes($attrs).'>'.$content.'</div>';
* </code>
*
* @param array $attributes Attribute list
* @return string
*/
public static function attributes(array $attributes = null)
{
if (empty($attributes)) return '';
// Init var
$sorted = array();
foreach (Html::$attribute_order as $key) {
if (isset($attributes[$key])) {
// Add the attribute to the sorted list
$sorted[$key] = $attributes[$key];
}
}
// Combine the sorted attributes
$attributes = $sorted + $attributes;
$compiled = '';
foreach ($attributes as $key => $value) {
if ($value === NULL) {
// Skip attributes that have NULL values
continue;
}
if (is_int($key)) {
// Assume non-associative keys are mirrored attributes
$key = $value;
}
// Add the attribute value
$compiled .= ' '.$key.'="'.Html::chars($value).'"';
}
return $compiled;
}
/**
* Create br tags
*
* <code>
* echo Html::br(2);
* </code>
*
* @param integer $num Count of line break tag
* @return string
*/
public static function br($num = 1)
{
return str_repeat("<br />",(int) $num);
}
/**
* Create &nbsp;
*
* <code>
* echo Html::nbsp(2);
* </code>
*
* @param integer $num Count of &nbsp;
* @return string
*/
public static function nbsp($num = 1)
{
return str_repeat("&nbsp;", (int) $num);
}
/**
* Create an arrow
*
* <code>
* echo Html::arrow('right');
* </code>
*
* @param string $direction Arrow direction [up,down,left,right]
* @param boolean $render If this option is true then render html object else return it
* @return string
*/
public static function arrow($direction)
{
switch ($direction) {
case "up": $output = '<span class="arrow">&uarr;</span>'; break;
case "down": $output = '<span class="arrow">&darr;</span>'; break;
case "left": $output = '<span class="arrow">&larr;</span>'; break;
case "right": $output = '<span class="arrow">&rarr;</span>'; break;
}
return $output;
}
/**
* Create HTML link anchor.
*
* <code>
* echo Html::anchor('About', 'http://sitename.com/about');
* </code>
*
* @param string $title Anchor title
* @param string $url Anchor url
* @param array $attributes Anchor attributes
* @uses Html::attributes
* @return string
*/
public static function anchor($title, $url = null, array $attributes = null)
{
// Add link
if ($url !== null) $attributes['href'] = $url;
return '<a'.Html::attributes($attributes).'>'.$title.'</a>';
}
/**
* Create HTML <h> tag
*
* <code>
* echo Html::heading('Title', 1);
* </code>
*
* @param string $title Text
* @param integer $h Number [1-6]
* @param array $attributes Heading attributes
* @uses Html::attributes
* @return string
*/
public static function heading($title, $h = 1, array $attributes = null)
{
$output = '<h'.(int) $h.Html::attributes($attributes).'>'.$title.'</h'.(int) $h.'>';
return $output;
}
/**
* Generate document type declarations
*
* <code>
* echo Html::doctype('html5');
* </code>
*
* @param string $type Doctype to generated
* @return mixed
*/
public static function doctype($type = 'html5')
{
$doctypes = array('xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">');
if (isset($doctypes[$type])) return $doctypes[$type]; else return false;
}
/**
* Create image
*
* <code>
* echo Html::image('data/files/pic1.jpg');
* </code>
*
* @param array $attributes Image attributes
* @param string $file File
* @uses Url::base
* @return string
*/
public static function image($file, array $attributes = null)
{
if (strpos($file, '://') === FALSE) {
$file = Url::base().'/'.$file;
}
// Add the image link
$attributes['src'] = $file;
$attributes['alt'] = (isset($attributes['alt'])) ? $attributes['alt'] : pathinfo($file, PATHINFO_FILENAME);
return '<img'.Html::attributes($attributes).' />';
}
/**
* Convert html to plain text
*
* <code>
* echo Html::toText('test');
* </code>
*
* @param string $str String
* @return string
*/
public static function toText($str)
{
return htmlspecialchars($str, ENT_QUOTES, 'utf-8');
}
/**
* Dynamically handle calls to custom macros.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters)
{
if (isset(Html::$macros[$method])) {
return call_user_func_array(Html::$macros[$method], $parameters);
}
throw new RuntimeException("Method [$method] does not exist.");
}
}

653
libraries/monstra/Image.php Normal file
View File

@@ -0,0 +1,653 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Image
{
/**
* Resizing contraint.
*
* @var integer
*/
const AUTO = 1;
/**
* Resizing contraint.
*
* @var integer
*/
const WIDTH = 2;
/**
* Resizing contraint.
*
* @var integer
*/
const HEIGHT = 3;
/**
* Watermark position.
*/
const TOP_LEFT = 4;
/**
* Watermark position.
*/
const TOP_RIGHT = 5;
/**
* Watermark position.
*/
const BOTTOM_LEFT = 6;
/**
* Watermark position.
*/
const BOTTOM_RIGHT = 7;
/**
* Watermark position.
*/
const CENTER = 8;
/**
* Holds info about the image.
*
* @var array
*/
protected $image_info;
/**
* Get value
*
* @param string $key Key
* @return mixed
*/
public function __get($key)
{
if (array_key_exists($key, $this->image_info)) return $this->image_info[$key];
}
/**
* Set value for specific key
*
* @param string $key Key
* @param mixed $value Value
*/
public function __set($key, $value)
{
$this->image_info[$key] = $value;
}
/**
* Image factory.
*
* <code>
* $image = Image::factory('original.png');
* </code>
*
* @param string $filename Filename
* @return Image
*/
public static function factory($filename)
{
return new Image($filename);
}
/**
* Construct
*
* @param string $file Filename
*/
public function __construct($file)
{
// Redefine vars
$file = (string) $file;
// Check if the file exists
if (file_exists($file)) {
// Extract attributes of the image file
list($this->width, $this->height, $type, $a) = getimagesize($file);
// Save image type
$this->type = $type;
// Create a new image
$this->image = $this->createImage($file, $type);
} else {
throw new RuntimeException(vsprintf("%s(): The file '{$file}' doesn't exist", array(__METHOD__)));
}
}
/**
* Create a new image from file.
*
* @param string $file Path to the image file
* @param integer $type Image type
* @return resource
*/
protected function createImage($file, $type)
{
// Create image from file
switch ($type) {
case IMAGETYPE_JPEG:
return imagecreatefromjpeg($file);
break;
case IMAGETYPE_GIF:
return imagecreatefromgif($file);
break;
case IMAGETYPE_PNG:
return imagecreatefrompng($file);
break;
default:
throw new RuntimeException(vsprintf("%s(): Unable to open '%s'. Unsupported image type.", array(__METHOD__, $type)));
}
}
/**
* Resizes the image to the chosen size.
*
* <code>
* Image::factory('original.png')->resize(800, 600)->save('edited.png');
* </code>
*
* @param integer $width Width of the image
* @param integer $height Height of the image
* @param integer $aspect_ratio Aspect ratio (Image::AUTO Image::WIDTH Image::HEIGHT)
* @return Image
*/
public function resize($width, $height = null, $aspect_ratio = null)
{
// Redefine vars
$width = (int) $width;
$height = ($height === null) ? null : (int) $height;
$aspect_ratio = ($aspect_ratio === null) ? null : (int) $aspect_ratio;
// Resizes the image to {$width}% of the original size
if ($height === null) {
$new_width = round($this->width * ($width / 100));
$new_height = round($this->height * ($width / 100));
} else {
// Resizes the image to the smalles possible dimension while maintaining aspect ratio
if ($aspect_ratio === Image::AUTO) {
// Calculate smallest size based on given height and width while maintaining aspect ratio
$percentage = min(($width / $this->width), ($height / $this->height));
$new_width = round($this->width * $percentage);
$new_height = round($this->height * $percentage);
// Resizes the image using the width to maintain aspect ratio
} elseif ($aspect_ratio === Image::WIDTH) {
// Base new size on given width while maintaining aspect ratio
$new_width = $width;
$new_height = round($this->height * ($width / $this->width));
// Resizes the image using the height to maintain aspect ratio
} elseif ($aspect_ratio === Image::HEIGHT) {
// Base new size on given height while maintaining aspect ratio
$new_width = round($this->width * ($height / $this->height));
$new_height = $height;
// Resizes the image to a dimension of {$width}x{$height} pixels while ignoring the aspect ratio
} else {
$new_width = $width;
$new_height = $height;
}
}
// Create a new true color image width new width and height
$resized = imagecreatetruecolor($new_width, $new_height);
// Copy and resize part of an image with resampling
imagecopyresampled($resized, $this->image, 0, 0, 0, 0, $new_width, $new_height, $this->width, $this->height);
// Destroy an image
imagedestroy($this->image);
// Create a new true color image width new width and height
$this->image = imagecreatetruecolor($new_width, $new_height);
// Copy and resize part of an image with resampling
imagecopyresampled($this->image, $resized, 0, 0, 0, 0, $new_width, $new_height, $new_width, $new_height);
// Destroy an image
imagedestroy($resized);
// Save new width and height
$this->width = $new_width;
$this->height = $new_height;
return $this;
}
/**
* Crops the image
*
* <code>
* Image::factory('original.png')->crop(800, 600, 0, 0)->save('edited.png');
* </code>
*
* @param integer $width Width of the crop
* @param integer $height Height of the crop
* @param integer $x The X coordinate of the cropped region's top left corner
* @param integer $y The Y coordinate of the cropped region's top left corner
* @return Image
*/
public function crop($width, $height, $x, $y)
{
// Redefine vars
$width = (int) $width;
$height = (int) $height;
$x = (int) $x;
$y = (int) $y;
// Calculate
if ($x + $width > $this->width) $width = $this->width - $x;
if ($y + $height > $this->height) $height = $this->height - $y;
if ($width <= 0 || $height <= 0) return false;
// Create a new true color image
$crop = imagecreatetruecolor($width, $height);
// Copy and resize part of an image with resampling
imagecopyresampled($crop, $this->image, 0, 0, $x, $y, $this->width, $this->height, $this->width, $this->height);
// Destroy an image
imagedestroy($this->image);
// Create a new true color image
$this->image = imagecreatetruecolor($width, $height);
// Copy and resize part of an image with resampling
imagecopyresampled($this->image, $crop, 0, 0, 0, 0, $width, $height, $width, $height);
// Destroy an image
imagedestroy($crop);
// Save new width and height
$this->width = $width;
$this->height = $height;
return $this;
}
/**
* Adds a watermark to the image.
*
* @param string $file Path to the image file
* @param integer $position Position of the watermark
* @param integer $opacity Opacity of the watermark in percent
* @return Image
*/
public function watermark($file, $position = null, $opacity = 100)
{
// Check if the image exists
if ( ! file_exists($file)) {
throw new RuntimeException(vsprintf("%s(): The image file ('%s') does not exist.", array(__METHOD__, $file)));
}
$watermark = $this->createImage($file, $this->type);
$watermarkW = imagesx($watermark);
$watermarkH = imagesy($watermark);
// Make sure that opacity is between 0 and 100
$opacity = max(min((int) $opacity, 100), 0);
if ($opacity < 100) {
if (GD_BUNDLED === 0) {
throw new RuntimeException(vsprintf("%s(): Setting watermark opacity requires the 'imagelayereffect' function which is only available in the bundled version of GD.", array(__METHOD__)));
}
// Convert alpha to 0-127
$alpha = min(round(abs(($opacity * 127 / 100) - 127)), 127);
$transparent = imagecolorallocatealpha($watermark, 0, 0, 0, $alpha);
imagelayereffect($watermark, IMG_EFFECT_OVERLAY);
imagefilledrectangle($watermark, 0, 0, $watermarkW, $watermarkH, $transparent);
}
// Position the watermark.
switch ($position) {
case Image::TOP_RIGHT:
$x = imagesx($this->image) - $watermarkW;
$y = 0;
break;
case Image::BOTTOM_LEFT:
$x = 0;
$y = imagesy($this->image) - $watermarkH;
break;
case Image::BOTTOM_RIGHT:
$x = imagesx($this->image) - $watermarkW;
$y = imagesy($this->image) - $watermarkH;
break;
case Image::CENTER:
$x = (imagesx($this->image) / 2) - ($watermarkW / 2);
$y = (imagesy($this->image) / 2) - ($watermarkH / 2);
break;
default:
$x = 0;
$y = 0;
}
imagealphablending($this->image, true);
imagecopy($this->image, $watermark, $x, $y, 0, 0, $watermarkW, $watermarkH);
imagedestroy($watermark);
// Return Image
return $this;
}
/**
* Convert image into grayscale
*
* <code>
* Image::factory('original.png')->grayscale()->save('edited.png');
* </code>
*
* @return Image
*/
public function grayscale()
{
imagefilter($this->image, IMG_FILTER_GRAYSCALE);
return $this;
}
/**
* Convert image into sepia
*
* <code>
* Image::factory('original.png')->sepia()->save('edited.png');
* </code>
*
* @return Image
*/
public function sepia()
{
imagefilter($this->image, IMG_FILTER_GRAYSCALE);
imagefilter($this->image, IMG_FILTER_COLORIZE, 112, 66, 20);
return $this;
}
/**
* Convert image into brightness
*
* <code>
* Image::factory('original.png')->brightness(60)->save('edited.png');
* </code>
*
* @param integer $level Level. From -255(min) to 255(max)
* @return Image
*/
public function brightness($level = 0)
{
imagefilter($this->image, IMG_FILTER_BRIGHTNESS, (int) $level);
return $this;
}
/**
* Convert image into colorize
*
* <code>
* Image::factory('original.png')->colorize(60, 0, 0)->save('edited.png');
* </code>
*
* @param integer $red Red
* @param integer $green Green
* @param integer $blue Blue
* @return Image
*/
public function colorize($red, $green, $blue)
{
imagefilter($this->image, IMG_FILTER_COLORIZE, (int) $red, (int) $green, (int) $blue);
return $this;
}
/**
* Convert image into contrast
*
* <code>
* Image::factory('original.png')->contrast(60)->save('edited.png');
* </code>
*
* @param integer $level Level. From -100(max) to 100(min) note the direction!
* @return Image
*/
public function contrast($level)
{
imagefilter($this->image, IMG_FILTER_CONTRAST, (int) $level);
return $this;
}
/**
* Creates a color based on a hex value.
*
* @param string $hex Hex code of the color
* @param integer $alpha Alpha. Default is 100
* @param boolean $returnRGB FALSE returns a color identifier, TRUE returns a RGB array
* @return integer
*/
protected function createColor($hex, $alpha = 100, $return_rgb = false)
{
// Redefine vars
$hex = (string) $hex;
$alpha = (int) $alpha;
$return_rgb = (bool) $return_rgb;
$hex = str_replace('#', '', $hex);
if (preg_match('/^([a-f0-9]{3}){1,2}$/i', $hex) === 0) {
throw new RuntimeException(vsprintf("%s(): Invalid color code ('%s').", array(__METHOD__, $hex)));
}
if (strlen($hex) === 3) {
$r = hexdec(str_repeat(substr($hex, 0, 1), 2));
$g = hexdec(str_repeat(substr($hex, 1, 1), 2));
$b = hexdec(str_repeat(substr($hex, 2, 1), 2));
} else {
$r = hexdec(substr($hex, 0, 2));
$g = hexdec(substr($hex, 2, 2));
$b = hexdec(substr($hex, 4, 2));
}
if ($return_rgb === true) {
return array('r' => $r, 'g' => $g, 'b' => $b);
} else {
// Convert alpha to 0-127
$alpha = min(round(abs(($alpha * 127 / 100) - 127)), 127);
return imagecolorallocatealpha($this->image, $r, $g, $b, $alpha);
}
}
/**
* Rotates the image using the given angle in degrees.
*
* <code>
* Image::factory('original.png')->rotate(90)->save('edited.png');
* </code>
*
* @param integer $degrees Degrees to rotate the image
* @return Image
*/
public function rotate($degrees)
{
if (GD_BUNDLED === 0) {
throw new RuntimeException(vsprintf("%s(): This method requires the 'imagerotate' function which is only available in the bundled version of GD.", array(__METHOD__)));
}
// Redefine vars
$degrees = (int) $degrees;
// Get image width and height
$width = imagesx($this->image);
$height = imagesy($this->image);
// Allocate a color for an image
$transparent = imagecolorallocatealpha($this->image, 0, 0, 0, 127);
// Rotate gif image
if ($this->image_info['type'] === IMAGETYPE_GIF) {
// Create a new true color image
$temp = imagecreatetruecolor($width, $height);
// Flood fill
imagefill($temp, 0, 0, $transparent);
// Copy part of an image
imagecopy($temp, $this->image, 0, 0, 0, 0, $width, $height);
// Destroy an image
imagedestroy($this->image);
// Save temp image
$this->image = $temp;
}
// Rotate an image with a given angle
$this->image = imagerotate($this->image, (360 - $degrees), $transparent);
// Define a color as transparent
imagecolortransparent($this->image, $transparent);
return $this;
}
/**
* Adds a border to the image.
*
* <code>
* Image::factory('original.png')->border('#000', 5)->save('edited.png');
* </code>
*
* @param string $color Hex code for the color
* @param integer $thickness Thickness of the frame in pixels
* @return Image
*/
public function border($color = '#000', $thickness = 5)
{
// Redefine vars
$color = (string) $color;
$thickness = (int) $thickness;
// Get image width and height
$width = imagesx($this->image);
$height = imagesy($this->image);
// Creates a color based on a hex value
$color = $this->createColor($color);
// Create border
for ($i = 0; $i < $thickness; $i++) {
if ($i < 0) {
$x = $width + 1;
$y = $hidth + 1;
} else {
$x = --$width;
$y = --$height;
}
imagerectangle($this->image, $i, $i, $x, $y, $color);
}
return $this;
}
/**
* Save image
*
* <code>
* Image::factory('original.png')->save('edited.png');
* </code>
*
* @param string $dest Desitination location of the file
* @param integer $quality Image quality. Default is 100
* @return Image
*/
public function save($file, $quality = 100)
{
// Redefine vars
$file = (string) $file;
$quality = (int) $quality;
$path_info = pathinfo($file);
if ( ! is_writable($path_info['dirname'])) {
throw new RuntimeException(vsprintf("%s(): '%s' is not writable.", array(__METHOD__, $path_info['dirname'])));
}
// Make sure that quality is between 0 and 100
$quality = max(min((int) $quality, 100), 0);
// Save image
switch ($path_info['extension']) {
case 'jpg':
case 'jpeg':
imagejpeg($this->image, $file, $quality);
break;
case 'gif':
imagegif($this->image, $file);
break;
case 'png':
imagealphablending($this->image, true);
imagesavealpha($this->image, true);
imagepng($this->image, $file, (9 - (round(($quality / 100) * 9))));
break;
default:
throw new RuntimeException(vsprintf("%s(): Unable to save to '%s'. Unsupported image format.", array(__METHOD__, $path_info['extension'])));
}
// Return Image
return $this;
}
/**
* Destructor
*/
public function __destruct()
{
imagedestroy($this->image);
}
}

View File

@@ -0,0 +1,224 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Inflector
{
/**
* Plural rules
*
* @var array
*/
protected static $plural_rules = array(
'/^(ox)$/' => '\1\2en', // ox
'/([m|l])ouse$/' => '\1ice', // mouse, louse
'/(matr|vert|ind)ix|ex$/' => '\1ices', // matrix, vertex, index
'/(x|ch|ss|sh)$/' => '\1es', // search, switch, fix, box, process, address
'/([^aeiouy]|qu)y$/' => '\1ies', // query, ability, agency
'/(hive)$/' => '\1s', // archive, hive
'/(?:([^f])fe|([lr])f)$/' => '\1\2ves', // half, safe, wife
'/sis$/' => 'ses', // basis, diagnosis
'/([ti])um$/' => '\1a', // datum, medium
'/(p)erson$/' => '\1eople', // person, salesperson
'/(m)an$/' => '\1en', // man, woman, spokesman
'/(c)hild$/' => '\1hildren', // child
'/(buffal|tomat)o$/' => '\1\2oes', // buffalo, tomato
'/(bu|campu)s$/' => '\1\2ses', // bus, campus
'/(alias|status|virus)$/' => '\1es', // alias
'/(octop)us$/' => '\1i', // octopus
'/(ax|cris|test)is$/' => '\1es', // axis, crisis
'/s$/' => 's', // no change (compatibility)
'/$/' => 's',
);
/**
* Singular rules
*
* @var array
*/
protected static $singular_rules = array(
'/(matr)ices$/' => '\1ix',
'/(vert|ind)ices$/' => '\1ex',
'/^(ox)en/' => '\1',
'/(alias)es$/' => '\1',
'/([octop|vir])i$/' => '\1us',
'/(cris|ax|test)es$/' => '\1is',
'/(shoe)s$/' => '\1',
'/(o)es$/' => '\1',
'/(bus|campus)es$/' => '\1',
'/([m|l])ice$/' => '\1ouse',
'/(x|ch|ss|sh)es$/' => '\1',
'/(m)ovies$/' => '\1\2ovie',
'/(s)eries$/' => '\1\2eries',
'/([^aeiouy]|qu)ies$/' => '\1y',
'/([lr])ves$/' => '\1f',
'/(tive)s$/' => '\1',
'/(hive)s$/' => '\1',
'/([^f])ves$/' => '\1fe',
'/(^analy)ses$/' => '\1sis',
'/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/' => '\1\2sis',
'/([ti])a$/' => '\1um',
'/(p)eople$/' => '\1\2erson',
'/(m)en$/' => '\1an',
'/(s)tatuses$/' => '\1\2tatus',
'/(c)hildren$/' => '\1\2hild',
'/(n)ews$/' => '\1\2ews',
'/([^us])s$/' => '\1',
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Returns a camelized string from a string using underscore syntax.
*
* <code>
* // "some_text_here" becomes "SomeTextHere"
* echo Inflector::camelize('some_text_here');
* </code>
*
* @param string $string Word to camelize.
* @return string Camelized word.
*/
public static function camelize($string)
{
// Redefine vars
$string = (string) $string;
return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
}
/**
* Returns a string using underscore syntax from a camelized string.
*
* <code>
* // "SomeTextHere" becomes "some_text_here"
* echo Inflector::underscore('SomeTextHere');
* </code>
*
* @param string $string CamelCased word
* @return string Underscored version of the $string
*/
public static function underscore($string)
{
// Redefine vars
$string = (string) $string;
return strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string));
}
/**
* Returns a humanized string from a string using underscore syntax.
*
* <code>
* // "some_text_here" becomes "Some text here"
* echo Inflector::humanize('some_text_here');
* </code>
*
* @param string $string String using underscore syntax.
* @return string Humanized version of the $string
*/
public static function humanize($string)
{
// Redefine vars
$string = (string) $string;
return ucfirst(strtolower(str_replace('_', ' ', $string)));
}
/**
* Returns ordinalize number.
*
* <code>
* // 1 becomes 1st
* echo Inflector::ordinalize(1);
* </code>
*
* @param integer $number Number to ordinalize
* @return string
*/
public static function ordinalize($number)
{
if ( ! is_numeric($number)) {
return $number;
}
if (in_array(($number % 100), range(11, 13))) {
return $number . 'th';
} else {
switch ($number % 10) {
case 1: return $number . 'st'; break;
case 2: return $number . 'nd'; break;
case 3: return $number . 'rd'; break;
default: return $number . 'th'; break;
}
}
}
/**
* Returns the plural version of the given word
*
* <code>
* echo Inflector::pluralize('cat');
* </code>
*
* @param string $word Word to pluralize
* @return string
*/
public static function pluralize($word)
{
$result = (string) $word;
foreach (Inflector::$plural_rules as $rule => $replacement) {
if (preg_match($rule, $result)) {
$result = preg_replace($rule, $replacement, $result);
break;
}
}
return $result;
}
/**
* Returns the singular version of the given word
*
* <code>
* echo Inflector::singularize('cats');
* </code>
*
* @param string $word Word to singularize
* @return string
*/
public static function singularize($word)
{
$result = (string) $word;
foreach (Inflector::$singular_rules as $rule => $replacement) {
if (preg_match($rule, $result)) {
$result = preg_replace($rule, $replacement, $result);
break;
}
}
return $result;
}
}

View File

@@ -0,0 +1,91 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Minify
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Minify html
*
* <code>
* echo Minify::html($buffer);
* </code>
*
* @param string $buffer html
* @return string
*/
public static function html($buffer)
{
return preg_replace('/^\\s+|\\s+$/m', '', $buffer);
}
/**
* Minify css
*
* <code>
* echo Minify::css($buffer);
* </code>
*
* @param string $buffer css
* @return string
*/
public static function css($buffer)
{
// Remove comments
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
// Remove tabs, spaces, newlines, etc.
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
// Preserve empty comment after '>' http://www.webdevout.net/css-hacks#in_css-selectors
$buffer = preg_replace('@>/\\*\\s*\\*/@', '>/*keep*/', $buffer);
// Preserve empty comment between property and value
// http://css-discuss.incutio.com/?page=BoxModelHack
$buffer = preg_replace('@/\\*\\s*\\*/\\s*:@', '/*keep*/:', $buffer);
$buffer = preg_replace('@:\\s*/\\*\\s*\\*/@', ':/*keep*/', $buffer);
// Remove ws around { } and last semicolon in declaration block
$buffer = preg_replace('/\\s*{\\s*/', '{', $buffer);
$buffer = preg_replace('/;?\\s*}\\s*/', '}', $buffer);
// Remove ws surrounding semicolons
$buffer = preg_replace('/\\s*;\\s*/', ';', $buffer);
// Remove ws around urls
$buffer = preg_replace('/url\\(\\s*([^\\)]+?)\\s*\\)/x', 'url($1)', $buffer);
// Remove ws between rules and colons
$buffer = preg_replace('/\\s*([{;])\\s*([\\*_]?[\\w\\-]+)\\s*:\\s*(\\b|[#\'"])/x', '$1$2:$3', $buffer);
// Minimize hex colors
$buffer = preg_replace('/([^=])#([a-f\\d])\\2([a-f\\d])\\3([a-f\\d])\\4([\\s;\\}])/i', '$1#$2$3$4$5', $buffer);
// Replace any ws involving newlines with a single newline
$buffer = preg_replace('/[ \\t]*\\n+\\s*/', "\n", $buffer);
return $buffer;
}
}

View File

@@ -0,0 +1,117 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
/*
* Version number for the current version of the Monstra Library.
*/
define('MONSTRA_LIBRARY_VERSION', '1.0.0');
/*
* Should we use the Monstra Autoloader to ensure the dependancies are automatically
* loaded?
*/
if ( ! defined('MONSTRA_LIBRARY_AUTOLOADER')) {
define('MONSTRA_LIBRARY_AUTOLOADER', true);
}
// Register autoload function
if (MONSTRA_LIBRARY_AUTOLOADER) {
spl_autoload_register(array('Monstra', 'autoload'));
}
/**
* Monstra
*/
class Monstra
{
/**
* Registry of variables
*
* @var array
*/
private static $registry = array();
/**
* Autload
*/
public static function autoload($className)
{
$path = dirname(realpath(__FILE__));
$className = ltrim($className, '\\');
$fileName = '';
$namespace = '';
if ($lastNsPos = strrpos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . '.php';
require $path.DIRECTORY_SEPARATOR.$fileName;
}
/**
* Checks if an object with this name is in the registry.
*
* @return bool
* @param string $name The name of the registry item to check for existence.
*/
public static function exists($name)
{
return isset(self::$registry[(string) $name]);
}
/**
* Registers a given value under a given name.
*
* @param string $name The name of the value to store.
* @param mixed[optional] $value The value that needs to be stored.
*/
public static function set($name, $value = null)
{
// redefine name
$name = (string) $name;
// delete item
if ($value === null) {
unset(self::$registry[$name]);
} else {
self::$registry[$name] = $value;
return self::get($name);
}
}
/**
* Fetch an item from the registry.
*
* @return mixed
* @param string $name The name of the item to fetch.
*/
public static function get($name)
{
$name = (string) $name;
if (!isset(self::$registry[$name])) {
throw new SpoonException('No item "' . $name . '" exists in the registry.');
}
return self::$registry[$name];
}
}

View File

@@ -0,0 +1,138 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Notification
{
/**
* Notifications session key
*
* @var string
*/
const SESSION_KEY = 'notifications';
/**
* Notifications array
*
* @var array
*/
private static $notifications = array();
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Returns a specific variable from the Notifications array.
*
* <code>
* echo Notification::get('success');
* echo Notification::get('errors');
* </code>
*
* @param string $key Variable name
* @return mixed
*/
public static function get($key)
{
// Redefine arguments
$key = (string) $key;
// Return specific variable from the Notifications array
return isset(Notification::$notifications[$key]) ? Notification::$notifications[$key] : null;
}
/**
* Adds specific variable to the Notifications array.
*
* <code>
* Notification::set('success', 'Data has been saved with success!');
* Notification::set('errors', 'Data not saved!');
* </code>
*
* @param string $key Variable name
* @param mixed $value Variable value
*/
public static function set($key, $value)
{
// Redefine arguments
$key = (string) $key;
// Save specific variable to the Notifications array
$_SESSION[Notification::SESSION_KEY][$key] = $value;
}
/**
* Adds specific variable to the Notifications array for current page.
*
* <code>
* Notification::setNow('success', 'Success!');
* </code>
*
* @param string $var Variable name
* @param mixed $value Variable value
*/
public static function setNow($key, $value)
{
// Redefine arguments
$key = (string) $key;
// Save specific variable for current page only
Notification::$notifications[$key] = $value;
}
/**
* Clears the Notifications array.
*
* <code>
* Notification::clean();
* </code>
*
* Data that previous pages stored will not be deleted, just the data that
* this page stored itself.
*/
public static function clean()
{
$_SESSION[Notification::SESSION_KEY] = array();
}
/**
* Initializes the Notification service.
*
* <code>
* Notification::init();
* </code>
*
* This will read notification/flash data from the $_SESSION variable and load it into
* the $this->previous array.
*/
public static function init()
{
// Get notification/flash data...
if ( ! empty($_SESSION[Notification::SESSION_KEY]) && is_array($_SESSION[Notification::SESSION_KEY])) {
Notification::$notifications = $_SESSION[Notification::SESSION_KEY];
}
$_SESSION[Notification::SESSION_KEY] = array();
}
}

View File

@@ -0,0 +1,203 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Number
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Convert bytes in 'kb','mb','gb','tb','pb'
*
* <code>
* echo Number::byteFormat(10000);
* </code>
*
* @param integer $size Data to convert
* @return string
*/
public static function byteFormat($size)
{
// Redefine vars
$size = (int) $size;
$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
return @round($size/pow(1024, ($i=floor(log($size, 1024)))), 2).' '.$unit[$i];
}
/**
* Converts a number into a more readable human-type number.
*
* <code>
* echo Number::quantity(7000); // 7K
* echo Number::quantity(7500); // 8K
* echo Number::quantity(7500, 1); // 7.5K
* </code>
*
* @param integer $num Num to convert
* @param integer $decimals Decimals
* @return string
*/
public static function quantity($num, $decimals = 0)
{
// Redefine vars
$num = (int) $num;
$decimals = (int) $decimals;
if ($num >= 1000 && $num < 1000000) {
return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000)).'K';
} elseif ($num >= 1000000 && $num < 1000000000) {
return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000)).'M';
} elseif ($num >= 1000000000) {
return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000000)).'B';
}
return $num;
}
/**
* Checks if the value is between the minimum and maximum (min & max included).
*
* <code>
* if (Number::between(2, 10, 5)) {
* // do something...
* }
* </code>
*
* @param float $minimum The minimum.
* @param float $maximum The maximum.
* @param float $value The value to validate.
* @return boolean
*/
public static function between($minimum, $maximum, $value)
{
return ((float) $value >= (float) $minimum && (float) $value <= (float) $maximum);
}
/**
* Checks the value for an even number.
*
* <code>
* if (Number::even(2)) {
* // do something...
* }
* </code>
*
* @param integer $value The value to validate.
* @return boolean
*/
public static function even($value)
{
return (((int) $value % 2) == 0);
}
/**
* Checks if the value is greather than a given minimum.
*
* <code>
* if (Number::greaterThan(2, 10)) {
* // do something...
* }
* </code>
*
* @param float $minimum The minimum as a float.
* @param float $value The value to validate.
* @return boolean
*/
public static function greaterThan($minimum, $value)
{
return ((float) $value > (float) $minimum);
}
/**
* Checks if the value is smaller than a given maximum.
*
* <code>
* if (Number::smallerThan(2, 10)) {
* // do something...
* }
* </code>
*
* @param integer $maximum The maximum.
* @param integer $value The value to validate.
* @return boolean
*/
public static function smallerThan($maximum, $value)
{
return ((int) $value < (int) $maximum);
}
/**
* Checks if the value is not greater than or equal a given maximum.
*
* <code>
* if (Number::maximum(2, 10)) {
* // do something...
* }
* </code>
*
* @param integer $maximum The maximum.
* @param integer $value The value to validate.
* @return boolean
*/
public static function maximum($maximum, $value)
{
return ((int) $value <= (int) $maximum);
}
/**
* Checks if the value is greater than or equal to a given minimum.
*
* <code>
* if (Number::minimum(2, 10)) {
* // do something...
* }
* </code>
*
* @param integer $minimum The minimum.
* @param integer $value The value to validate.
* @return boolean
*/
public static function minimum($minimum, $value)
{
return ((int) $value >= (int) $minimum);
}
/**
* Checks the value for an odd number.
*
* <code>
* if (Number::odd(2)) {
* // do something...
* }
* </code>
*
* @param integer $value The value to validate.
* @return boolean
*/
public static function odd($value)
{
return ! Number::even((int) $value);
}
}

1266
libraries/monstra/Orm.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,153 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Request
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Redirects the browser to a page specified by the $url argument.
*
* <code>
* Request::redirect('test');
* </code>
*
* @param string $url The URL
* @param integer $status Status
* @param integer $delay Delay
*/
public static function redirect($url, $status = 302, $delay = null)
{
// Redefine vars
$url = (string) $url;
$status = (int) $status;
// Status codes
$messages = array();
$messages[301] = '301 Moved Permanently';
$messages[302] = '302 Found';
// Is Headers sent ?
if (headers_sent()) {
echo "<script>document.location.href='" . $url . "';</script>\n";
} else {
// Redirect headers
Request::setHeaders('HTTP/1.1 ' . $status . ' ' . Arr::get($messages, $status, 302));
// Delay execution
if ($delay !== null) sleep((int) $delay);
// Redirect
Request::setHeaders("Location: $url");
// Shutdown request
Request::shutdown();
}
}
/**
* Set one or multiple headers.
*
* <code>
* Request::setHeaders('Location: http://site.com/');
* </code>
*
* @param mixed $headers String or array with headers to send.
*/
public static function setHeaders($headers)
{
// Loop elements
foreach ((array) $headers as $header) {
// Set header
header((string) $header);
}
}
/**
* Get
*
* <code>
* $action = Request::get('action');
* </code>
*
* @param string $key Key
* @param mixed
*/
public static function get($key)
{
return Arr::get($_GET, $key);
}
/**
* Post
*
* <code>
* $login = Request::post('login');
* </code>
*
* @param string $key Key
* @param mixed
*/
public static function post($key)
{
return Arr::get($_POST, $key);
}
/**
* Returns whether this is an ajax request or not
*
* <code>
* if (Request::isAjax()) {
* // do something...
* }
* </code>
*
* @return boolean
*/
public static function isAjax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}
/**
* Terminate request
*
* <code>
* Request::shutdown();
* </code>
*
*/
public static function shutdown()
{
exit(0);
}
}

View File

@@ -0,0 +1,101 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Response
{
/**
* HTTP status codes and messages
*
* @var array
*/
public static $messages = array(
// Informational 1xx
100 => 'Continue',
101 => 'Switching Protocols',
// Success 2xx
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
// Redirection 3xx
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found', // 1.1
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
// 306 is deprecated but reserved
307 => 'Temporary Redirect',
// Client Error 4xx
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
// Server Error 5xx
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
509 => 'Bandwidth Limit Exceeded'
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Set header status
*
* <code>
* Response::status(404);
* </code>
*
* @param integer $status Status code
*/
public static function status($status)
{
if (array_key_exists($status, Response::$messages)) header('HTTP/1.1 ' . $status . ' ' . Response::$messages[$status]);
}
}

View File

@@ -0,0 +1,237 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Security
{
/**
* Key name for token storage
*
* @var string
*/
public static $token_name = 'security_token';
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Generate and store a unique token which can be used to help prevent
* [CSRF](http://wikipedia.org/wiki/Cross_Site_Request_Forgery) attacks.
*
* <code>
* $token = Security::token();
* </code>
*
* You can insert this token into your forms as a hidden field:
*
* <code>
* echo Form::hidden('csrf', Security::token());
* </code>
*
* This provides a basic, but effective, method of preventing CSRF attacks.
*
* @param boolean $new force a new token to be generated?. Default is false
* @return string
*/
public static function token($new = false)
{
// Get the current token
$token = Session::get(Security::$token_name);
// Create a new unique token
if ($new === true or ! $token) {
// Generate a new unique token
$token = sha1(uniqid(mt_rand(), true));
// Store the new token
Session::set(Security::$token_name, $token);
}
// Return token
return $token;
}
/**
* Check that the given token matches the currently stored security token.
*
* <code>
* if (Security::check($token)) {
* // Pass
* }
* </code>
*
* @param string $token token to check
* @return boolean
*/
public static function check($token)
{
return Security::token() === $token;
}
/**
* Encrypt password
*
* <code>
* $encrypt_password = Security::encryptPassword('password');
* </code>
*
* @param string $password Password to encrypt
*/
public static function encryptPassword($password)
{
return md5(md5(trim($password) . MONSTRA_PASSWORD_SALT));
}
/**
* Create safe name. Use to create safe username, filename, pagename.
*
* <code>
* $safe_name = Security::safeName('hello world');
* </code>
*
* @param string $str String
* @param string $delimiter String delimiter
* @param boolean $lowercase String Lowercase
* @return string
*/
public static function safeName($str, $delimiter = '-', $lowercase = false)
{
// Redefine vars
$str = (string) $str;
$delimiter = (string) $delimiter;
$lowercase = (bool) $lowercase;
$delimiter = (string) $delimiter;
// Remove tags
$str = filter_var($str, FILTER_SANITIZE_STRING);
// Decode all entities to their simpler forms
$str = html_entity_decode($str, ENT_QUOTES, 'UTF-8');
// Reserved characters (RFC 3986)
$reserved_characters = array(
'/', '?', ':', '@', '#', '[', ']',
'!', '$', '&', '\'', '(', ')', '*',
'+', ',', ';', '='
);
// Remove reserved characters
$str = str_replace($reserved_characters, ' ', $str);
// Set locale to en_US.UTF8
setlocale(LC_ALL, 'en_US.UTF8');
// Translit ua,ru => latin
$str = Text::translitIt($str);
// Convert string
$str = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
// Remove characters
$str = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $str );
$str = preg_replace("/[\/_|+ -]+/", $delimiter, $str );
$str = trim($str, $delimiter);
// Lowercase
if ($lowercase === true) $str = Text::lowercase($str);
// Return safe name
return $str;
}
/**
* Create safe url.
*
* <code>
* $url = Security::sanitizeURL('http://test.com');
* </code>
*
* @param string $url Url to sanitize
* @return string
*/
public static function sanitizeURL($url)
{
$url = trim($url);
$url = rawurldecode($url);
$url = str_replace(array('--','&quot;','!','@','#','$','%','^','*','(',')','+','{','}','|',':','"','<','>',
'[',']','\\',';',"'",',','*','+','~','`','laquo','raquo',']>','&#8216;','&#8217;','&#8220;','&#8221;','&#8211;','&#8212;'),
array('-','-','','','','','','','','','','','','','','','','','','','','','','','','','','',''),
$url);
$url = str_replace('--', '-', $url);
$url = rtrim($url, "-");
$url = str_replace('..', '', $url);
$url = str_replace('//', '', $url);
$url = preg_replace('/^\//', '', $url);
$url = preg_replace('/^\./', '', $url);
return $url;
}
/**
* Sanitize URL to prevent XSS - Cross-site scripting
*/
public static function runSanitizeURL()
{
$_GET = array_map('Security::sanitizeURL', $_GET);
}
/**
* That prevents null characters between ascii characters.
*
* @param string $str String
*/
public static function removeInvisibleCharacters($str)
{
// Redefine vars
$str = (string) $str;
// Thanks to ci for this tip :)
$non_displayables = array('/%0[0-8bcef]/', '/%1[0-9a-f]/', '/[\x00-\x08]/', '/\x0b/', '/\x0c/', '/[\x0e-\x1f]/');
do {
$cleaned = $str;
$str = preg_replace($non_displayables, '', $str);
} while ($cleaned != $str);
// Return safe string
return $str;
}
/**
* Sanitize data to prevent XSS - Cross-site scripting
*
* @param string $str String
*/
public static function xssClean($str)
{
// Remove invisible characters
$str = Security::removeInvisibleCharacters($str);
// Convert html to plain text
$str = Html::toText($str);
// Return safe string
return $str;
}
}

View File

@@ -0,0 +1,187 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Session
{
/**
* Starts the session.
*
* <code>
* Session::start();
* </code>
*
*/
public static function start()
{
// Is session already started?
if ( ! session_id()) {
// Start the session
return @session_start();
}
// If already started
return true;
}
/**
* Deletes one or more session variables.
*
* <code>
* Session::delete('user');
* </code>
*
*/
public static function delete()
{
// Loop all arguments
foreach (func_get_args() as $argument) {
// Array element
if (is_array($argument)) {
// Loop the keys
foreach ($argument as $key) {
// Unset session key
unset($_SESSION[(string) $key]);
}
} else {
// Remove from array
unset($_SESSION[(string) $argument]);
}
}
}
/**
* Destroys the session.
*
* <code>
* Session::destroy();
* </code>
*
*/
public static function destroy()
{
// Destroy
if (session_id()) {
session_unset();
session_destroy();
$_SESSION = array();
}
}
/**
* Checks if a session variable exists.
*
* <code>
* if (Session::exists('user')) {
* // Do something...
* }
* </code>
*
* @return boolean
*/
public static function exists()
{
// Start session if needed
if ( ! session_id()) Session::start();
// Loop all arguments
foreach (func_get_args() as $argument) {
// Array element
if (is_array($argument)) {
// Loop the keys
foreach ($argument as $key) {
// Does NOT exist
if ( ! isset($_SESSION[(string) $key])) return false;
}
} else {
// Does NOT exist
if ( ! isset($_SESSION[(string) $argument])) return false;
}
}
return true;
}
/**
* Gets a variable that was stored in the session.
*
* <code>
* echo Session::get('user');
* </code>
*
* @param string $key The key of the variable to get.
* @return mixed
*/
public static function get($key)
{
// Start session if needed
if ( ! session_id()) self::start();
// Redefine key
$key = (string) $key;
// Fetch key
if (Session::exists((string) $key)) return $_SESSION[(string) $key];
// Key doesn't exist
return null;
}
/**
* Returns the sessionID.
*
* <code>
* echo Session::getSessionId();
* </code>
*
* @return string
*/
public static function getSessionId()
{
if ( ! session_id()) Session::start();
return session_id();
}
/**
* Stores a variable in the session.
*
* <code>
* Session::set('user', 'Awilum');
* </code>
*
* @param string $key The key for the variable.
* @param mixed $value The value to store.
*/
public static function set($key, $value)
{
// Start session if needed
if ( ! session_id()) self::start();
// Set key
$_SESSION[(string) $key] = $value;
}
}

475
libraries/monstra/Text.php Normal file
View File

@@ -0,0 +1,475 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Text
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Translit function ua,ru => latin
*
* <code>
* echo Text::translitIt('Привет');
* </code>
*
* @param string $str [ua,ru] string
* @return string $str
*/
public static function translitIt($str)
{
// Redefine vars
$str = (string) $str;
$patern = array(
"А" => "A", "Б" => "B", "В" => "V", "Г" => "G",
"Д" => "D", "Е" => "E", "Ж" => "J", "З" => "Z",
"И" => "I", "Й" => "Y", "К" => "K", "Л" => "L",
"М" => "M", "Н" => "N", "О" => "O", "П" => "P",
"Р" => "R", "С" => "S", "Т" => "T", "У" => "U",
"Ф" => "F", "Х" => "H", "Ц" => "TS", "Ч" => "CH",
"Ш" => "SH", "Щ" => "SCH", "Ъ" => "", "Ы" => "YI",
"Ь" => "", "Э" => "E", "Ю" => "YU", "Я" => "YA",
"а" => "a", "б" => "b", "в" => "v", "г" => "g",
"д" => "d", "е" => "e", "ж" => "j", "з" => "z",
"и" => "i", "й" => "y", "к" => "k", "л" => "l",
"м" => "m", "н" => "n", "о" => "o","п" => "p",
"р" => "r", "с" => "s", "т" => "t", "у" => "u",
"ф" => "f", "х" => "h", "ц" => "ts", "ч" => "ch",
"ш" => "sh", "щ" => "sch", "ъ" => "y", "ї" => "i",
"Ї" => "Yi", "є" => "ie", "Є" => "Ye", "ы" => "yi",
"ь" => "", "э" => "e", "ю" => "yu", "я" => "ya", "ё" => "yo"
);
return strtr($str, $patern);
}
/**
* Removes any leading and traling slashes from a string
*
* <code>
* echo Text::trimSlashes('some text here/');
* </code>
*
* @param string $str String with slashes
* @return string
*/
public static function trimSlashes($str)
{
// Redefine vars
$str = (string) $str;
return trim($str, '/');
}
/**
* Removes slashes contained in a string or in an array
*
* <code>
* echo Text::strpSlashes('some \ text \ here');
* </code>
*
* @param mixed $str String or array of strings with slashes
* @return mixed
*/
public static function strpSlashes($str)
{
if (is_array($str)) {
foreach ($str as $key => $val) {
$result[$key] = stripslashes($val);
}
} else {
$result = stripslashes($str);
}
return $result;
}
/**
* Removes single and double quotes from a string
*
* <code>
* echo Text::stripQuotes('some "text" here');
* </code>
*
* @param string $str String with single and double quotes
* @return string
*/
public static function stripQuotes($str)
{
// Redefine vars
$str = (string) $str;
return str_replace(array('"', "'"), '', $str);
}
/**
* Convert single and double quotes to entities
*
* <code>
* echo Text::quotesToEntities('some "text" here');
* </code>
*
* @param string $str String with single and double quotes
* @return string
*/
public static function quotesToEntities($str)
{
// Redefine vars
$str = (string) $str;
return str_replace(array("\'", "\"", "'", '"'), array("&#39;", "&quot;", "&#39;", "&quot;"), $str);
}
/**
* Creates a random string of characters
*
* <code>
* echo Text::random();
* </code>
*
* @param string $type The type of string. Default is 'alnum'
* @param integer $length The number of characters. Default is 16
* @return string
*/
public static function random($type = 'alnum', $length = 16)
{
// Redefine vars
$type = (string) $type;
$length = (int) $length;
switch ($type) {
case 'basic':
return mt_rand();
break;
default:
case 'alnum':
case 'numeric':
case 'nozero':
case 'alpha':
case 'distinct':
case 'hexdec':
switch ($type) {
case 'alpha':
$pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
default:
case 'alnum':
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'numeric':
$pool = '0123456789';
break;
case 'nozero':
$pool = '123456789';
break;
case 'distinct':
$pool = '2345679ACDEFHJKLMNPRSTUVWXYZ';
break;
case 'hexdec':
$pool = '0123456789abcdef';
break;
}
$str = '';
for ($i=0; $i < $length; $i++) {
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
return $str;
break;
case 'unique':
return md5(uniqid(mt_rand()));
break;
case 'sha1' :
return sha1(uniqid(mt_rand(), true));
break;
}
}
/**
* Add's _1 to a string or increment the ending number to allow _2, _3, etc
*
* <code>
* $str = Text::increment($str);
* </code>
*
* @param string $str String to increment
* @param integer $first Start with
* @param string $separator Separator
* @return string
*/
public static function increment($str, $first = 1, $separator = '_')
{
preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);
return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
}
/**
* Cut string
*
* <code>
* echo Text::cut('Some text here', 5);
* </code>
*
* @param string $str Input string
* @param integer $length Length after cut
* @param string $cut_msg Message after cut string
* @return string
*/
public static function cut($str, $length, $cut_msg = null)
{
// Redefine vars
$str = (string) $str;
$length = (int) $length;
if (isset($cut_msg)) $msg = $cut_msg; else $msg = '...';
return function_exists('mb_substr') ? mb_substr($str, 0, $length, 'utf-8') . $msg : substr($str, 0, $length) . $msg;
}
/**
* Lowercase
*
* <code>
* echo Text::lowercase('Some text here');
* </code>
*
* @param string $str String
* @return string
*/
public static function lowercase($str)
{
// Redefine vars
$str = (string) $str;
return function_exists('mb_strtolower') ? mb_strtolower($str, 'utf-8') : strtolower($str);
}
/**
* Uppercase
*
* <code>
* echo Text::uppercase('some text here');
* </code>
*
* @param string $str String
* @return string
*/
public static function uppercase($str)
{
// Redefine vars
$str = (string) $str;
return function_exists('mb_strtoupper') ? mb_strtoupper($str, 'utf-8') : strtoupper($str);
}
/**
* Get length
*
* <code>
* echo Text::length('Some text here');
* </code>
*
* @param string $str String
* @return string
*/
public static function length($str)
{
// Redefine vars
$str = (string) $str;
return function_exists('mb_strlen') ? mb_strlen($str, 'utf-8') : strlen($str);
}
/**
* Create a lorem ipsum text
*
* <code>
* echo Text::lorem(2);
* </code>
*
* @param integer $num Count
* @return string
*/
public static function lorem($num = 1)
{
// Redefine vars
$num = (int) $num;
return str_repeat('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', (int) $num);
}
/**
* Extract the last `$num` characters from a string.
*
* <code>
* echo Text::right('Some text here', 4);
* </code>
*
* @param string $str The string to extract the characters from.
* @param integer $num The number of characters to extract.
* @return string
*/
public static function right($str, $num)
{
// Redefine vars
$str = (string) $str;
$num = (int) $num;
return substr($str, Text::length($str)-$num, $num);
}
/**
* Extract the first `$num` characters from a string.
*
* <code>
* echo Text::left('Some text here', 4);
* </code>
*
* @param string $str The string to extract the characters from.
* @param integer $num The number of characters to extract.
* @return string
*/
public static function left($str, $num)
{
// Redefine vars
$str = (string) $str;
$num = (int) $num;
return substr($str, 0, $num);
}
/**
* Replaces newline with <br> or <br />.
*
* <code>
* echo Text::nl2br("Some \n text \n here");
* </code>
*
* @param string $str The input string
* @param boolean $xhtml Xhtml or not
* @return string
*/
public static function nl2br($str, $xhtml = true)
{
// Redefine vars
$str = (string) $str;
$xhtml = (bool) $xhtml;
return str_replace(array("\r\n", "\n\r", "\n", "\r"), (($xhtml) ? '<br />' : '<br>'), $str);
}
/**
* Replaces <br> and <br /> with newline.
*
* <code>
* echo Text::br2nl("Some <br /> text <br /> here");
* </code>
*
* @param string $str The input string
* @return string
*/
public static function br2nl($str)
{
// Redefine vars
$str = (string) $str;
return str_replace(array('<br>', '<br/>', '<br />'), "\n", $str);
}
/**
* Converts & to &amp;.
*
* <code>
* echo Text::ampEncode("M&CMS");
* </code>
*
* @param string $str The input string
* @return string
*/
public static function ampEncode($str)
{
// Redefine vars
$str = (string) $str;
return str_replace('&', '&amp;', $str);
}
/**
* Converts &amp; to &.
*
* <code>
* echo Text::ampEncode("M&amp;CMS");
* </code>
*
* @param string $str The input string
* @return string
*/
public static function ampDecode($str)
{
// Redefine vars
$str = (string) $str;
return str_replace('&amp;', '&', $str);
}
/**
* Convert plain text to html
*
* <code>
* echo Text::toHtml('test');
* </code>
*
* @param string $str String
* @return string
*/
public static function toHtml($str)
{
// Redefine vars
$str = (string) $str;
return html_entity_decode($str, ENT_QUOTES, 'utf-8');
}
}

107
libraries/monstra/Url.php Normal file
View File

@@ -0,0 +1,107 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Url
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Takes a long url and uses the TinyURL API to return a shortened version.
*
* <code>
* echo Url::tiny('http:://sitename.com');
* </code>
*
* @param string $url Long url
* @return string
*/
public static function tiny($url)
{
return file_get_contents('http://tinyurl.com/api-create.php?url='.(string) $url);
}
/**
* Check is url exists
*
* <code>
* if (Url::exists('http:://sitename.com')) {
* // Do something...
* }
* </code>
*
* @param string $url Url
* @return boolean
*/
public static function exists($url)
{
$a_url = parse_url($url);
if ( ! isset($a_url['port'])) $a_url['port'] = 80;
$errno = 0;
$errstr = '';
$timeout = 30;
if (isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])) {
$fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout);
if ( ! $fid) return false;
$page = isset($a_url['path']) ? $a_url['path'] : '';
$page .= isset($a_url['query']) ? '?'.$a_url['query'] : '';
fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n");
$head = fread($fid, 4096);
fclose($fid);
return preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head);
} else {
return false;
}
}
/**
* Gets the base URL
*
* <code>
* echo Url::base();
* </code>
*
* @return string
*/
public static function base()
{
$https = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') ? 'https://' : 'http://';
return $https . rtrim(rtrim($_SERVER['HTTP_HOST'], '\\/') . dirname($_SERVER['PHP_SELF']), '\\/');
}
/**
* Gets current URL
*
* <code>
* echo Url::current();
* </code>
*
* @return string
*/
public static function current()
{
return (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
}
}

207
libraries/monstra/Valid.php Normal file
View File

@@ -0,0 +1,207 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Valid
{
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct()
{
// Nothing here
}
/**
* Check an email address for correct format.
*
* <code>
* if (Valid::email('test@test.com')) {
* // Do something...
* }
* </code>
*
* @param string $email email address
* @return boolean
*/
public static function email($email)
{
return (bool) filter_var((string) $email, FILTER_VALIDATE_EMAIL);
}
/**
* Check an ip address for correct format.
*
* <code>
* if (Valid::ip('127.0.0.1') || Valid::ip('0:0:0:0:0:0:7f00:1')) {
* // Do something...
* }
* </code>
*
* @param string $ip ip address
* @return boolean
*/
public static function ip($ip)
{
return (bool) filter_var((string) $ip, FILTER_VALIDATE_IP);
}
/**
* Check an credit card for correct format.
*
* <code>
* if (Valid::creditCard(7711111111111111, 'Visa')) {
* // Do something...
* }
* </code>
*
* @param integer $num Credit card num
* @param string $type Credit card type:
* American - American Express
* Dinners - Diner's Club
* Discover - Discover Card
* Master - Mastercard
* Visa - Visa
* @return boolean
*/
public static function creditCard($num, $type)
{
// Redefine vars
$num = (int) $num;
$type = (string) $type;
switch ($type) {
case "American": return (bool) preg_match("/^([34|37]{2})([0-9]{13})$/", $num);
case "Dinners": return (bool) preg_match("/^([30|36|38]{2})([0-9]{12})$/", $num);
case "Discover": return (bool) preg_match("/^([6011]{4})([0-9]{12})$/", $num);
case "Master": return (bool) preg_match("/^([51|52|53|54|55]{2})([0-9]{14})$/", $num);
case "Visa": return (bool) preg_match("/^([4]{1})([0-9]{12,15})$/", $num);
}
}
/**
* Check an phone number for correct format.
*
* <code>
* if (Valid::phone(0661111117)) {
* // Do something...
* }
* </code>
*
* @param string $num Phone number
* @return boolean
*/
public static function phone($num)
{
return (bool) preg_match("/^([0-9\(\)\/\+ \-]*)$/", (string) $num);
}
/**
* Check an url for correct format.
*
* <code>
* if (Valid::url('http://site.com/')) {
* // Do something...
* }
* </code>
*
* @param string $url Url
* @return boolean
*/
public static function url($url)
{
return (bool) filter_var((string) $url, FILTER_VALIDATE_URL);
}
/**
* Check an date for correct format.
*
* <code>
* if (Valid::date('12/12/12')) {
* // Do something...
* }
* </code>
*
* @param string $str Date
* @return boolean
*/
public static function date($str)
{
return (strtotime($str) !== false);
}
/**
* Checks whether a string consists of digits only (no dots or dashes).
*
* <code>
* if (Valid::digit('12')) {
* // Do something...
* }
* </code>
*
* @param string $str String
* @return boolean
*/
public static function digit($str)
{
return (bool) preg_match ("/[^0-9]/", $str);
}
/**
* Checks whether a string is a valid number (negative and decimal numbers allowed).
*
* <code>
* if (Valid::numeric('3.14')) {
* // Do something...
* }
* </code>
*
* Uses {@link http://www.php.net/manual/en/function.localeconv.php locale conversion}
* to allow decimal point to be locale specific.
*
* @param string $str String
* @return boolean
*/
public static function numeric($str)
{
$locale = localeconv();
return (bool) preg_match('/^-?[0-9'.$locale['decimal_point'].']++$/D', (string) $str);
}
/**
* Checks if the given regex statement is valid.
*
* @param string $regexp The value to validate.
* @return boolean
*/
public static function regexp($regexp)
{
// dummy string
$dummy = 'Monstra - fast and simple PHP library';
// validate
return (@preg_match((string) $regexp, $dummy) !== false);
}
}

373
libraries/monstra/Zip.php Normal file
View File

@@ -0,0 +1,373 @@
<?php
/**
* Monstra Library
*
* This source file is part of the Monstra Library. More information,
* documentation and tutorials can be found at http://library.monstra.org
*
* @package Monstra
*
* @author Romanenko Sergey / Awilum
* @copyright (c) 2012 - 2013 Romanenko Sergey / Awilum
* @since 1.0.0
*/
class Zip
{
public $zipdata = '';
public $directory = '';
public $entries = 0;
public $file_num = 0;
public $offset = 0;
public $now;
/**
* Constructor
*/
public function __construct()
{
$this->now = time();
}
/**
* Zip factory
*
* <code>
* Zip::factory();
* </code>
*
* @return Zip
*/
public static function factory()
{
return new Zip();
}
/**
* Add Directory
*
* <code>
* Zip::factory()->addDir('test');
* </code>
*
* @param mixed $directory The directory name. Can be string or array
*/
public function addDir($directory)
{
foreach ((array) $directory as $dir) {
if ( ! preg_match("|.+/$|", $dir)) {
$dir .= '/';
}
$dir_time = $this->_get_mod_time($dir);
$this->_add_dir($dir, $dir_time['file_mtime'], $dir_time['file_mdate']);
}
return $this;
}
/**
* Get file/directory modification time
*
* @param string $dir Full path to the dir
* @return array
*/
protected function _get_mod_time($dir)
{
// If this is a newly created file/dir, we will set the time to 'now'
$date = (@filemtime($dir)) ? filemtime($dir) : getdate($this->now);
$time['file_mtime'] = ($date['hours'] << 11) + ($date['minutes'] << 5) + $date['seconds'] / 2;
$time['file_mdate'] = (($date['year'] - 1980) << 9) + ($date['mon'] << 5) + $date['mday'];
return $time;
}
/**
* Add Directory
*
* @param string $dir The directory name
* @param integer $file_mtime File mtime
* @param integer $file_mdate File mdate
*/
private function _add_dir($dir, $file_mtime, $file_mdate)
{
$dir = str_replace("\\", "/", $dir);
$this->zipdata .=
"\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V', 0) // crc32
.pack('V', 0) // compressed filesize
.pack('V', 0) // uncompressed filesize
.pack('v', strlen($dir)) // length of pathname
.pack('v', 0) // extra field length
.$dir
// below is "data descriptor" segment
.pack('V', 0) // crc32
.pack('V', 0) // compressed filesize
.pack('V', 0); // uncompressed filesize
$this->directory .=
"\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V',0) // crc32
.pack('V',0) // compressed filesize
.pack('V',0) // uncompressed filesize
.pack('v', strlen($dir)) // length of pathname
.pack('v', 0) // extra field length
.pack('v', 0) // file comment length
.pack('v', 0) // disk number start
.pack('v', 0) // internal file attributes
.pack('V', 16) // external file attributes - 'directory' bit set
.pack('V', $this->offset) // relative offset of local header
.$dir;
$this->offset = strlen($this->zipdata);
$this->entries++;
}
/**
* Add Data to Zip
*
* <code>
* Zip::factory()->addData('test.txt', 'Some test text here');
* </code>
*
* Lets you add files to the archive. If the path is included
* in the filename it will be placed within a directory. Make
* sure you use add_dir() first to create the folder.
*
* @param mixed $filepath Full path to the file
* @param string $data Data
*/
public function addData($filepath, $data = null)
{
if (is_array($filepath)) {
foreach ($filepath as $path => $data) {
$file_data = $this->_get_mod_time($path);
$this->_add_data($path, $data, $file_data['file_mtime'], $file_data['file_mdate']);
}
} else {
$file_data = $this->_get_mod_time($filepath);
$this->_add_data($filepath, $data, $file_data['file_mtime'], $file_data['file_mdate']);
}
return $this;
}
/**
* Add Data to Zip
*
* @param string $filepath Full path to the file
* @param string $data The data to be encoded
* @param integer $file_mtime File mtime
* @param integer $file_mdate File mdate
*/
private function _add_data($filepath, $data, $file_mtime, $file_mdate)
{
$filepath = str_replace("\\", "/", $filepath);
$uncompressed_size = strlen($data);
$crc32 = crc32($data);
$gzdata = gzcompress($data);
$gzdata = substr($gzdata, 2, -4);
$compressed_size = strlen($gzdata);
$this->zipdata .=
"\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V', $crc32)
.pack('V', $compressed_size)
.pack('V', $uncompressed_size)
.pack('v', strlen($filepath)) // length of filename
.pack('v', 0) // extra field length
.$filepath
.$gzdata; // "file data" segment
$this->directory .=
"\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V', $crc32)
.pack('V', $compressed_size)
.pack('V', $uncompressed_size)
.pack('v', strlen($filepath)) // length of filename
.pack('v', 0) // extra field length
.pack('v', 0) // file comment length
.pack('v', 0) // disk number start
.pack('v', 0) // internal file attributes
.pack('V', 32) // external file attributes - 'archive' bit set
.pack('V', $this->offset) // relative offset of local header
.$filepath;
$this->offset = strlen($this->zipdata);
$this->entries++;
$this->file_num++;
}
/**
* Read the contents of a file and add it to the zip
*
* <code>
* Zip::factory()->readFile('test.txt');
* </code>
*
* @param string $path Path
* @param boolean $preserve_filepath Preserve filepath
* @return mixed
*/
public function readFile($path, $preserve_filepath = false)
{
if ( ! file_exists($path)) {
return false;
}
if (false !== ($data = file_get_contents($path))) {
$name = str_replace("\\", "/", $path);
if ($preserve_filepath === false) {
$name = preg_replace("|.*/(.+)|", "\\1", $name);
}
$this->addData($name, $data);
return $this;
}
return false;
}
/**
* Read a directory and add it to the zip.
*
* <code>
* Zip::factory()->readDir('test/');
* </code>
*
* This function recursively reads a folder and everything it contains (including
* sub-folders) and creates a zip based on it. Whatever directory structure
* is in the original file path will be recreated in the zip file.
*
* @param string $path Path to source
* @param boolean $preserve_filepath Preserve filepath
* @param string $root_path Root path
* @return mixed
*/
public function readDir($path, $preserve_filepath = true, $root_path = null)
{
if ( ! $fp = @opendir($path)) {
return false;
}
// Set the original directory root for child dir's to use as relative
if ($root_path === null) {
$root_path = dirname($path) . '/';
}
while (false !== ($file = readdir($fp))) {
if (substr($file, 0, 1) == '.') {
continue;
}
if (@is_dir($path.$file)) {
$this->readDir($path.$file."/", $preserve_filepath, $root_path);
} else {
if (false !== ($data = file_get_contents($path.$file))) {
$name = str_replace("\\", "/", $path);
if ($preserve_filepath === false) {
$name = str_replace($root_path, '', $name);
}
$this->addData($name.$file, $data);
}
}
}
return $this;
}
/**
* Get the Zip file
*
* <code>
* Zip::factory()->getZip();
* </code>
*
* @return string
*/
public function getZip()
{
// Is there any data to return?
if ($this->entries == 0) {
return false;
}
$zip_data = $this->zipdata;
$zip_data .= $this->directory."\x50\x4b\x05\x06\x00\x00\x00\x00";
$zip_data .= pack('v', $this->entries); // total # of entries "on this disk"
$zip_data .= pack('v', $this->entries); // total # of entries overall
$zip_data .= pack('V', strlen($this->directory)); // size of central dir
$zip_data .= pack('V', strlen($this->zipdata)); // offset to start of central dir
$zip_data .= "\x00\x00"; // .zip file comment length
return $zip_data;
}
/**
* Write File to the specified directory
*
* <code>
* Zip::factory()->readDir('test1/')->readDir('test2/')->archive('test.zip');
* </code>
*
* @param string $filepath The file name
* @return boolean
*/
public function archive($filepath)
{
if ( ! ($fp = @fopen($filepath, "w"))) {
return false;
}
flock($fp, LOCK_EX);
fwrite($fp, $this->getZip());
flock($fp, LOCK_UN);
fclose($fp);
return true;
}
/**
* Initialize Data
*
* <code>
* Zip::factory()->clearData();
* </code>
*
* Lets you clear current zip data. Useful if you need to create
* multiple zips with different data.
*/
public function clearData()
{
$this->zipdata = '';
$this->directory = '';
$this->entries = 0;
$this->file_num = 0;
$this->offset = 0;
}
}

View File

@@ -1,7 +0,0 @@
<?php
/**
* Set meta generator
*/
Action::add('theme_meta', 'setMetaGenerator');
function setMetaGenerator() { echo '<meta name="generator" content="Powered by Monstra '.Core::VERSION.'" />'; }

View File

@@ -1,117 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra CMS Defines
*/
/**
* The filesystem path to the 'monstra' folder
*/
define('MONSTRA', ROOT . DS . 'monstra');
/**
* The filesystem path to the site 'themes' folder
*/
define('THEMES_SITE', ROOT . DS . 'public' . DS . 'themes');
/**
* The filesystem path to the admin 'themes' folder
*/
define('THEMES_ADMIN', ROOT . DS . 'admin' . DS . 'themes');
/**
* The filesystem path to the 'plugins' folder
*/
define('PLUGINS', ROOT . DS . 'plugins');
/**
* The filesystem path to the 'box' folder which is contained within
* the 'plugins' folder
*/
define('PLUGINS_BOX', PLUGINS . DS . 'box');
/**
* The filesystem path to the 'helpers' folder which is contained within
* the 'monstra' folder
*/
define('HELPERS', MONSTRA . DS . 'helpers');
/**
* The filesystem path to the 'engine' folder which is contained within
* the 'monstra' folder
*/
define('ENGINE', MONSTRA . DS . 'engine');
/**
* The filesystem path to the 'boot' folder which is contained within
* the 'monstra' folder
*/
define('BOOT', MONSTRA . DS . 'boot');
/**
* The filesystem path to the 'storage' folder
*/
define('STORAGE', ROOT . DS . 'storage');
/**
* The filesystem path to the 'xmldb' folder
*/
define('XMLDB', STORAGE . DS . 'database');
/**
* The filesystem path to the 'cache' folder
*/
define('CACHE', ROOT . DS . 'tmp' . DS . 'cache');
/**
* The filesystem path to the 'minify' folder
*/
define('MINIFY', ROOT . DS . 'tmp' . DS . 'minify');
/**
* The filesystem path to the 'logs' folder
*/
define('LOGS', ROOT . DS . 'tmp' . DS . 'logs');
/**
* The filesystem path to the 'assets' folder
*/
define('ASSETS', ROOT . DS . 'public' . DS . 'assets');
/**
* The filesystem path to the 'uploads' folder
*/
define('UPLOADS', ROOT . DS . 'public' . DS . 'uploads');
/**
* Set password salt
*/
define('MONSTRA_PASSWORD_SALT', 'YOUR_SALT_HERE');
/**
* Set date format
*/
define('MONSTRA_DATE_FORMAT', 'Y-m-d / H:i:s');
/**
* Set eval php
*/
define('MONSTRA_EVAL_PHP', false);
/**
* Check Monstra CMS version
*/
define('CHECK_MONSTRA_VERSION', true);
/**
* Set gzip output
*/
define('MONSTRA_GZIP', false);
/**
* Monstra database settings
*/
//define('MONSTRA_DB_DSN', 'mysql:dbname=monstra;host=localhost;port=3306');
//define('MONSTRA_DB_USER', 'root');
//define('MONSTRA_DB_PASSWORD', 'password');

View File

@@ -1,21 +0,0 @@
<?php
/**
* Evaluate a string as PHP code
*/
if (MONSTRA_EVAL_PHP) Filter::add('content', 'evalPHP');
function obEval($mathes) {
ob_start();
eval($mathes[1]);
$mathes = ob_get_contents();
ob_end_clean();
return $mathes;
}
function evalPHP($str) { return preg_replace_callback('/\[php\](.*?)\[\/php\]/ms','obEval', $str); }
/**
* Add shortcode parser filter
*/
Filter::add('content', 'Shortcode::parse', 11);

View File

@@ -1,8 +0,0 @@
<?php
/**
* Add new shortcode {siteurl}
*/
Shortcode::add('siteurl', 'returnSiteUrl');
function returnSiteUrl() { return Option::get('siteurl'); }

View File

@@ -1,503 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Main Monstra engine module. Core module.
*
* Monstra - Content Management System.
* Site: mostra.org
* Copyright (C) 2012 Romanenko Sergey / Awilum [awilum@msn.com]
*
* @package Monstra
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
*/
class Core {
/**
* An instance of the Core class
*
* @var core
*/
protected static $instance = null;
/**
* Common environment type constants for consistency and convenience
*/
const PRODUCTION = 1;
const STAGING = 2;
const TESTING = 3;
const DEVELOPMENT = 4;
/**
* The version of Monstra
*/
const VERSION = '2.1.3';
/**
* Monstra environment
*
* @var string
*/
public static $environment = Core::PRODUCTION;
/**
* Protected clone method to enforce singleton behavior.
*
* @access protected
*/
protected function __clone() {
// Nothing here.
}
/**
* Construct
*/
protected function __construct() {
// Load core defines
Core::loadDefines();
/**
* Compress HTML with gzip
*/
if (MONSTRA_GZIP) {
if ( ! ob_start("ob_gzhandler")) ob_start();
} else {
ob_start();
}
/**
* Send default header and set internal encoding
*/
header('Content-Type: text/html; charset=UTF-8');
function_exists('mb_language') AND mb_language('uni');
function_exists('mb_regex_encoding') AND mb_regex_encoding('UTF-8');
function_exists('mb_internal_encoding') AND mb_internal_encoding('UTF-8');
/**
* Gets the current configuration setting of magic_quotes_gpc
* and kill magic quotes
*/
if (get_magic_quotes_gpc()) {
function stripslashesGPC(&$value) { $value = stripslashes($value); }
array_walk_recursive($_GET, 'stripslashesGPC');
array_walk_recursive($_POST, 'stripslashesGPC');
array_walk_recursive($_COOKIE, 'stripslashesGPC');
array_walk_recursive($_REQUEST, 'stripslashesGPC');
}
// Error handling for Developers only.
if (Core::$environment != Core::PRODUCTION) {
// Set error handler
set_error_handler('Core::errorHandler');
// Set fatal error handler
register_shutdown_function('Core::fatalErrorHandler');
// Set exception handler
set_exception_handler('Core::exceptionHandler');
}
// Register autoload function
spl_autoload_register('Core::autoloadHelpers');
// Start session
Session::start();
// Init ORM
if (defined('MONSTRA_DB_DSN')) {
ORM::configure(MONSTRA_DB_DSN);
ORM::configure('username', MONSTRA_DB_USER);
ORM::configure('password', MONSTRA_DB_PASSWORD);
}
// Auto cleanup if MONSTRA_DEBUG is true
if (Core::$environment == Core::DEVELOPMENT) {
// Cleanup minify
if (count($files = File::scan(MINIFY, array('css', 'js', 'php'))) > 0) foreach ($files as $file) File::delete(MINIFY . DS . $file);
// Cleanup cache
if (count($namespaces = Dir::scan(CACHE)) > 0) foreach ($namespaces as $namespace) Dir::delete(CACHE . DS . $namespace);
}
// Load XMLDB API module
require_once(ENGINE . DS . 'xmldb.php');
// Load Options API module
require_once(ENGINE . DS . 'options.php');
// Init Options API module
Option::init();
// Set default timezone
@ini_set('date.timezone', Option::get('timezone'));
if (function_exists('date_default_timezone_set')) date_default_timezone_set(Option::get('timezone')); else putenv('TZ='.Option::get('timezone'));
// Sanitize URL to prevent XSS - Cross-site scripting
Security::runSanitizeURL();
// Load Plugins API module
require_once(ENGINE . DS . 'plugins.php');
// Load Shortcodes API module
require_once(ENGINE . DS . 'shortcodes.php');
// Load default
Core::loadPluggable();
// Init I18n
I18n::init(Option::get('language'));
// Init Plugins API
Plugin::init();
// Init Notification service
Notification::init();
// Load Site module
require_once(ENGINE . DS . 'site.php');
// Init site module
if( ! BACKEND) Site::init();
}
/**
* Autoload helpers
*
* @param string $class_name Class name
*/
protected static function autoloadHelpers($class_name) {
if (file_exists($path = HELPERS . DS . strtolower($class_name) . '.php')) include $path;
}
/**
* Load Defines
*/
protected static function loadDefines() {
$environments = array(1 => 'production',
2 => 'staging',
3 => 'testing',
4 => 'development');
$root_defines = ROOT . DS . 'boot' . DS . 'defines.php';
$environment_defines = ROOT . DS . 'boot' . DS . $environments[Core::$environment] . DS . 'defines.php';
$monstra_defines = ROOT . DS . 'monstra' . DS . 'boot' . DS . 'defines.php';
if (file_exists($root_defines)) {
include $root_defines;
} elseif(file_exists($environment_defines)) {
include $environment_defines;
} elseif(file_exists($monstra_defines)) {
include $monstra_defines;
} else {
throw new RuntimeException("The defines file does not exist.");
}
}
/**
* Load Pluggable
*/
protected static function loadPluggable() {
$environments = array(1 => 'production',
2 => 'staging',
3 => 'testing',
4 => 'development');
$root_pluggable = ROOT . DS . 'boot';
$environment_pluggable = ROOT . DS . 'boot' . DS . $environments[Core::$environment];
$monstra_pluggable = ROOT . DS . 'monstra' . DS . 'boot';
if (file_exists($root_pluggable . DS . 'filters.php')) {
include $root_pluggable . DS . 'filters.php';
} elseif(file_exists($environment_pluggable . DS . 'filters.php')) {
include $environment_pluggable . DS . 'filters.php';
} elseif(file_exists($monstra_pluggable . DS . 'filters.php')) {
include $monstra_pluggable . DS . 'filters.php';
} else {
throw new RuntimeException("The pluggable file does not exist.");
}
if (file_exists($root_pluggable . DS . 'actions.php')) {
include $root_pluggable . DS . 'actions.php';
} elseif(file_exists($environment_pluggable . DS . 'actions.php')) {
include $environment_pluggable . DS . 'actions.php';
} elseif(file_exists($monstra_pluggable . DS . 'actions.php')) {
include $monstra_pluggable . DS . 'actions.php';
} else {
throw new RuntimeException("The pluggable file does not exist.");
}
if (file_exists($root_pluggable . DS . 'shortcodes.php')) {
include $root_pluggable . DS . 'shortcodes.php';
} elseif(file_exists($environment_pluggable . DS . 'shortcodes.php')) {
include $environment_pluggable . DS . 'shortcodes.php';
} elseif(file_exists($monstra_pluggable . DS . 'shortcodes.php')) {
include $monstra_pluggable . DS . 'shortcodes.php';
} else {
throw new RuntimeException("The pluggable file does not exist.");
}
}
/**
* Exception Handler
*
* @param object $exception An exception object
*/
public static function exceptionHandler($exception) {
// Empty output buffers
while (ob_get_level() > 0) ob_end_clean();
// Send headers and output
@header('Content-Type: text/html; charset=UTF-8');
@header('HTTP/1.1 500 Internal Server Error');
// Get highlighted code
$code = Core::highlightCode($exception->getFile(), $exception->getLine());
// Determine error type
if ($exception instanceof ErrorException) {
$error_type = 'ErrorException: ';
$codes = array (
E_ERROR => 'Fatal Error',
E_PARSE => 'Parse Error',
E_COMPILE_ERROR => 'Compile Error',
E_COMPILE_WARNING => 'Compile Warning',
E_STRICT => 'Strict Mode Error',
E_NOTICE => 'Notice',
E_WARNING => 'Warning',
E_RECOVERABLE_ERROR => 'Recoverable Error',
/*E_DEPRECATED => 'Deprecated',*/ /* PHP 5.3 */
E_USER_NOTICE => 'Notice',
E_USER_WARNING => 'Warning',
E_USER_ERROR => 'Error',
/*E_USER_DEPRECATED => 'Deprecated'*/ /* PHP 5.3 */
);
$error_type .= in_array($exception->getCode(), array_keys($codes)) ? $codes[$exception->getCode()] : 'Unknown Error';
} else {
$error_type = get_class($exception);
}
// Show exception if core environment is DEVELOPMENT
if (Core::$environment == Core::DEVELOPMENT) {
// Development
echo ("
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Monstra</title>
<style>
* { margin: 0; padding: 0; }
body { background-color: #EEE; }
h1,h2,h3,p{font-family:Verdana;font-weight:lighter;margin:10px;}
.exception {border: 1px solid #CCC; padding: 10px; background-color: #FFF; color: #333; margin:10px;}
pre, .code {font-family: Courier, monospace; font-size:12px;margin:0px;padding:0px;}
.highlighted {background-color: #f0eb96; font-weight: bold; border-top: 1px solid #ccc; border-bottom: 1px solid #ccc;}
.code {background:#fff;border:1px solid #ccc;overflow:auto;}
.line {display: inline-block; background-color: #EFEFEF; padding: 4px 8px 4px 8px; margin-right:10px; }
</style>
</head>
<body>
<div class='exception'>
<h1>Monstra - ".$error_type."</h1>
<p>".$exception->getMessage()."</p>
<h2>Location</h2>
<p>Exception thrown on line <code>".$exception->getLine()."</code> in <code>".$exception->getFile()."</code></p>
");
if ( ! empty($code)) {
echo '<div class="code">';
foreach ($code as $line) {
echo '<pre '; if ($line['highlighted']) { echo 'class="highlighted"'; } echo '><span class="line">' . $line['number'] . '</span>' . $line['code'] . '</pre>';
}
echo '</div>';
}
echo '</div></body></html>';
} else {
// Production
echo ("
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Monstra</title>
<style>
* { margin: 0; padding: 0; }
.exception {border: 1px solid #CCC; padding: 10px; background-color: #FFF; color: #333; margin:10px;}
body { background-color: #EEE; font-family: sans-serif; font-size: 16px; line-height: 20px; margin: 40px; }
h1,h2,h3,p{font-family:Verdana;font-weight:lighter;margin:10px;}
</style>
</head>
<body>
<div class='exception'>
<h1>Oops!</h1>
<p>An unexpected error has occurred.</p>
</div>
</body>
</html>
");
}
// Writes message to log
@file_put_contents(LOGS . DS . gmdate('Y_m_d') . '.log',
gmdate('Y/m/d H:i:s') . ' --- ' . '['.$error_type.']' . ' --- ' . $exception->getMessage() . ' --- ' . 'Exception thrown on line '.$exception->getLine().' in '.$exception->getFile() . "\n",
FILE_APPEND);
exit(1);
}
/**
* Converts errors to ErrorExceptions.
*
* @param integer $code The error code
* @param string $message The error message
* @param string $file The filename where the error occurred
* @param integer $line The line number where the error occurred
* @return boolean
*/
public static function errorHandler($code, $message, $file, $line) {
// If isset error_reporting and $code then throw new error exception
if ((error_reporting() & $code) !== 0) {
throw new ErrorException($message, $code, 0, $file, $line);
}
// Don't execute PHP internal error handler
return true;
}
/**
* Returns an array of lines from a file.
*
* @param string $file File in which you want to highlight a line
* @param integer $line Line number to highlight
* @param integer $padding Number of padding lines
* @return array
*/
protected static function highlightCode($file, $line, $padding = 5) {
// Is file readable ?
if ( ! is_readable($file)) {
return false;
}
// Init vars
$lines = array();
$current_line = 0;
// Open file
$handle = fopen($file, 'r');
// Read file
while ( ! feof($handle)) {
$current_line++;
$temp = fgets($handle);
if ($current_line > $line + $padding) {
break; // Exit loop after we have found what we were looking for
}
if ($current_line >= ($line - $padding) && $current_line <= ($line + $padding)) {
$lines[] = array (
'number' => str_pad($current_line, 4, ' ', STR_PAD_LEFT),
'highlighted' => ($current_line === $line),
'code' => Core::highlightString($temp),
);
}
}
// Close
fclose($handle);
// Return lines
return $lines;
}
/**
* Highlight string
*
* @param string $string String
* @return string
*/
protected static function highlightString($string) {
return str_replace(array("\n", '<code>', '</code>', '<span style="color: #0000BB">&lt;?php&nbsp;', '#$@r4!/*'),
array('', '', '', '<span style="color: #0000BB">', '/*'),
highlight_string('<?php ' . str_replace('/*', '#$@r4!/*', $string), true));
}
/**
* Convert errors not caught by the errorHandler to ErrorExceptions.
*/
public static function fatalErrorHandler() {
// Get last error
$error = error_get_last();
// If isset error then throw new error exception
if (isset($error) && ($error['type'] === E_ERROR)) {
Core::exceptionHandler(new ErrorException($error['message'], $error['type'], 0, $error['file'], $error['line']));
exit(1);
}
}
/**
* Initialize Monstra engine
*
* @return Core
*/
public static function init() {
if ( ! isset(self::$instance)) self::$instance = new Core();
return self::$instance;
}
}

View File

@@ -1,189 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra Options API module
*
* @package Monstra
* @subpackage Engine
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Option {
/**
* Options
*
* @var array
*/
protected static $options = null;
/**
* An instance of the Option class
*
* @var option
*/
protected static $instance = null;
/**
* Initializing options
*
* @param string $name Options file
*/
public static function init(){
if ( ! isset(self::$instance)) self::$instance = new Option();
return self::$instance;
}
/**
* Protected clone method to enforce singleton behavior.
*
* @access protected
*/
protected function __clone() {
// Nothing here.
}
/**
* Construct
*/
protected function __construct() {
Option::$options = new Table('options');
}
/**
* Add a new option
*
* <code>
* Option::add('pages_limit', 10);
* Option::add(array('pages_count' => 10, 'pages_default' => 'home'));
* </code>
*
* @param mixed $option Name of option to add.
* @param mixed $value Option value.
* @return boolean
*/
public static function add($option, $value = null) {
if (is_array($option)) {
foreach ($option as $k => $v) {
$_option = Option::$options->select('[name="'.$k.'"]', null);
if (count($_option) == 0) {
Option::$options->insert(array('name' => $k, 'value' => $v));
}
}
} else {
$_option = Option::$options->select('[name="'.$option.'"]', null);
if (count($_option) == 0) {
return Option::$options->insert(array('name' => $option, 'value' => $value));
}
}
}
/**
* Update option value
*
* <code>
* Option::update('pages_limit', 12);
* Option::update(array('pages_count' => 10, 'pages_default' => 'home'));
* </code>
*
* @param mixed $option Name of option to update.
* @param mixed $value Option value.
* @return boolean
*/
public static function update($option, $value = null) {
if (is_array($option)) {
foreach ($option as $k => $v) {
Option::$options->updateWhere('[name="'.$k.'"]', array('value' => $v));
}
} else {
return Option::$options->updateWhere('[name="'.$option.'"]', array('value' => $value));
}
}
/**
* Get option value
*
* <code>
* $pages_limit = Option::get('pages_limit');
* if ($pages_limit == '10') {
* // do something...
* }
* </code>
*
* @param string $option Name of option to get.
* @return string
*/
public static function get($option) {
// Redefine vars
$option = (string) $option;
// Select specific option
$option_name = Option::$options->select('[name="'.$option.'"]', null);
// Return specific option value
return isset($option_name['value']) ? $option_name['value'] : '';
}
/**
* Delete option
*
* <code>
* Option::delete('pages_limit');
* </code>
*
* @param string $option Name of option to delete.
* @return boolean
*/
public static function delete($option) {
// Redefine vars
$option = (string) $option;
// Delete specific option
return Option::$options->deleteWhere('[name="'.$option.'"]');
}
/**
* Check if option exist
*
* <code>
* if (Option::exists('pages_limit')) {
* // do something...
* }
* </code>
*
* @param string $option Name of option to check.
* @return boolean
*/
public static function exists($option) {
// Redefine vars
$option = (string) $option;
// Check if option exists
return (count(Option::$options->select('[name="'.$option.'"]', null)) > 0) ? true : false;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,187 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra Shortcodes API
*
* The Shortcode API s a simple regex based parser that allows you to replace simple bbcode-like tags
* within a HTMLText or HTMLVarchar field when rendered into a content.
*
* Examples of shortcode tags:
*
* {shortcode}
* {shortcode parameter="value"}
* {shortcode parameter="value"}Enclosed Content{/shortcode}
*
*
* Example of escaping shortcodes:
*
* {{shortcode}}
*
*
* @package Monstra
* @subpackage Engine
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Shortcode {
/**
* Shortcode tags array
*
* @var shortcode_tags
*/
protected static $shortcode_tags = array();
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Add new shortcode
*
* <code>
* function returnSiteUrl() {
* return Option::get('siteurl');
* }
*
* // Add shortcode {siteurl}
* Shortcode::add('siteurl', 'returnSiteUrl');
* </code>
*
* @param string $shortcode Shortcode tag to be searched in content.
* @param string $callback_function The callback function to replace the shortcode with.
*/
public static function add($shortcode, $callback_function) {
// Redefine vars
$shortcode = (string) $shortcode;
// Add new shortcode
if (is_callable($callback_function)) Shortcode::$shortcode_tags[$shortcode] = $callback_function;
}
/**
* Remove a specific registered shortcode.
*
* <code>
* Shortcode::delete('shortcode_name');
* </code>
*
* @param string $shortcode Shortcode tag.
*/
public static function delete($shortcode) {
// Redefine vars
$shortcode = (string) $shortcode;
// Delete shortcode
if (Shortcode::exists($shortcode)) unset(Shortcode::$shortcode_tags[$shortcode]);
}
/**
* Remove all registered shortcodes.
*
* <code>
* Shortcode::clear();
* </code>
*
*/
public static function clear() {
Shortcode::$shortcode_tags = array();
}
/**
* Check if a shortcode has been registered.
*
* <code>
* if (Shortcode::exists('shortcode_name')) {
* // do something...
* }
* </code>
*
* @param string $shortcode Shortcode tag.
*/
public static function exists($shortcode) {
// Redefine vars
$shortcode = (string) $shortcode;
// Check shortcode
return array_key_exists($shortcode, Shortcode::$shortcode_tags);
}
/**
* Parse a string, and replace any registered shortcodes within it with the result of the mapped callback.
*
* <code>
* $content = Shortcode::parse($content);
* </code>
*
* @param string $content Content
* @return string
*/
public static function parse($content) {
if ( ! Shortcode::$shortcode_tags) return $content;
$shortcodes = implode('|', array_map('preg_quote', array_keys(Shortcode::$shortcode_tags)));
$pattern = "/(.?)\{([$shortcodes]+)(.*?)(\/)?\}(?(4)|(?:(.+?)\{\/\s*\\2\s*\}))?(.?)/s";
return preg_replace_callback($pattern, 'Shortcode::_handle', $content);
}
/**
* _handle()
*/
protected static function _handle($matches) {
$prefix = $matches[1];
$suffix = $matches[6];
$shortcode = $matches[2];
// Allow for escaping shortcodes by enclosing them in {{shortcode}}
if ($prefix == '{' && $suffix == '}') {
return substr($matches[0], 1, -1);
}
$attributes = array(); // Parse attributes into into this array.
if (preg_match_all('/(\w+) *= *(?:([\'"])(.*?)\\2|([^ "\'>]+))/', $matches[3], $match, PREG_SET_ORDER)) {
foreach ($match as $attribute) {
if ( ! empty($attribute[4])) {
$attributes[strtolower($attribute[1])] = $attribute[4];
} elseif ( ! empty($attribute[3])) {
$attributes[strtolower($attribute[1])] = $attribute[3];
}
}
}
// Check if this shortcode realy exists then call user function else return empty string
return (isset(Shortcode::$shortcode_tags[$shortcode])) ? $prefix . call_user_func(Shortcode::$shortcode_tags[$shortcode], $attributes, $matches[5], $shortcode) . $suffix : '';
}
}

View File

@@ -1,228 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra Site module
*
* @package Monstra
* @subpackage Engine
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Site {
/**
* An instance of the Site class
*
* @var site
*/
protected static $instance = null;
/**
* Initializing site
*
* @return Site
*/
public static function init() {
if ( ! isset(self::$instance)) self::$instance = new Site();
return self::$instance;
}
/**
* Protected clone method to enforce singleton behavior.
*
* @access protected
*/
protected function __clone() {
// Nothing here.
}
/**
* Construct
*/
protected function __construct() {
call_user_func(ucfirst(Uri::command()).'::main');
}
/**
* Get site name
*
* <code>
* echo Site::name();
* </code>
*
* @return string
*/
public static function name() {
return Option::get('sitename');
}
/**
* Get site theme
*
* <code>
* echo Site::theme();
* </code>
*
* @return string
*/
public static function theme() {
return Option::get('theme_site_name');
}
/**
* Get Page title
*
* <code>
* echo Site::title();
* </code>
*
* @return string
*/
public static function title() {
return call_user_func(ucfirst(Uri::command()).'::title');
}
/**
* Get page description
*
* <code>
* echo Site::description();
* </code>
*
* @return string
*/
public static function description() {
return (($description = trim(call_user_func(ucfirst(Uri::command()).'::description'))) == '') ? Html::toText(Option::get('description')) : Html::toText($description);
}
/**
* Get page keywords
*
* <code>
* echo Site::keywords();
* </code>
*
* @return string
*/
public static function keywords() {
return (($keywords = trim(call_user_func(ucfirst(Uri::command()).'::keywords'))) == '') ? Html::toText(Option::get('keywords')) : Html::toText($keywords);
}
/**
* Get site slogan
*
* <code>
* echo Site::slogan();
* </code>
*
* @return string
*/
public static function slogan() {
return Option::get('slogan');
}
/**
* Get page content
*
* <code>
* echo Site::content();
* </code>
*
* @return string
*/
public static function content() {
return Filter::apply('content', call_user_func(ucfirst(Uri::command()).'::content'));
}
/**
* Get compressed template
*
* <code>
* echo Site::template();
* </code>
*
* @param string $theme Theme name
* @return mixed
*/
public static function template($theme = null) {
// Get specific theme or current theme
$current_theme = ($theme == null) ? Option::get('theme_site_name') : $theme ;
// Get template
$template = call_user_func(ucfirst(Uri::command()).'::template');
// Check whether is there such a template in the current theme
// else return default template: index
// also compress template file :)
if (File::exists(THEMES_SITE . DS . $current_theme . DS . $template . '.template.php')) {
if ( ! file_exists(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php') or
filemtime(THEMES_SITE . DS . $current_theme . DS . $template .'.template.php') > filemtime(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php')) {
$buffer = file_get_contents(THEMES_SITE. DS . $current_theme . DS . $template .'.template.php');
$buffer = Minify::html($buffer);
file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.minify.' . $template . '.template.php', $buffer);
}
return 'minify.'.$template;
} else {
if ( ! File::exists(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php') or
filemtime(THEMES_SITE . DS . $current_theme . DS . 'index.template.php') > filemtime(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php')) {
$buffer = file_get_contents(THEMES_SITE . DS . $current_theme . DS . 'index.template.php');
$buffer = Minify::html($buffer);
file_put_contents(MINIFY . DS . 'theme.' . $current_theme . '.' . 'minify.index.template.php', $buffer);
}
return 'minify.index';
}
}
/**
* Get site url
*
* <code>
* echo Site::url();
* </code>
*
* @return string
*/
public static function url() {
return Option::get('siteurl');
}
/**
* Get copyright information
*
* <code>
* echo Site::powered();
* </code>
*
* @return string
*/
public static function powered() {
return __('Powered by', 'system').' <a href="http://monstra.org" target="_blank">Monstra</a> ' . Core::VERSION;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,171 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Agent Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Agent {
/**
* Mobiles
*
* @var array
*/
public static $mobiles = array (
'ipad',
'iphone',
'ipod',
'android',
'windows ce',
'windows phone',
'mobileexplorer',
'opera mobi',
'opera mini',
'fennec',
'blackberry',
'nokia',
'kindle',
'ericsson',
'motorola',
'minimo',
'iemobile',
'symbian',
'webos',
'hiptop',
'palmos',
'palmsource',
'xiino',
'avantgo',
'docomo',
'up.browser',
'vodafone',
'portable',
'pocket',
'mobile',
'phone',
);
/**
* Robots
*
* @var array
*/
public static $robots = array(
'googlebot',
'msnbot',
'slurp',
'yahoo',
'askjeeves',
'fastcrawler',
'infoseek',
'lycos',
'ia_archiver',
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Searches for a string in the user agent string.
*
* @param array $agents Array of strings to look for
* @return boolean
*/
protected static function find($agents) {
// If isset HTTP_USER_AGENT ?
if (isset($_SERVER['HTTP_USER_AGENT'])) {
// Loop through $agents array
foreach($agents as $agent) {
// If current user agent == agents[agent] then return true
if(stripos($_SERVER['HTTP_USER_AGENT'], $agent) !== false) {
return true;
}
}
}
// Else return false
return false;
}
/**
* Returns true if the user agent that made the request is identified as a mobile device.
*
* <code>
* if (Agent::isMobile()) {
* // Do something...
* }
* </code>
*
* @return boolean
*/
public static function isMobile() {
return Agent::find(Agent::$mobiles);
}
/**
* Returns true if the user agent that made the request is identified as a robot/crawler.
*
* <code>
* if (Agent::isRobot()) {
* // Do something...
* }
* </code>
*
* @return boolean
*/
public static function isRobot() {
return Agent::find(Agent::$robots);
}
/**
* Returns TRUE if the string you're looking for exists in the user agent string and FALSE if not.
*
* <code>
* if (Agent::is('iphone')) {
* // Do something...
* }
*
* if (Agent::is(array('iphone', 'ipod'))) {
* // Do something...
* }
* </code>
*
* @param mixed $device String or array of strings you're looking for
* @return boolean
*/
public static function is($device) {
return Agent::find((array) $device);
}
}

View File

@@ -1,97 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Alert Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Alert {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Show success message
*
* <code>
* Alert::success('Message here...');
* </code>
*
* @param string $message Message
* @param integer $time Time
*/
public static function success($message, $time = 3000) {
// Redefine vars
$message = (string) $message;
$time = (int) $time;
echo '<div class="alert alert-info">'.$message.'</div>
<script type="text/javascript">setTimeout(\'$(".alert").slideUp("slow")\', '.$time.'); </script>';
}
/**
* Show warning message
*
* <code>
* Alert::warning('Message here...');
* </code>
*
* @param string $message Message
* @param integer $time Time
*/
public static function warning($message, $time = 3000) {
// Redefine vars
$message = (string) $message;
$time = (int) $time;
echo '<div class="alert alert-warning">'.$message.'</div>
<script type="text/javascript">setTimeout(\'$(".alert").slideUp("slow")\', '.$time.'); </script>';
}
/**
* Show error message
*
* <code>
* Alert::error('Message here...');
* </code>
*
* @param string $message Message
* @param integer $time Time
*/
public static function error($message, $time = 3000) {
// Redefine vars
$message = (string) $message;
$time = (int) $time;
echo '<div class="alert alert-error">'.$message.'</div>
<script type="text/javascript">setTimeout(\'$(".alert").slideUp("slow")\', '.$time.'); </script>';
}
}

View File

@@ -1,193 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Array Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Arr {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Subval sort
*
* <code>
* $new_array = Arr::subvalSort($old_array, 'sort');
* </code>
*
* @param array $a Array
* @param string $subkey Key
* @param string $order Order type DESC or ASC
* @return array
*/
public static function subvalSort($a, $subkey, $order = null) {
if (count($a) != 0 || (!empty($a))) {
foreach ($a as $k => $v) $b[$k] = function_exists('mb_strtolower') ? mb_strtolower($v[$subkey]) : strtolower($v[$subkey]);
if ($order == null || $order == 'ASC') asort($b); else if ($order == 'DESC') arsort($b);
foreach ($b as $key => $val) $c[] = $a[$key];
return $c;
}
}
/**
* Returns value from array using "dot notation".
* If the key does not exist in the array, the default value will be returned instead.
*
* <code>
* $login = Arr::get($_POST, 'login');
*
* $array = array('foo' => 'bar');
* $foo = Arr::get($array, 'foo');
*
* $array = array('test' => array('foo' => 'bar'));
* $foo = Arr::get($array, 'test.foo');
* </code>
*
* @param array $array Array to extract from
* @param string $path Array path
* @param mixed $default Default value
* @return mixed
*/
public static function get($array, $path, $default = null) {
// Get segments from path
$segments = explode('.', $path);
// Loop through segments
foreach($segments as $segment) {
// Check
if ( ! is_array($array) || !isset($array[$segment])) {
return $default;
}
// Write
$array = $array[$segment];
}
// Return
return $array;
}
/**
* Deletes an array value using "dot notation".
*
* <code>
* Arr::delete($array, 'foo.bar');
* </code>
*
* @access public
* @param array $array Array you want to modify
* @param string $path Array path
* @return boolean
*/
public static function delete(&$array, $path) {
// Get segments from path
$segments = explode('.', $path);
// Loop through segments
while(count($segments) > 1) {
$segment = array_shift($segments);
if ( ! isset($array[$segment]) || !is_array($array[$segment])) {
return false;
}
$array =& $array[$segment];
}
unset($array[array_shift($segments)]);
return true;
}
/**
* Checks if the given dot-notated key exists in the array.
*
* <code>
* if (Arr::keyExists($array, 'foo.bar')) {
* // Do something...
* }
* </code>
*
* @param array $array The search array
* @param mixed $path Array path
* @return boolean
*/
public static function keyExists($array, $path) {
foreach (explode('.', $path) as $segment) {
if ( ! is_array($array) or ! array_key_exists($segment, $array)) {
return false;
}
$array = $array[$segment];
}
return true;
}
/**
* Returns a random value from an array.
*
* <code>
* Arr::random(array('php', 'js', 'css', 'html'));
* </code>
*
* @access public
* @param array $array Array path
* @return mixed
*/
public static function random($array) {
return $array[array_rand($array)];
}
/**
* Returns TRUE if the array is associative and FALSE if not.
*
* <code>
* if (Arr::isAssoc($array)) {
* // Do something...
* }
* </code>
*
* @param array $array Array to check
* @return boolean
*/
public static function isAssoc($array) {
return (bool) count(array_filter(array_keys($array), 'is_string'));
}
}

View File

@@ -1,225 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Cache Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Cache {
/**
* Cache directory
*
* @var string
*/
public static $cache_dir = CACHE;
/**
* Cache file ext
*
* @var string
*/
public static $cache_file_ext = 'txt';
/**
* Cache life time (in seconds)
*
* @var int
*/
public static $cache_time = 31556926;
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Configure the settings of Cache
*
* <code>
* Cache::configure('cache_dir', 'path/to/cache/dir');
* </code>
*
* @param mixed $setting Setting name
* @param mixed $value Setting value
*/
public static function configure($setting, $value){
if (property_exists("cache", $setting)) Cache::$$setting = $value;
}
/**
* Get data from cache
*
* <code>
* $profile = Cache::get('profiles', 'profile');
* </code>
*
* @param string $namespace Namespace
* @param string $key Cache key
* @return boolean
*/
public static function get($namespace, $key){
// Redefine vars
$namespace = (string) $namespace;
// Get cache file id
$cache_file_id = Cache::getCacheFileID($namespace, $key);
// Is cache file exists ?
if (file_exists($cache_file_id)) {
// If cache file has not expired then fetch it
if ((time() - filemtime($cache_file_id)) < Cache::$cache_time) {
$handle = fopen($cache_file_id, 'r');
$cache = '';
while ( ! feof($handle)) {
$cache .= fgets($handle);
}
fclose($handle);
return unserialize($cache);
} else {
unlink($cache_file_id);
return false;
}
} else {
return false;
}
}
/**
* Create new cache file $key in namescapce $namespace with the given data $data
*
* <code>
* $profile = array('login' => 'Awilum',
* 'email' => 'awilum@msn.com');
* Cache::put('profiles', 'profile', $profile);
* </code>
*
* @param string $namespace Namespace
* @param string $key Cache key
* @param mixed $data The variable to store
* @return boolean
*/
public static function put($namespace, $key, $data) {
// Redefine vars
$namespace = (string) $namespace;
// Is CACHE directory writable ?
if (file_exists(CACHE) === false || is_readable(CACHE) === false || is_writable(CACHE) === false) {
throw new RuntimeException(vsprintf("%s(): Cache directory ('%s') is not writable.", array(__METHOD__, CACHE)));
}
// Create namespace
if ( ! file_exists(Cache::getNamespaceID($namespace))) {
mkdir(Cache::getNamespaceID($namespace), 0775, true);
}
// Write cache to specific namespace
return file_put_contents(Cache::getCacheFileID($namespace, $key), serialize($data), LOCK_EX);
}
/**
* Deletes a cache in specific namespace
*
* <code>
* Cache::delete('profiles', 'profile');
* </code>
*
* @param string $namespace Namespace
* @param string $key Cache key
* @return boolean
*/
public static function delete($namespace, $key) {
// Redefine vars
$namespace = (string) $namespace;
if (file_exists(Cache::getCacheFileID($namespace, $key))) unlink(Cache::getCacheFileID($namespace, $key)); else return false;
}
/**
* Clean specific cache namespace.
*
* <code>
* Cache::clean('profiles');
* </code>
*
* @param string $namespace Namespace
* @return null
*/
public static function clean($namespace) {
// Redefine vars
$namespace = (string) $namespace;
array_map("unlink", glob(Cache::$cache_dir . DS . md5($namespace) . DS . "*." . Cache::$cache_file_ext));
}
/**
* Get cache file ID
*
* @param string $namespace Namespace
* @param string $key Cache key
* @return string
*/
protected static function getCacheFileID($namespace, $key) {
// Redefine vars
$namespace = (string) $namespace;
return Cache::$cache_dir . DS . md5($namespace) . DS . md5($key) . '.' . Cache::$cache_file_ext;
}
/**
* Get namespace ID
*
* @param string $namespace Namespace
* @return string
*/
protected static function getNamespaceID($namespace) {
// Redefine vars
$namespace = (string) $namespace;
return Cache::$cache_dir . DS . md5($namespace);
}
}

View File

@@ -1,84 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Captcha Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Captcha {
/**
* Creates the question from random variables, which are also saved to the session.
*
* <code>
* <form method="post">
* <?php echo Captcha::getMathQuestion(); ?>
* <input type="text" name="answer" />
* <input type="submit" name="sumbmit" />
* </form>
* </code>
*
* @return string
*/
public static function getMathQuestion() {
if ( ! isset($_SESSION["math_question_v1"]) && ! isset($_SESSION["math_question_v2"])) {
$v1 = rand(1,9);
$v2 = rand(1,9);
$_SESSION["math_question_v1"] = $v1;
$_SESSION["math_question_v2"] = $v2;
} else {
$v1 = $_SESSION["math_question_v1"];
$v2 = $_SESSION["math_question_v2"];
}
return sprintf("%s + %s = ", $v1, $v2);
}
/**
* Checks the given answer if it matches the addition of the saved session variables.
*
* <code>
* if (isset($_POST['submit'])) {
* if (Captcha::correctAnswer($_POST['answer'])) {
* // Do something...
* }
* }
* </code>
*
* @param integer $answer User answer
*/
public static function correctAnswer($answer){
$v1 = $_SESSION["math_question_v1"];
$v2 = $_SESSION["math_question_v2"];
unset($_SESSION['math_question_v1']);
unset($_SESSION['math_question_v2']);
if (($v1 + $v2) == $answer) {
return true;
}
return false;
}
}

View File

@@ -1,113 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Cookie Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Cookie {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Send a cookie
*
* <code>
* Cookie::set('limit', 10);
* </code>
*
* @param string $key A name for the cookie.
* @param mixed $value The value to be stored. Keep in mind that they will be serialized.
* @param integer $expire The number of seconds that this cookie will be available.
* @param string $path The path on the server in which the cookie will be availabe. Use / for the entire domain, /foo if you just want it to be available in /foo.
* @param string $domain The domain that the cookie is available on. Use .example.com to make it available on all subdomains of example.com.
* @param boolean $secure Should the cookie be transmitted over a HTTPS-connection? If true, make sure you use a secure connection, otherwise the cookie won't be set.
* @param boolean $httpOnly Should the cookie only be available through HTTP-protocol? If true, the cookie can't be accessed by Javascript, ...
* @return boolean
*/
public static function set($key, $value, $expire = 86400, $domain = '', $path = '/', $secure = false, $httpOnly = false) {
// Redefine vars
$key = (string) $key;
$value = serialize($value);
$expire = time() + (int) $expire;
$path = (string) $path;
$domain = (string) $domain;
$secure = (bool) $secure;
$httpOnly = (bool) $httpOnly;
// Set cookie
return setcookie($key, $value, $expire, $path, $domain, $secure, $httpOnly);
}
/**
* Get a cookie
*
* <code>
* $limit = Cookie::get('limit');
* </code>
*
* @param string $key The name of the cookie that should be retrieved.
* @return mixed
*/
public static function get($key) {
// Redefine key
$key = (string) $key;
// Cookie doesn't exist
if( ! isset($_COOKIE[$key])) return false;
// Fetch base value
$value = (get_magic_quotes_gpc()) ? stripslashes($_COOKIE[$key]) : $_COOKIE[$key];
// Unserialize
$actual_value = @unserialize($value);
// If unserialize failed
if($actual_value === false && serialize(false) != $value) return false;
// Everything is fine
return $actual_value;
}
/**
* Delete a cookie
*
* <code>
* Cookie::delete('limit');
* </code>
*
* @param string $name The name of the cookie that should be deleted.
*/
public static function delete($key) {
unset($_COOKIE[$key]);
}
}

View File

@@ -1,153 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Curl Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Curl {
/**
* Default curl options.
*
* @var array
*/
protected static $default_options = array(
CURLOPT_USERAGENT => 'Mozilla/5.0 (compatible; Monstra CMS; +http://monstra.org)',
CURLOPT_RETURNTRANSFER => true
);
/**
* Information about the last transfer.
*
* @var array
*/
protected static $info;
/**
* Performs a curl GET request.
*
* <code>
* $res = Curl::get('http://site.com/');
* </code>
*
* @param string $url The URL to fetch
* @param array $options An array specifying which options to set and their values
* @return string
*/
public static function get($url, array $options = null) {
// Redefine vars
$url = (string) $url;
// Check if curl is available
if ( ! function_exists('curl_init')) throw new RuntimeException(vsprintf("%s(): This method requires cURL (http://php.net/curl), it seems like the extension isn't installed.", array(__METHOD__)));
// Initialize a cURL session
$handle = curl_init($url);
// Merge options
$options = (array) $options + Curl::$default_options;
// Set multiple options for a cURL transfer
curl_setopt_array($handle, $options);
// Perform a cURL session
$response = curl_exec($handle);
// Set information regarding a specific transfer
Curl::$info = curl_getinfo($handle);
// Close a cURL session
curl_close($handle);
// Return response
return $response;
}
/**
* Performs a curl POST request.
*
* <code>
* $res = Curl::post('http://site.com/login');
* </code>
*
* @param string $url The URL to fetch
* @param array $data An array with the field name as key and field data as value
* @param boolean $multipart True to send data as multipart/form-data and false to send as application/x-www-form-urlencoded
* @param array $options An array specifying which options to set and their values
* @return string
*/
public static function post($url, array $data = null, $multipart = false, array $options = null) {
// Redefine vars
$url = (string) $url;
// Check if curl is available
if ( ! function_exists('curl_init')) throw new RuntimeException(vsprintf("%s(): This method requires cURL (http://php.net/curl), it seems like the extension isn't installed.", array(__METHOD__)));
// Initialize a cURL session
$handle = curl_init($url);
// Merge options
$options = (array) $options + Curl::$default_options;
// Add options
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = ($multipart === true) ? (array) $data : http_build_query((array) $data);
// Set multiple options for a cURL transfer
curl_setopt_array($handle, $options);
// Perform a cURL session
$response = curl_exec($handle);
// Set information regarding a specific transfer
Curl::$info = curl_getinfo($handle);
// Close a cURL session
curl_close($handle);
// Return response
return $response;
}
/**
* Gets information about the last transfer.
*
* <code>
* $res = Curl::getInfo();
* </code>
*
* @param string $value Array key of the array returned by curl_getinfo()
* @return mixed
*/
public static function getInfo($value = null) {
if (empty(Curl::$info)) {
return false;
}
return ($value === null) ? Curl::$info : Curl::$info[$value];
}
}

View File

@@ -1,432 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Date Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Date {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Get format date
*
* <code>
* echo Date::format($date, 'j.n.Y');
* </code>
*
* @param integer $date Unix timestamp
* @param string $format Date format
* @return integer
*/
public static function format($date, $format = '') {
// Redefine vars
$format = (string) $format;
$date = (int) $date;
if ($format != '') { return date($format, $date); } else { return date(MONSTRA_DATE_FORMAT, $date); }
}
/**
* Get number of seconds in a minute, incrementing by a step.
*
* <code>
* $seconds = Date::seconds();
* </code>
*
* @param integer $step Amount to increment each step by, 1 to 30
* @param integer $start Start value
* @param integer $end End value
* @return array
*/
public static function seconds($step = 1, $start = 0, $end = 60) {
// Redefine vars
$step = (int) $step;
$start = (int) $start;
$end = (int) $end;
return Date::_range($step, $start, $end);
}
/**
* Get number of minutes in a hour, incrementing by a step.
*
* <code>
* $minutes = Date::minutes();
* </code>
*
* @param integer $step Amount to increment each step by, 1 to 30
* @param integer $start Start value
* @param integer $end End value
* @return array
*/
public static function minutes($step = 5, $start = 0, $end = 60) {
// Redefine vars
$step = (int) $step;
$start = (int) $start;
$end = (int) $end;
return Date::_range($step, $start, $end);
}
/**
* Get number of hours, incrementing by a step.
*
* <code>
* $hours = Date::hours();
* </code>
*
* @param integer $step Amount to increment each step by, 1 to 30
* @param integer $long Start value
* @param integer $start End value
* @return array
*/
public static function hours($step = 1, $long = false, $start = null) {
// Redefine vars
$step = (int) $step;
$long = (bool) $long;
if ($start === null) $start = ($long === FALSE) ? 1 : 0;
$end = ($long === true) ? 23 : 12;
return Date::_range($step, $start, $end, true);
}
/**
* Get number of months.
*
* <code>
* $months = Date::months();
* </code>
*
* @return array
*/
public static function months() {
return Date::_range(1, 1, 12, true);
}
/**
* Get number of days.
*
* <code>
* $months = Date::days();
* </code>
*
* @return array
*/
public static function days() {
return Date::_range(1, 1, Date::daysInMonth((int)date('M')), true);
}
/**
* Returns the number of days in the requested month
*
* <code>
* $days = Date::daysInMonth(1);
* </code>
*
* @param integer $month Month as a number (1-12)
* @param integer $year The year
* @return integer
*/
public static function daysInMonth($month, $year = null) {
// Redefine vars
$month = (int) $month;
$year = ! empty($year) ? (int) $year : (int) date('Y');
if ($month < 1 or $month > 12) {
return false;
} elseif ($month == 2) {
if ($year % 400 == 0 or ($year % 4 == 0 and $year % 100 != 0)) {
return 29;
}
}
$days_in_month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
return $days_in_month[$month-1];
}
/**
* Get number of years.
*
* <code>
* $years = Date::years();
* </code>
*
* @param integer $long Start value
* @param integer $start End value
* @return array
*/
public static function years($start = 1980, $end = 2024) {
// Redefine vars
$start = (int) $start;
$end = (int) $end;
return Date::_range(1, $start, $end, true);
}
/**
* Get current season name
*
* <code>
* echo Date::season();
* </code>
*
* @return string
*/
public static function season() {
$seasons = array("Winter", "Spring", "Summer", "Autumn");
return $seasons[(int)((date("n") %12)/3)];
}
/**
* Get today date
*
* <code>
* echo Date::today();
* </code>
*
* @param string $format Date format
* @return string
*/
public static function today($format = '') {
// Redefine vars
$format = (string) $format;
if ($format != '') { return date($format); } else { return date(MONSTRA_DATE_FORMAT); }
}
/**
* Get yesterday date
*
* <code>
* echo Date::yesterday();
* </code>
*
* @param string $format Date format
* @return string
*/
public static function yesterday($format = '') {
// Redefine vars
$format = (string) $format;
if ($format != '') { return date($format, strtotime("-1 day")); } else { return date(MONSTRA_DATE_FORMAT, strtotime("-1 day")); }
}
/**
* Get tomorrow date
*
* <code>
* echo Date::tomorrow();
* </code>
*
* @param string $format Date format
* @return string
*/
public static function tomorrow($format = '') {
// Redefine vars
$format = (string) $format;
if ($format != '') { return date($format, strtotime("+1 day")); } else { return date(MONSTRA_DATE_FORMAT, strtotime("-1 day")); }
}
/**
* Converts a UNIX timestamp to DOS format.
*
* <code>
* $dos = Date::unix2dos($unix);
* </code>
*
* @param integer $timestamp UNIX timestamp
* @return integer
*/
public static function unix2dos($timestamp = 0) {
$timestamp = ($_timestamp == 0) ? getdate() : getdate($_timestamp);
if ($timestamp['year'] < 1980) return (1 << 21 | 1 << 16);
$timestamp['year'] -= 1980;
return ($timestamp['year'] << 25 | $timestamp['mon'] << 21 |
$timestamp['mday'] << 16 | $timestamp['hours'] << 11 |
$timestamp['minutes'] << 5 | $timestamp['seconds'] >> 1);
}
/**
* Converts a DOS timestamp to UNIX format.
*
* <code>
* $unix = Date::dos2unix($dos);
* </code>
*
* @param integer $timestamp DOS timestamp
* @return integer
*/
public static function dos2unix($timestamp) {
$sec = 2 * ($timestamp & 0x1f);
$min = ($timestamp >> 5) & 0x3f;
$hrs = ($timestamp >> 11) & 0x1f;
$day = ($timestamp >> 16) & 0x1f;
$mon = (($timestamp >> 21) & 0x0f);
$year = (($timestamp >> 25) & 0x7f) + 1980;
return mktime($hrs, $min, $sec, $mon, $day, $year);
}
/**
* Get Time zones
*
* @return array
*/
public static function timezones() {
return array('Kwajalein'=>'(GMT-12:00) International Date Line West',
'Pacific/Samoa'=>'(GMT-11:00) Midway Island, Samoa',
'Pacific/Honolulu'=>'(GMT-10:00) Hawaii',
'America/Anchorage'=>'(GMT-09:00) Alaska',
'America/Los_Angeles'=>'(GMT-08:00) Pacific Time (US &amp; Canada)',
'America/Tijuana'=>'(GMT-08:00) Tijuana, Baja California',
'America/Denver'=>'(GMT-07:00) Mountain Time (US &amp; Canada)',
'America/Chihuahua'=>'(GMT-07:00) Chihuahua, La Paz, Mazatlan',
'America/Phoenix'=>'(GMT-07:00) Arizona',
'America/Regina'=>'(GMT-06:00) Saskatchewan',
'America/Tegucigalpa'=>'(GMT-06:00) Central America',
'America/Chicago'=>'(GMT-06:00) Central Time (US &amp; Canada)',
'America/Mexico_City'=>'(GMT-06:00) Guadalajara, Mexico City, Monterrey',
'America/New_York'=>'(GMT-05:00) Eastern Time (US &amp; Canada)',
'America/Bogota'=>'(GMT-05:00) Bogota, Lima, Quito, Rio Branco',
'America/Indiana/Indianapolis'=>'(GMT-05:00) Indiana (East)',
'America/Caracas'=>'(GMT-04:30) Caracas',
'America/Halifax'=>'(GMT-04:00) Atlantic Time (Canada)',
'America/Manaus'=>'(GMT-04:00) Manaus',
'America/Santiago'=>'(GMT-04:00) Santiago',
'America/La_Paz'=>'(GMT-04:00) La Paz',
'America/St_Johns'=>'(GMT-03:30) Newfoundland',
'America/Argentina/Buenos_Aires'=>'(GMT-03:00) Buenos Aires',
'America/Sao_Paulo'=>'(GMT-03:00) Brasilia',
'America/Godthab'=>'(GMT-03:00) Greenland',
'America/Montevideo'=>'(GMT-03:00) Montevideo',
'America/Argentina/Buenos_Aires'=>'(GMT-03:00) Georgetown',
'Atlantic/South_Georgia'=>'(GMT-02:00) Mid-Atlantic',
'Atlantic/Azores'=>'(GMT-01:00) Azores',
'Atlantic/Cape_Verde'=>'(GMT-01:00) Cape Verde Is.',
'Europe/London'=>'(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London',
'Atlantic/Reykjavik'=>'(GMT) Monrovia, Reykjavik',
'Africa/Casablanca'=>'(GMT) Casablanca',
'Europe/Belgrade'=>'(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague',
'Europe/Sarajevo'=>'(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb',
'Europe/Brussels'=>'(GMT+01:00) Brussels, Copenhagen, Madrid, Paris',
'Africa/Algiers'=>'(GMT+01:00) West Central Africa',
'Europe/Amsterdam'=>'(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna',
'Africa/Cairo'=>'(GMT+02:00) Cairo',
'Europe/Helsinki'=>'(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius',
'Europe/Athens'=>'(GMT+02:00) Athens, Bucharest, Istanbul',
'Asia/Jerusalem'=>'(GMT+02:00) Jerusalem',
'Asia/Amman'=>'(GMT+02:00) Amman',
'Asia/Beirut'=>'(GMT+02:00) Beirut',
'Africa/Windhoek'=>'(GMT+02:00) Windhoek',
'Africa/Harare'=>'(GMT+02:00) Harare, Pretoria',
'Asia/Kuwait'=>'(GMT+03:00) Kuwait, Riyadh',
'Asia/Baghdad'=>'(GMT+03:00) Baghdad',
'Europe/Minsk'=>'(GMT+03:00) Minsk',
'Africa/Nairobi'=>'(GMT+03:00) Nairobi',
'Asia/Tbilisi'=>'(GMT+03:00) Tbilisi',
'Asia/Tehran'=>'(GMT+03:30) Tehran',
'Asia/Muscat'=>'(GMT+04:00) Abu Dhabi, Muscat',
'Asia/Baku'=>'(GMT+04:00) Baku',
'Europe/Moscow'=>'(GMT+04:00) Moscow, St. Petersburg, Volgograd',
'Asia/Yerevan'=>'(GMT+04:00) Yerevan',
'Asia/Karachi'=>'(GMT+05:00) Islamabad, Karachi',
'Asia/Tashkent'=>'(GMT+05:00) Tashkent',
'Asia/Kolkata'=>'(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi',
'Asia/Colombo'=>'(GMT+05:30) Sri Jayawardenepura',
'Asia/Katmandu'=>'(GMT+05:45) Kathmandu',
'Asia/Dhaka'=>'(GMT+06:00) Astana, Dhaka',
'Asia/Yekaterinburg'=>'(GMT+06:00) Ekaterinburg',
'Asia/Rangoon'=>'(GMT+06:30) Yangon (Rangoon)',
'Asia/Novosibirsk'=>'(GMT+07:00) Almaty, Novosibirsk',
'Asia/Bangkok'=>'(GMT+07:00) Bangkok, Hanoi, Jakarta',
'Asia/Beijing'=>'(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi',
'Asia/Ulaanbaatar'=>'(GMT+08:00) Irkutsk, Ulaan Bataar',
'Asia/Krasnoyarsk'=>'(GMT+08:00) Krasnoyarsk',
'Asia/Kuala_Lumpur'=>'(GMT+08:00) Kuala Lumpur, Singapore',
'Asia/Taipei'=>'(GMT+08:00) Taipei',
'Australia/Perth'=>'(GMT+08:00) Perth',
'Asia/Seoul'=>'(GMT+09:00) Seoul',
'Asia/Tokyo'=>'(GMT+09:00) Osaka, Sapporo, Tokyo',
'Australia/Darwin'=>'(GMT+09:30) Darwin',
'Australia/Adelaide'=>'(GMT+09:30) Adelaide',
'Australia/Sydney'=>'(GMT+10:00) Canberra, Melbourne, Sydney',
'Australia/Brisbane'=>'(GMT+10:00) Brisbane',
'Australia/Hobart'=>'(GMT+10:00) Hobart',
'Asia/Yakutsk'=>'(GMT+10:00) Yakutsk',
'Pacific/Guam'=>'(GMT+10:00) Guam, Port Moresby',
'Asia/Vladivostok'=>'(GMT+11:00) Vladivostok',
'Pacific/Fiji'=>'(GMT+12:00) Fiji, Kamchatka, Marshall Is.',
'Asia/Magadan'=>'(GMT+12:00) Magadan, Solomon Is., New Caledonia',
'Pacific/Auckland'=>'(GMT+12:00) Auckland, Wellington',
'Pacific/Tongatapu'=>'(GMT+13:00) Nukualofa'
);
}
/**
* _range()
*/
protected static function _range($step, $start, $end, $flag = false) {
$result = array();
if ($flag) {
for ($i = $start; $i <= $end; $i += $step) $result[$i] = (string)$i;
} else {
for ($i = $start; $i < $end; $i += $step) $result[$i] = sprintf('%02d', $i);
}
return $result;
}
}

View File

@@ -1,124 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Debug Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Debug {
/**
* Time
*
* @var array
*/
protected static $time = array();
/**
* Memory
*
* @var array
*/
protected static $memory = array();
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Save current time for current point
*
* <code>
* Debug::elapsedTimeSetPoint('point_name');
* </code>
*
* @param string $point_name Point name
*/
public static function elapsedTimeSetPoint($point_name) {
Debug::$time[$point_name] = microtime(true);
}
/**
* Get elapsed time for current point
*
* <code>
* echo Debug::elapsedTime('point_name');
* </code>
*
* @param string $point_name Point name
* @return string
*/
public static function elapsedTime($point_name) {
if (isset(Debug::$time[$point_name])) return sprintf("%01.4f", microtime(true) - Debug::$time[$point_name]);
}
/**
* Save current memory for current point
*
* <code>
* Debug::memoryUsageSetPoint('point_name');
* </code>
*
* @param string $point_name Point name
*/
public static function memoryUsageSetPoint($point_name) {
Debug::$memory[$point_name] = memory_get_usage();
}
/**
* Get memory usage for current point
*
* <code>
* echo Debug::memoryUsage('point_name');
* </code>
*
* @param string $point_name Point name
* @return string
*/
public static function memoryUsage($point_name) {
if (isset(Debug::$memory[$point_name])) return Number::byteFormat(memory_get_usage() - Debug::$memory[$point_name]);
}
/**
* Print the variable $data and exit if exit = true
*
* <code>
* Debug::dump($data);
* </code>
*
* @param mixed $data Data
* @param boolean $exit Exit
*/
public static function dump($data, $exit = false){
echo "<pre>dump \n---------------------- \n\n" . print_r($data, true) . "\n----------------------</pre>";
if ($exit) exit;
}
}

View File

@@ -1,215 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Directory Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
/**
* Dir class
*/
class Dir {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Creates a directory
*
* <code>
* Dir::create('folder1');
* </code>
*
* @param string $dir Name of directory to create
* @param integer $chmod Chmod
* @return boolean
*/
public static function create($dir, $chmod = 0775) {
// Redefine vars
$dir = (string) $dir;
// Create new dir if $dir !exists
return ( ! Dir::exists($dir)) ? @mkdir($dir, $chmod, true) : true;
}
/**
* Checks if this directory exists.
*
* <code>
* if (Dir::exists('folder1')) {
* // Do something...
* }
* </code>
*
* @param string $dir Full path of the directory to check.
* @return boolean
*/
public static function exists($dir) {
// Redefine vars
$dir = (string) $dir;
// Directory exists
if (file_exists($dir) && is_dir($dir)) return true;
// Doesn't exist
return false;
}
/**
* Check dir permission
*
* <code>
* echo Dir::checkPerm('folder1');
* </code>
*
* @param string $dir Directory to check
* @return string
*/
public static function checkPerm($dir) {
// Redefine vars
$dir = (string) $dir;
// Clear stat cache
clearstatcache();
// Return perm
return substr(sprintf('%o', fileperms($dir)), -4);
}
/**
* Delete directory
*
* <code>
* Dir::delete('folder1');
* </code>
*
* @param string $dir Name of directory to delete
*/
public static function delete($dir) {
// Redefine vars
$dir = (string) $dir;
// Delete dir
if (is_dir($dir)){$ob=scandir($dir);foreach ($ob as $o){if($o!='.'&&$o!='..'){if(filetype($dir.'/'.$o)=='dir')Dir::delete($dir.'/'.$o); else unlink($dir.'/'.$o);}}}
reset($ob); rmdir($dir);
}
/**
* Get list of directories
*
* <code>
* $dirs = Dir::scan('folders');
* </code>
*
* @param string $dir Directory
*/
public static function scan($dir){
// Redefine vars
$dir = (string) $dir;
// Scan dir
if (is_dir($dir)&&$dh=opendir($dir)){$f=array();while ($fn=readdir($dh)){if($fn!='.'&&$fn!='..'&&is_dir($dir.DS.$fn))$f[]=$fn;}return$f;}
}
/**
* Check if a directory is writable.
*
* <code>
* if (Dir::writable('folder1')) {
* // Do something...
* }
* </code>
*
* @param string $path The path to check.
* @return booleans
*/
public static function writable($path) {
// Redefine vars
$path = (string) $path;
// Create temporary file
$file = tempnam($path, 'writable');
// File has been created
if($file !== false) {
// Remove temporary file
File::delete($file);
// Writable
return true;
}
// Else not writable
return false;
}
/**
* Get directory size.
*
* <code>
* echo Dir::size('folder1');
* </code>
*
* @param string $path The path to directory.
* @return integer
*/
public static function size($path) {
// Redefine vars
$path = (string) $path;
$total_size = 0;
$files = scandir($path);
$clean_path = rtrim($path, '/') . '/';
foreach ($files as $t) {
if ( $t <> "." && $t <> "..") {
$current_file = $clean_path . $t;
if (is_dir($current_file)) {
$total_size += Dir::size($current_file);
} else {
$total_size += filesize($current_file);
}
}
}
// Return total size
return $total_size;
}
}

View File

@@ -1,596 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* File Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class File {
/**
* Mime type list
*
* @var array
*/
public static $mime_types = array(
'aac' => 'audio/aac',
'atom' => 'application/atom+xml',
'avi' => 'video/avi',
'bmp' => 'image/x-ms-bmp',
'c' => 'text/x-c',
'class' => 'application/octet-stream',
'css' => 'text/css',
'csv' => 'text/csv',
'deb' => 'application/x-deb',
'dll' => 'application/x-msdownload',
'dmg' => 'application/x-apple-diskimage',
'doc' => 'application/msword',
'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'exe' => 'application/octet-stream',
'flv' => 'video/x-flv',
'gif' => 'image/gif',
'gz' => 'application/x-gzip',
'h' => 'text/x-c',
'htm' => 'text/html',
'html' => 'text/html',
'ini' => 'text/plain',
'jar' => 'application/java-archive',
'java' => 'text/x-java',
'jpeg' => 'image/jpeg',
'jpg' => 'image/jpeg',
'js' => 'text/javascript',
'json' => 'application/json',
'mid' => 'audio/midi',
'midi' => 'audio/midi',
'mka' => 'audio/x-matroska',
'mkv' => 'video/x-matroska',
'mp3' => 'audio/mpeg',
'mp4' => 'application/mp4',
'mpeg' => 'video/mpeg',
'mpg' => 'video/mpeg',
'odt' => 'application/vnd.oasis.opendocument.text',
'ogg' => 'audio/ogg',
'pdf' => 'application/pdf',
'php' => 'text/x-php',
'png' => 'image/png',
'psd' => 'image/vnd.adobe.photoshop',
'py' => 'application/x-python',
'ra' => 'audio/vnd.rn-realaudio',
'ram' => 'audio/vnd.rn-realaudio',
'rar' => 'application/x-rar-compressed',
'rss' => 'application/rss+xml',
'safariextz' => 'application/x-safari-extension',
'sh' => 'text/x-shellscript',
'shtml' => 'text/html',
'swf' => 'application/x-shockwave-flash',
'tar' => 'application/x-tar',
'tif' => 'image/tiff',
'tiff' => 'image/tiff',
'torrent' => 'application/x-bittorrent',
'txt' => 'text/plain',
'wav' => 'audio/wav',
'webp' => 'image/webp',
'wma' => 'audio/x-ms-wma',
'xls' => 'application/vnd.ms-excel',
'xml' => 'text/xml',
'zip' => 'application/zip',
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Returns true if the File exists.
*
* <code>
* if (File::exists('filename.txt')) {
* // Do something...
* }
* </code>
*
* @param string $filename The file name
* @return boolean
*/
public static function exists($filename) {
// Redefine vars
$filename = (string) $filename;
// Return
return (file_exists($filename) && is_file($filename));
}
/**
* Delete file
*
* <code>
* File::delete('filename.txt');
* </code>
*
* @param mixed $filename The file name or array of files
* @return boolean
*/
public static function delete($filename) {
// Is array
if (is_array($filename)) {
// Delete each file in $filename array
foreach($filename as $file) {
@unlink((string) $file);
}
} else {
// Is string
return @unlink((string) $filename);
}
}
/**
* Rename file
*
* <code>
* File::rename('filename1.txt', 'filename2.txt');
* </code>
*
* @param string $from Original file location
* @param string $to Desitination location of the file
* @return boolean
*/
public static function rename($from, $to) {
// Redefine vars
$from = (string) $from;
$to = (string) $to;
// If file exists $to than rename it
if ( ! File::exists($to)) return rename($from, $to);
// Else return false
return false;
}
/**
* Copy file
*
* <code>
* File::copy('folder1/filename.txt', 'folder2/filename.txt');
* </code>
*
* @param string $from Original file location
* @param string $to Desitination location of the file
* @return boolean
*/
public static function copy($from, $to) {
// Redefine vars
$from = (string) $from;
$to = (string) $to;
// If file !exists $from and exists $to then return false
if ( ! File::exists($from) || File::exists($to)) return false;
// Else copy file
return copy($from, $to);
}
/**
* Get the File extension.
*
* <code>
* echo File::ext('filename.txt');
* </code>
*
* @param string $filename The file name
* @return string
*/
public static function ext($filename){
// Redefine vars
$filename = (string) $filename;
// Return file extension
return substr(strrchr($filename, '.'), 1);
}
/**
* Get the File name
*
* <code>
* echo File::name('filename.txt');
* </code>
*
* @param string $filename The file name
* @return string
*/
public static function name($filename) {
// Redefine vars
$filename = (string) $filename;
// Return filename
return basename($filename, '.'.File::ext($filename));
}
/**
* Get list of files in directory recursive
*
* <code>
* $files = File::scan('folder');
* $files = File::scan('folder', 'txt');
* $files = File::scan('folder', array('txt', 'log'));
* </code>
*
* @param string $folder Folder
* @param mixed $type Files types
* @return array
*/
public static function scan($folder, $type = null) {
$data = array();
if (is_dir($folder)) {
$iterator = new RecursiveDirectoryIterator($folder);
foreach (new RecursiveIteratorIterator($iterator) as $file) {
if ($type !== null) {
if (is_array($type)) {
$file_ext = substr(strrchr($file->getFilename(), '.'), 1);
if (in_array($file_ext, $type)) {
if (strpos($file->getFilename(), $file_ext, 1)) {
$data[] = $file->getFilename();
}
}
} else {
if (strpos($file->getFilename(), $type, 1)) {
$data[] = $file->getFilename();
}
}
} else {
if ($file->getFilename() !== '.' && $file->getFilename() !== '..') $data[] = $file->getFilename();
}
}
return $data;
} else {
return false;
}
}
/**
* Fetch the content from a file or URL.
*
* <code>
* echo File::getContent('filename.txt');
* </code>
*
* @param string $filename The file name
* @return boolean
*/
public static function getContent($filename) {
// Redefine vars
$filename = (string) $filename;
// If file exists load it
if (File::exists($filename)) {
return file_get_contents($filename);
}
}
/**
* Writes a string to a file.
*
* @param string $filename The path of the file.
* @param string $content The content that should be written.
* @param boolean $createFile Should the file be created if it doesn't exists?
* @param boolean $append Should the content be appended if the file already exists?
* @param integer $chmod Mode that should be applied on the file.
* @return boolean
*/
public static function setContent($filename, $content, $create_file = true, $append = false, $chmod = 0666) {
// Redefine vars
$filename = (string) $filename;
$content = (string) $content;
$create_file = (bool) $create_file;
$append = (bool) $append;
// File may not be created, but it doesn't exist either
if ( ! $create_file && File::exists($filename)) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' doesn't exist", array(__METHOD__)));
// Create directory recursively if needed
Dir::create(dirname($filename));
// Create file & open for writing
$handler = ($append) ? @fopen($filename, 'a') : @fopen($filename, 'w');
// Something went wrong
if ($handler === false) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' could not be created. Check if PHP has enough permissions.", array(__METHOD__)));
// Store error reporting level
$level = error_reporting();
// Disable errors
error_reporting(0);
// Write to file
$write = fwrite($handler, $content);
// Validate write
if($write === false) throw new RuntimeException(vsprintf("%s(): The file '{$filename}' could not be created. Check if PHP has enough permissions.", array(__METHOD__)));
// Close the file
fclose($handler);
// Chmod file
chmod($filename, $chmod);
// Restore error reporting level
error_reporting($level);
// Return
return true;
}
/**
* Get time(in Unix timestamp) the file was last changed
*
* <code>
* echo File::lastChange('filename.txt');
* </code>
*
* @param string $filename The file name
* @return boolean
*/
public static function lastChange($filename) {
// Redefine vars
$filename = (string) $filename;
// If file exists return filemtime
if (File::exists($filename)) {
return filemtime($filename);
}
// Return
return false;
}
/**
* Get last access time
*
* <code>
* echo File::lastAccess('filename.txt');
* </code>
*
* @param string $filename The file name
* @return boolean
*/
public static function lastAccess($filename) {
// Redefine vars
$filename = (string) $filename;
// If file exists return fileatime
if (File::exists($filename)) {
return fileatime($filename);
}
// Return
return false;
}
/**
* Returns the mime type of a file. Returns false if the mime type is not found.
*
* <code>
* echo File::mime('filename.txt');
* </code>
*
* @param string $file Full path to the file
* @param boolean $guess Set to false to disable mime type guessing
* @return string
*/
public static function mime($file, $guess = true) {
// Redefine vars
$file = (string) $file;
$guess = (bool) $guess;
// Get mime using the file information functions
if (function_exists('finfo_open')) {
$info = finfo_open(FILEINFO_MIME_TYPE);
$mime = finfo_file($info, $file);
finfo_close($info);
return $mime;
} else {
// Just guess mime by using the file extension
if ($guess === true) {
$mime_types = File::$mime_types;
$extension = pathinfo($file, PATHINFO_EXTENSION);
return isset($mime_types[$extension]) ? $mime_types[$extension] : false;
} else {
return false;
}
}
}
/**
* Forces a file to be downloaded.
*
* <code>
* File::download('filename.txt');
* </code>
*
* @param string $file Full path to file
* @param string $content_type Content type of the file
* @param string $filename Filename of the download
* @param integer $kbps Max download speed in KiB/s
*/
public static function download($file, $content_type = null, $filename = null, $kbps = 0) {
// Redefine vars
$file = (string) $file;
$content_type = ($content_type === null) ? null : (string) $content_type;
$filename = ($filename === null) ? null : (string) $filename;
$kbps = (int) $kbps;
// Check that the file exists and that its readable
if (file_exists($file) === false || is_readable($file) === false) {
throw new RuntimeException(vsprintf("%s(): Failed to open stream.", array(__METHOD__)));
}
// Empty output buffers
while (ob_get_level() > 0) ob_end_clean();
// Send headers
if ($content_type === null) $content_type = File::mime($file);
if ($filename === null) $filename = basename($file);
header('Content-type: ' . $content_type);
header('Content-Disposition: attachment; filename="' . $filename . '"');
header('Content-Length: ' . filesize($file));
// Read file and write it to the output
@set_time_limit(0);
if ($kbps === 0) {
readfile($file);
} else {
$handle = fopen($file, 'r');
while ( ! feof($handle) && !connection_aborted()) {
$s = microtime(true);
echo fread($handle, round($kbps * 1024));
if (($wait = 1e6 - (microtime(true) - $s)) > 0) usleep($wait);
}
fclose($handle);
}
exit();
}
/**
* Display a file in the browser.
*
* <code>
* File::display('filename.txt');
* </code>
*
* @param string $file Full path to file
* @param string $content_type Content type of the file
* @param string $filename Filename of the download
*/
public static function display($file, $content_type = null, $filename = null) {
// Redefine vars
$file = (string) $file;
$content_type = ($content_type === null) ? null : (string) $content_type;
$filename = ($filename === null) ? null : (string) $filename;
// Check that the file exists and that its readable
if (file_exists($file) === false || is_readable($file) === false) {
throw new RuntimeException(vsprintf("%s(): Failed to open stream.", array(__METHOD__)));
}
// Empty output buffers
while (ob_get_level() > 0) ob_end_clean();
// Send headers
if ($content_type === null) $content_type = File::mime($file);
if($filename === null) $filename = basename($file);
header('Content-type: ' . $content_type);
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Length: ' . filesize($file));
// Read file and write to output
readfile($file);
exit();
}
/**
* Tests whether a file is writable for anyone.
*
* <code>
* if (File::writable('filename.txt')) {
* // do something...
* }
* </code>
*
* @param string $file File to check
* @return boolean
*/
public static function writable($file) {
// Redefine vars
$file = (string) $file;
// Is file exists ?
if ( ! file_exists($file)) throw new RuntimeException(vsprintf("%s(): The file '{$file}' doesn't exist", array(__METHOD__)));
// Gets file permissions
$perms = fileperms($file);
// Is writable ?
if (is_writable($file) || ($perms & 0x0080) || ($perms & 0x0010) || ($perms & 0x0002)) return true;
}
}

View File

@@ -1,429 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Form Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum based on Kohana Form helper
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Form {
/**
* The registered custom macros.
*
* @var array
*/
public static $macros = array();
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Registers a custom macro.
*
* <code>
*
* // Registering a Form macro
* Form::macro('my_field', function() {
* return '<input type="text" name="my_field">';
* });
*
* // Calling a custom Form macro
* echo Form::my_field();
*
*
* // Registering a Form macro with parameters
* Form::macro('my_field', function($value = '') {
* return '<input type="text" name="my_field" value="'.$value.'">';
* });
*
* // Calling a custom Form macro with parameters
* echo Form::my_field('Monstra');
*
* </code>
*
* @param string $name Name
* @param Closure $macro Macro
*/
public static function macro($name, $macro) {
Form::$macros[$name] = $macro;
}
/**
* Create an opening HTML form tag.
*
* <code>
* // Form will submit back to the current page using POST
* echo Form::open();
*
* // Form will submit to 'search' using GET
* echo Form::open('search', array('method' => 'get'));
*
* // When "file" inputs are present, you must include the "enctype"
* echo Form::open(null, array('enctype' => 'multipart/form-data'));
* </code>
*
* @param mixed $action Form action, defaults to the current request URI.
* @param array $attributes HTML attributes.
* @uses Url::base
* @uses Html::attributes
* @return string
*/
public static function open($action = null, array $attributes = null) {
if ( ! $action) {
// Submits back to the current url
$action = '';
} elseif (strpos($action, '://') === false) {
// Make the URI absolute
$action = Url::base() . '/' . $action;
}
// Add the form action to the attributes
$attributes['action'] = $action;
if ( ! isset($attributes['method'])) {
// Use POST method
$attributes['method'] = 'post';
}
return '<form'.Html::attributes($attributes).'>';
}
/**
* Create a form input.
* Text is default input type.
*
* <code>
* echo Form::input('username', $username);
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param array $attributes HTML attributes
* @uses Html::attributes
* @return string
*/
public static function input($name, $value = null, array $attributes = null) {
// Set the input name
$attributes['name'] = $name;
// Set the input id
$attributes['id'] = (isset($attributes['id']))?$attributes['id']:$name;
// Set the input value
$attributes['value'] = $value;
if ( ! isset($attributes['type'])) {
// Default type is text
$attributes['type'] = 'text';
}
return '<input'.Html::attributes($attributes).' />';
}
/**
* Create a hidden form input.
*
* <code>
* echo Form::hidden('user_id', $user_id);
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function hidden($name, $value = null, array $attributes = null) {
// Set the input type
$attributes['type'] = 'hidden';
return Form::input($name, $value, $attributes);
}
/**
* Creates a password form input.
*
* <code>
* echo Form::password('password');
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function password($name, $value = null, array $attributes = null) {
// Set the input type
$attributes['type'] = 'password';
return Form::input($name, $value, $attributes);
}
/**
* Creates a file upload form input.
*
* <code>
* echo Form::file('image');
* </code>
*
* @param string $name Input name
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function file($name, array $attributes = null) {
// Set the input type
$attributes['type'] = 'file';
return Form::input($name, null, $attributes);
}
/**
* Creates a checkbox form input.
*
* <code>
* echo Form::checkbox('i_am_not_a_robot');
* </code>
*
* @param string $name Input name
* @param string $input Input value
* @param boolean $checked Checked status
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function checkbox($name, $value = null, $checked = false, array $attributes = null) {
// Set the input type
$attributes['type'] = 'checkbox';
if ($checked === true) {
// Make the checkbox active
$attributes['checked'] = 'checked';
}
return Form::input($name, $value, $attributes);
}
/**
* Creates a radio form input.
*
* <code>
* echo Form::radio('i_am_not_a_robot');
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param boolean $checked Checked status
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function radio($name, $value = null, $checked = null, array $attributes = null) {
// Set the input type
$attributes['type'] = 'radio';
if ($checked === true) {
// Make the radio active
$attributes['checked'] = 'checked';
}
return Form::input($name, $value, $attributes);
}
/**
* Creates a textarea form input.
*
* <code>
* echo Form::textarea('text', $text);
* </code>
*
* @param string $name Name
* @param string $body Body
* @param array $attributes HTML attributes
* @uses Html::attributes
* @return string
*/
public static function textarea($name, $body = '', array $attributes = null) {
// Set the input name
$attributes['name'] = $name;
// Set the input id
$attributes['id'] = (isset($attributes['id']))?$attributes['id']:$name;
return '<textarea'.Html::attributes($attributes).'>'.$body.'</textarea>';
}
/**
* Creates a select form input.
*
* <code>
* echo Form::select('themes', array('default', 'classic', 'modern'));
* </code>
*
* @param string $name Name
* @param array $options Options array
* @param string $selected Selected option
* @param array $attributes HTML attributes
* @uses Html::attributes
* @return string
*/
public static function select($name, array $options = null, $selected = null, array $attributes = null) {
// Set the input name
$attributes['name'] = $name;
// Set the input id
$attributes['id'] = (isset($attributes['id']))?$attributes['id']:$name;
$options_output = '';
foreach ($options as $value => $name) {
if ($selected == $value) $current = ' selected '; else $current = '';
$options_output .= '<option value="'.$value.'" '.$current.'>'.$name.'</option>';
}
return '<select'.Html::attributes($attributes).'>'.$options_output.'</select>';
}
/**
* Creates a submit form input.
*
* <code>
* echo Form::submit('save', 'Save');
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param array $attributes HTML attributes
* @uses Form::input
* @return string
*/
public static function submit($name, $value, array $attributes = null) {
// Set the input type
$attributes['type'] = 'submit';
return Form::input($name, $value, $attributes);
}
/**
* Creates a button form input.
*
* <code>
* echo Form::button('save', 'Save Profile', array('type' => 'submit'));
* </code>
*
* @param string $name Input name
* @param string $value Input value
* @param array $attributes HTML attributes
* @uses Html::attributes
* @return string
*/
public static function button($name, $body, array $attributes = null) {
// Set the input name
$attributes['name'] = $name;
return '<button'.Html::attributes($attributes).'>'.$body.'</button>';
}
/**
* Creates a form label.
*
* <code>
* echo Form::label('username', 'Username');
* </code>
*
* @param string $input Target input
* @param string $text Label text
* @param array $attributes HTML attributes
* @uses Html::attributes
* @return string
*/
public static function label($input, $text, array $attributes = null) {
// Set the label target
$attributes['for'] = $input;
return '<label'.Html::attributes($attributes).'>'.$text.'</label>';
}
/**
* Create closing form tag.
*
* <code>
* echo Form::close();
* </code>
*
* @return string
*/
public static function close() {
return '</form>';
}
/**
* Dynamically handle calls to custom macros.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters) {
if (isset(Form::$macros[$method])) {
return call_user_func_array(Form::$macros[$method], $parameters);
}
throw new RuntimeException("Method [$method] does not exist.");
}
}

View File

@@ -1,327 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* HTML Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum based on Kohana HTML helper
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Html {
/**
* Preferred order of attributes
*
* @var array
*/
public static $attribute_order = array (
'action', 'method', 'type', 'id', 'name', 'value',
'href', 'src', 'width', 'height', 'cols', 'rows',
'size', 'maxlength', 'rel', 'media', 'accept-charset',
'accept', 'tabindex', 'accesskey', 'alt', 'title', 'class',
'style', 'selected', 'checked', 'readonly', 'disabled',
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Registers a custom macro.
*
* <code>
*
* // Registering a Htmlk macro
* Html::macro('my_element', function() {
* return '<element id="monstra">';
* });
*
* // Calling a custom Html macro
* echo Html::my_element();
*
*
* // Registering a Html macro with parameters
* Html::macro('my_element', function(id = '') {
* return '<element id="'.$id.'">';
* });
*
* // Calling a custom Html macro with parameters
* echo Html::my_element('monstra');
*
* </code>
*
* @param string $name Name
* @param Closure $macro Macro
*/
public static function macro($name, $macro) {
Html::$macros[$name] = $macro;
}
/**
* Convert special characters to HTML entities. All untrusted content
* should be passed through this method to prevent XSS injections.
*
* <code>
* echo Html::chars($username);
* </code>
*
* @param string $value String to convert
* @param boolean $double_encode Encode existing entities
* @return string
*/
public static function chars($value, $double_encode = true) {
return htmlspecialchars((string)$value, ENT_QUOTES, 'utf-8', $double_encode);
}
/**
* Compiles an array of HTML attributes into an attribute string.
* Attributes will be sorted using Html::$attribute_order for consistency.
*
* <code>
* echo '<div'.Html::attributes($attrs).'>'.$content.'</div>';
* </code>
*
* @param array $attributes Attribute list
* @return string
*/
public static function attributes(array $attributes = null) {
if (empty($attributes)) return '';
// Init var
$sorted = array();
foreach (Html::$attribute_order as $key) {
if (isset($attributes[$key])) {
// Add the attribute to the sorted list
$sorted[$key] = $attributes[$key];
}
}
// Combine the sorted attributes
$attributes = $sorted + $attributes;
$compiled = '';
foreach ($attributes as $key => $value) {
if ($value === NULL) {
// Skip attributes that have NULL values
continue;
}
if (is_int($key)) {
// Assume non-associative keys are mirrored attributes
$key = $value;
}
// Add the attribute value
$compiled .= ' '.$key.'="'.Html::chars($value).'"';
}
return $compiled;
}
/**
* Create br tags
*
* <code>
* echo Html::br(2);
* </code>
*
* @param integer $num Count of line break tag
* @return string
*/
public static function br($num = 1) {
return str_repeat("<br />",(int)$num);
}
/**
* Create &nbsp;
*
* <code>
* echo Html::nbsp(2);
* </code>
*
* @param integer $num Count of &nbsp;
* @return string
*/
public static function nbsp($num = 1) {
return str_repeat("&nbsp;", (int)$num);
}
/**
* Create an arrow
*
* <code>
* echo Html::arrow('right');
* </code>
*
* @param string $direction Arrow direction [up,down,left,right]
* @param boolean $render If this option is true then render html object else return it
* @return string
*/
public static function arrow($direction) {
switch ($direction) {
case "up": $output = '<span class="arrow">&uarr;</span>'; break;
case "down": $output = '<span class="arrow">&darr;</span>'; break;
case "left": $output = '<span class="arrow">&larr;</span>'; break;
case "right": $output = '<span class="arrow">&rarr;</span>'; break;
}
return $output;
}
/**
* Create HTML link anchor.
*
* <code>
* echo Html::anchor('About', 'http://sitename.com/about');
* </code>
*
* @param string $title Anchor title
* @param string $url Anchor url
* @param array $attributes Anchor attributes
* @uses Html::attributes
* @return string
*/
public static function anchor($title, $url = null, array $attributes = null) {
// Add link
if ($url !== null) $attributes['href'] = $url;
return '<a'.Html::attributes($attributes).'>'.$title.'</a>';
}
/**
* Create HTML <h> tag
*
* <code>
* echo Html::heading('Title', 1);
* </code>
*
* @param string $title Text
* @param integer $h Number [1-6]
* @param array $attributes Heading attributes
* @uses Html::attributes
* @return string
*/
public static function heading($title, $h = 1, array $attributes = null) {
$output = '<h'.(int)$h.Html::attributes($attributes).'>'.$title.'</h'.(int)$h.'>';
return $output;
}
/**
* Generate document type declarations
*
* <code>
* echo Html::doctype('html5');
* </code>
*
* @param string $type Doctype to generated
* @return mixed
*/
public static function doctype($type = 'html5') {
$doctypes = array('xhtml11' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">',
'xhtml1-strict' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">',
'xhtml1-trans' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">',
'xhtml1-frame' => '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">',
'html5' => '<!DOCTYPE html>',
'html4-strict' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">',
'html4-trans' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">',
'html4-frame' => '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">');
if (isset($doctypes[$type])) return $doctypes[$type]; else return false;
}
/**
* Create image
*
* <code>
* echo Html::image('data/files/pic1.jpg');
* </code>
*
* @param array $attributes Image attributes
* @param string $file File
* @uses Url::base
* @return string
*/
public static function image($file, array $attributes = null) {
if (strpos($file, '://') === FALSE) {
$file = Url::base().'/'.$file;
}
// Add the image link
$attributes['src'] = $file;
$attributes['alt'] = (isset($attributes['alt'])) ? $attributes['alt'] : pathinfo($file, PATHINFO_FILENAME);
return '<img'.Html::attributes($attributes).' />';
}
/**
* Convert html to plain text
*
* <code>
* echo Html::toText('test');
* </code>
*
* @param string $str String
* @return string
*/
public static function toText($str) {
return htmlspecialchars($str, ENT_QUOTES, 'utf-8');
}
/**
* Dynamically handle calls to custom macros.
*
* @param string $method
* @param array $parameters
* @return mixed
*/
public static function __callStatic($method, $parameters) {
if (isset(Html::$macros[$method])) {
return call_user_func_array(Html::$macros[$method], $parameters);
}
throw new RuntimeException("Method [$method] does not exist.");
}
}

View File

@@ -1,673 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Image Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Image {
/**
* Resizing contraint.
*
* @var integer
*/
const AUTO = 1;
/**
* Resizing contraint.
*
* @var integer
*/
const WIDTH = 2;
/**
* Resizing contraint.
*
* @var integer
*/
const HEIGHT = 3;
/**
* Watermark position.
*/
const TOP_LEFT = 4;
/**
* Watermark position.
*/
const TOP_RIGHT = 5;
/**
* Watermark position.
*/
const BOTTOM_LEFT = 6;
/**
* Watermark position.
*/
const BOTTOM_RIGHT = 7;
/**
* Watermark position.
*/
const CENTER = 8;
/**
* Holds info about the image.
*
* @var array
*/
protected $image_info;
/**
* Get value
*
* @param string $key Key
* @return mixed
*/
public function __get($key) {
if (array_key_exists($key, $this->image_info)) return $this->image_info[$key];
}
/**
* Set value for specific key
*
* @param string $key Key
* @param mixed $value Value
*/
public function __set($key, $value) {
$this->image_info[$key] = $value;
}
/**
* Image factory.
*
* <code>
* $image = Image::factory('original.png');
* </code>
*
* @param string $filename Filename
* @return Image
*/
public static function factory($filename) {
return new Image($filename);
}
/**
* Construct
*
* @param string $file Filename
*/
public function __construct($file) {
// Redefine vars
$file = (string) $file;
// Check if the file exists
if (file_exists($file)) {
// Extract attributes of the image file
list($this->width, $this->height, $type, $a) = getimagesize($file);
// Save image type
$this->type = $type;
// Create a new image
$this->image = $this->createImage($file, $type);
} else {
throw new RuntimeException(vsprintf("%s(): The file '{$file}' doesn't exist", array(__METHOD__)));
}
}
/**
* Create a new image from file.
*
* @param string $file Path to the image file
* @param integer $type Image type
* @return resource
*/
protected function createImage($file, $type) {
// Create image from file
switch($type) {
case IMAGETYPE_JPEG:
return imagecreatefromjpeg($file);
break;
case IMAGETYPE_GIF:
return imagecreatefromgif($file);
break;
case IMAGETYPE_PNG:
return imagecreatefrompng($file);
break;
default:
throw new RuntimeException(vsprintf("%s(): Unable to open '%s'. Unsupported image type.", array(__METHOD__, $type)));
}
}
/**
* Resizes the image to the chosen size.
*
* <code>
* Image::factory('original.png')->resize(800, 600)->save('edited.png');
* </code>
*
* @param integer $width Width of the image
* @param integer $height Height of the image
* @param integer $aspect_ratio Aspect ratio (Image::AUTO Image::WIDTH Image::HEIGHT)
* @return Image
*/
public function resize($width, $height = null, $aspect_ratio = null) {
// Redefine vars
$width = (int) $width;
$height = ($height === null) ? null : (int) $height;
$aspect_ratio = ($aspect_ratio === null) ? null : (int) $aspect_ratio;
// Resizes the image to {$width}% of the original size
if ($height === null) {
$new_width = round($this->width * ($width / 100));
$new_height = round($this->height * ($width / 100));
} else {
// Resizes the image to the smalles possible dimension while maintaining aspect ratio
if ($aspect_ratio === Image::AUTO) {
// Calculate smallest size based on given height and width while maintaining aspect ratio
$percentage = min(($width / $this->width), ($height / $this->height));
$new_width = round($this->width * $percentage);
$new_height = round($this->height * $percentage);
// Resizes the image using the width to maintain aspect ratio
} else if ($aspect_ratio === Image::WIDTH) {
// Base new size on given width while maintaining aspect ratio
$new_width = $width;
$new_height = round($this->height * ($width / $this->width));
// Resizes the image using the height to maintain aspect ratio
} else if($aspect_ratio === Image::HEIGHT) {
// Base new size on given height while maintaining aspect ratio
$new_width = round($this->width * ($height / $this->height));
$new_height = $height;
// Resizes the image to a dimension of {$width}x{$height} pixels while ignoring the aspect ratio
} else {
$new_width = $width;
$new_height = $height;
}
}
// Create a new true color image width new width and height
$resized = imagecreatetruecolor($new_width, $new_height);
// Copy and resize part of an image with resampling
imagecopyresampled($resized, $this->image, 0, 0, 0, 0, $new_width, $new_height, $this->width, $this->height);
// Destroy an image
imagedestroy($this->image);
// Create a new true color image width new width and height
$this->image = imagecreatetruecolor($new_width, $new_height);
// Copy and resize part of an image with resampling
imagecopyresampled($this->image, $resized, 0, 0, 0, 0, $new_width, $new_height, $new_width, $new_height);
// Destroy an image
imagedestroy($resized);
// Save new width and height
$this->width = $new_width;
$this->height = $new_height;
return $this;
}
/**
* Crops the image
*
* <code>
* Image::factory('original.png')->crop(800, 600, 0, 0)->save('edited.png');
* </code>
*
* @param integer $width Width of the crop
* @param integer $height Height of the crop
* @param integer $x The X coordinate of the cropped region's top left corner
* @param integer $y The Y coordinate of the cropped region's top left corner
* @return Image
*/
public function crop($width, $height, $x, $y) {
// Redefine vars
$width = (int) $width;
$height = (int) $height;
$x = (int) $x;
$y = (int) $y;
// Calculate
if ($x + $width > $this->width) $width = $this->width - $x;
if ($y + $height > $this->height) $height = $this->height - $y;
if ($width <= 0 || $height <= 0) return false;
// Create a new true color image
$crop = imagecreatetruecolor($width, $height);
// Copy and resize part of an image with resampling
imagecopyresampled($crop, $this->image, 0, 0, $x, $y, $this->width, $this->height, $this->width, $this->height);
// Destroy an image
imagedestroy($this->image);
// Create a new true color image
$this->image = imagecreatetruecolor($width, $height);
// Copy and resize part of an image with resampling
imagecopyresampled($this->image, $crop, 0, 0, 0, 0, $width, $height, $width, $height);
// Destroy an image
imagedestroy($crop);
// Save new width and height
$this->width = $width;
$this->height = $height;
return $this;
}
/**
* Adds a watermark to the image.
*
* @param string $file Path to the image file
* @param integer $position Position of the watermark
* @param integer $opacity Opacity of the watermark in percent
* @return Image
*/
public function watermark($file, $position = null, $opacity = 100) {
// Check if the image exists
if ( ! file_exists($file)) {
throw new RuntimeException(vsprintf("%s(): The image file ('%s') does not exist.", array(__METHOD__, $file)));
}
$watermark = $this->createImage($file, $this->type);
$watermarkW = imagesx($watermark);
$watermarkH = imagesy($watermark);
// Make sure that opacity is between 0 and 100
$opacity = max(min((int) $opacity, 100), 0);
if($opacity < 100) {
if(GD_BUNDLED === 0) {
throw new RuntimeException(vsprintf("%s(): Setting watermark opacity requires the 'imagelayereffect' function which is only available in the bundled version of GD.", array(__METHOD__)));
}
// Convert alpha to 0-127
$alpha = min(round(abs(($opacity * 127 / 100) - 127)), 127);
$transparent = imagecolorallocatealpha($watermark, 0, 0, 0, $alpha);
imagelayereffect($watermark, IMG_EFFECT_OVERLAY);
imagefilledrectangle($watermark, 0, 0, $watermarkW, $watermarkH, $transparent);
}
// Position the watermark.
switch($position) {
case Image::TOP_RIGHT:
$x = imagesx($this->image) - $watermarkW;
$y = 0;
break;
case Image::BOTTOM_LEFT:
$x = 0;
$y = imagesy($this->image) - $watermarkH;
break;
case Image::BOTTOM_RIGHT:
$x = imagesx($this->image) - $watermarkW;
$y = imagesy($this->image) - $watermarkH;
break;
case Image::CENTER:
$x = (imagesx($this->image) / 2) - ($watermarkW / 2);
$y = (imagesy($this->image) / 2) - ($watermarkH / 2);
break;
default:
$x = 0;
$y = 0;
}
imagealphablending($this->image, true);
imagecopy($this->image, $watermark, $x, $y, 0, 0, $watermarkW, $watermarkH);
imagedestroy($watermark);
// Return Image
return $this;
}
/**
* Convert image into grayscale
*
* <code>
* Image::factory('original.png')->grayscale()->save('edited.png');
* </code>
*
* @return Image
*/
public function grayscale() {
imagefilter($this->image, IMG_FILTER_GRAYSCALE);
return $this;
}
/**
* Convert image into sepia
*
* <code>
* Image::factory('original.png')->sepia()->save('edited.png');
* </code>
*
* @return Image
*/
public function sepia() {
imagefilter($this->image, IMG_FILTER_GRAYSCALE);
imagefilter($this->image, IMG_FILTER_COLORIZE, 112, 66, 20);
return $this;
}
/**
* Convert image into brightness
*
* <code>
* Image::factory('original.png')->brightness(60)->save('edited.png');
* </code>
*
* @param integer $level Level. From -255(min) to 255(max)
* @return Image
*/
public function brightness($level = 0) {
imagefilter($this->image, IMG_FILTER_BRIGHTNESS, (int)$level);
return $this;
}
/**
* Convert image into colorize
*
* <code>
* Image::factory('original.png')->colorize(60, 0, 0)->save('edited.png');
* </code>
*
* @param integer $red Red
* @param integer $green Green
* @param integer $blue Blue
* @return Image
*/
public function colorize($red, $green, $blue) {
imagefilter($this->image, IMG_FILTER_COLORIZE, (int)$red, (int)$green, (int)$blue);
return $this;
}
/**
* Convert image into contrast
*
* <code>
* Image::factory('original.png')->contrast(60)->save('edited.png');
* </code>
*
* @param integer $level Level. From -100(max) to 100(min) note the direction!
* @return Image
*/
public function contrast($level) {
imagefilter($this->image, IMG_FILTER_CONTRAST, (int)$level);
return $this;
}
/**
* Creates a color based on a hex value.
*
* @param string $hex Hex code of the color
* @param integer $alpha Alpha. Default is 100
* @param boolean $returnRGB FALSE returns a color identifier, TRUE returns a RGB array
* @return integer
*/
protected function createColor($hex, $alpha = 100, $return_rgb = false) {
// Redefine vars
$hex = (string) $hex;
$alpha = (int) $alpha;
$return_rgb = (bool) $return_rgb;
$hex = str_replace('#', '', $hex);
if (preg_match('/^([a-f0-9]{3}){1,2}$/i', $hex) === 0) {
throw new RuntimeException(vsprintf("%s(): Invalid color code ('%s').", array(__METHOD__, $hex)));
}
if (strlen($hex) === 3) {
$r = hexdec(str_repeat(substr($hex, 0, 1), 2));
$g = hexdec(str_repeat(substr($hex, 1, 1), 2));
$b = hexdec(str_repeat(substr($hex, 2, 1), 2));
} else {
$r = hexdec(substr($hex, 0, 2));
$g = hexdec(substr($hex, 2, 2));
$b = hexdec(substr($hex, 4, 2));
}
if ($return_rgb === true) {
return array('r' => $r, 'g' => $g, 'b' => $b);
} else {
// Convert alpha to 0-127
$alpha = min(round(abs(($alpha * 127 / 100) - 127)), 127);
return imagecolorallocatealpha($this->image, $r, $g, $b, $alpha);
}
}
/**
* Rotates the image using the given angle in degrees.
*
* <code>
* Image::factory('original.png')->rotate(90)->save('edited.png');
* </code>
*
* @param integer $degrees Degrees to rotate the image
* @return Image
*/
public function rotate($degrees) {
if (GD_BUNDLED === 0) {
throw new RuntimeException(vsprintf("%s(): This method requires the 'imagerotate' function which is only available in the bundled version of GD.", array(__METHOD__)));
}
// Redefine vars
$degrees = (int) $degrees;
// Get image width and height
$width = imagesx($this->image);
$height = imagesy($this->image);
// Allocate a color for an image
$transparent = imagecolorallocatealpha($this->image, 0, 0, 0, 127);
// Rotate gif image
if ($this->image_info['type'] === IMAGETYPE_GIF) {
// Create a new true color image
$temp = imagecreatetruecolor($width, $height);
// Flood fill
imagefill($temp, 0, 0, $transparent);
// Copy part of an image
imagecopy($temp, $this->image, 0, 0, 0, 0, $width, $height);
// Destroy an image
imagedestroy($this->image);
// Save temp image
$this->image = $temp;
}
// Rotate an image with a given angle
$this->image = imagerotate($this->image, (360 - $degrees), $transparent);
// Define a color as transparent
imagecolortransparent($this->image, $transparent);
return $this;
}
/**
* Adds a border to the image.
*
* <code>
* Image::factory('original.png')->border('#000', 5)->save('edited.png');
* </code>
*
* @param string $color Hex code for the color
* @param integer $thickness Thickness of the frame in pixels
* @return Image
*/
public function border($color = '#000', $thickness = 5) {
// Redefine vars
$color = (string) $color;
$thickness = (int) $thickness;
// Get image width and height
$width = imagesx($this->image);
$height = imagesy($this->image);
// Creates a color based on a hex value
$color = $this->createColor($color);
// Create border
for ($i = 0; $i < $thickness; $i++) {
if ($i < 0) {
$x = $width + 1;
$y = $hidth + 1;
} else {
$x = --$width;
$y = --$height;
}
imagerectangle($this->image, $i, $i, $x, $y, $color);
}
return $this;
}
/**
* Save image
*
* <code>
* Image::factory('original.png')->save('edited.png');
* </code>
*
* @param string $dest Desitination location of the file
* @param integer $quality Image quality. Default is 100
* @return Image
*/
public function save($file, $quality = 100) {
// Redefine vars
$file = (string) $file;
$quality = (int) $quality;
$path_info = pathinfo($file);
if ( ! is_writable($path_info['dirname'])) {
throw new RuntimeException(vsprintf("%s(): '%s' is not writable.", array(__METHOD__, $path_info['dirname'])));
}
// Make sure that quality is between 0 and 100
$quality = max(min((int) $quality, 100), 0);
// Save image
switch ($path_info['extension']) {
case 'jpg':
case 'jpeg':
imagejpeg($this->image, $file, $quality);
break;
case 'gif':
imagegif($this->image, $file);
break;
case 'png':
imagealphablending($this->image, true);
imagesavealpha($this->image, true);
imagepng($this->image, $file, (9 - (round(($quality / 100) * 9))));
break;
default:
throw new RuntimeException(vsprintf("%s(): Unable to save to '%s'. Unsupported image format.", array(__METHOD__, $path_info['extension'])));
}
// Return Image
return $this;
}
/**
* Destructor
*/
public function __destruct() {
imagedestroy($this->image);
}
}

View File

@@ -1,238 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Inflector Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Inflector {
/**
* Plural rules
*
* @var array
*/
protected static $plural_rules = array(
'/^(ox)$/' => '\1\2en', // ox
'/([m|l])ouse$/' => '\1ice', // mouse, louse
'/(matr|vert|ind)ix|ex$/' => '\1ices', // matrix, vertex, index
'/(x|ch|ss|sh)$/' => '\1es', // search, switch, fix, box, process, address
'/([^aeiouy]|qu)y$/' => '\1ies', // query, ability, agency
'/(hive)$/' => '\1s', // archive, hive
'/(?:([^f])fe|([lr])f)$/' => '\1\2ves', // half, safe, wife
'/sis$/' => 'ses', // basis, diagnosis
'/([ti])um$/' => '\1a', // datum, medium
'/(p)erson$/' => '\1eople', // person, salesperson
'/(m)an$/' => '\1en', // man, woman, spokesman
'/(c)hild$/' => '\1hildren', // child
'/(buffal|tomat)o$/' => '\1\2oes', // buffalo, tomato
'/(bu|campu)s$/' => '\1\2ses', // bus, campus
'/(alias|status|virus)$/' => '\1es', // alias
'/(octop)us$/' => '\1i', // octopus
'/(ax|cris|test)is$/' => '\1es', // axis, crisis
'/s$/' => 's', // no change (compatibility)
'/$/' => 's',
);
/**
* Singular rules
*
* @var array
*/
protected static $singular_rules = array(
'/(matr)ices$/' => '\1ix',
'/(vert|ind)ices$/' => '\1ex',
'/^(ox)en/' => '\1',
'/(alias)es$/' => '\1',
'/([octop|vir])i$/' => '\1us',
'/(cris|ax|test)es$/' => '\1is',
'/(shoe)s$/' => '\1',
'/(o)es$/' => '\1',
'/(bus|campus)es$/' => '\1',
'/([m|l])ice$/' => '\1ouse',
'/(x|ch|ss|sh)es$/' => '\1',
'/(m)ovies$/' => '\1\2ovie',
'/(s)eries$/' => '\1\2eries',
'/([^aeiouy]|qu)ies$/' => '\1y',
'/([lr])ves$/' => '\1f',
'/(tive)s$/' => '\1',
'/(hive)s$/' => '\1',
'/([^f])ves$/' => '\1fe',
'/(^analy)ses$/' => '\1sis',
'/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$/' => '\1\2sis',
'/([ti])a$/' => '\1um',
'/(p)eople$/' => '\1\2erson',
'/(m)en$/' => '\1an',
'/(s)tatuses$/' => '\1\2tatus',
'/(c)hildren$/' => '\1\2hild',
'/(n)ews$/' => '\1\2ews',
'/([^us])s$/' => '\1',
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Returns a camelized string from a string using underscore syntax.
*
* <code>
* // "some_text_here" becomes "SomeTextHere"
* echo Inflector::camelize('some_text_here');
* </code>
*
* @param string $string Word to camelize.
* @return string Camelized word.
*/
public static function camelize($string) {
// Redefine vars
$string = (string) $string;
return str_replace(' ', '', ucwords(str_replace('_', ' ', $string)));
}
/**
* Returns a string using underscore syntax from a camelized string.
*
* <code>
* // "SomeTextHere" becomes "some_text_here"
* echo Inflector::underscore('SomeTextHere');
* </code>
*
* @param string $string CamelCased word
* @return string Underscored version of the $string
*/
public static function underscore($string) {
// Redefine vars
$string = (string) $string;
return strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $string));
}
/**
* Returns a humanized string from a string using underscore syntax.
*
* <code>
* // "some_text_here" becomes "Some text here"
* echo Inflector::humanize('some_text_here');
* </code>
*
* @param string $string String using underscore syntax.
* @return string Humanized version of the $string
*/
public static function humanize($string) {
// Redefine vars
$string = (string) $string;
return ucfirst(strtolower(str_replace('_', ' ', $string)));
}
/**
* Returns ordinalize number.
*
* <code>
* // 1 becomes 1st
* echo Inflector::ordinalize(1);
* </code>
*
* @param integer $number Number to ordinalize
* @return string
*/
public static function ordinalize($number) {
if ( ! is_numeric($number)) {
return $number;
}
if (in_array(($number % 100), range(11, 13))) {
return $number . 'th';
} else {
switch ($number % 10) {
case 1: return $number . 'st'; break;
case 2: return $number . 'nd'; break;
case 3: return $number . 'rd'; break;
default: return $number . 'th'; break;
}
}
}
/**
* Returns the plural version of the given word
*
* <code>
* echo Inflector::pluralize('cat');
* </code>
*
* @param string $word Word to pluralize
* @return string
*/
public static function pluralize($word) {
$result = (string) $word;
foreach (Inflector::$plural_rules as $rule => $replacement) {
if (preg_match($rule, $result)) {
$result = preg_replace($rule, $replacement, $result);
break;
}
}
return $result;
}
/**
* Returns the singular version of the given word
*
* <code>
* echo Inflector::singularize('cats');
* </code>
*
* @param string $word Word to singularize
* @return string
*/
public static function singularize($word) {
$result = (string) $word;
foreach (Inflector::$singular_rules as $rule => $replacement) {
if (preg_match($rule, $result)) {
$result = preg_replace($rule, $replacement, $result);
break;
}
}
return $result;
}
}

View File

@@ -1,98 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Minify Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Minify {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Minify html
*
* <code>
* echo Minify::html($buffer);
* </code>
*
* @param string $buffer html
* @return string
*/
public static function html($buffer) {
return preg_replace('/^\\s+|\\s+$/m', '', $buffer);
}
/**
* Minify css
*
* <code>
* echo Minify::css($buffer);
* </code>
*
* @param string $buffer css
* @return string
*/
public static function css($buffer) {
// Remove comments
$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
// Remove tabs, spaces, newlines, etc.
$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
// Preserve empty comment after '>' http://www.webdevout.net/css-hacks#in_css-selectors
$buffer = preg_replace('@>/\\*\\s*\\*/@', '>/*keep*/', $buffer);
// Preserve empty comment between property and value
// http://css-discuss.incutio.com/?page=BoxModelHack
$buffer = preg_replace('@/\\*\\s*\\*/\\s*:@', '/*keep*/:', $buffer);
$buffer = preg_replace('@:\\s*/\\*\\s*\\*/@', ':/*keep*/', $buffer);
// Remove ws around { } and last semicolon in declaration block
$buffer = preg_replace('/\\s*{\\s*/', '{', $buffer);
$buffer = preg_replace('/;?\\s*}\\s*/', '}', $buffer);
// Remove ws surrounding semicolons
$buffer = preg_replace('/\\s*;\\s*/', ';', $buffer);
// Remove ws around urls
$buffer = preg_replace('/url\\(\\s*([^\\)]+?)\\s*\\)/x', 'url($1)', $buffer);
// Remove ws between rules and colons
$buffer = preg_replace('/\\s*([{;])\\s*([\\*_]?[\\w\\-]+)\\s*:\\s*(\\b|[#\'"])/x', '$1$2:$3', $buffer);
// Minimize hex colors
$buffer = preg_replace('/([^=])#([a-f\\d])\\2([a-f\\d])\\3([a-f\\d])\\4([\\s;\\}])/i', '$1#$2$3$4$5', $buffer);
// Replace any ws involving newlines with a single newline
$buffer = preg_replace('/[ \\t]*\\n+\\s*/', "\n", $buffer);
return $buffer;
}
}

View File

@@ -1,150 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Notification Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Notification {
/**
* Notifications session key
*
* @var string
*/
const SESSION_KEY = 'notifications';
/**
* Notifications array
*
* @var array
*/
private static $notifications = array();
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Returns a specific variable from the Notifications array.
*
* <code>
* echo Notification::get('success');
* echo Notification::get('errors');
* </code>
*
* @param string $key Variable name
* @return mixed
*/
public static function get($key) {
// Redefine arguments
$key = (string) $key;
// Return specific variable from the Notifications array
return isset(Notification::$notifications[$key]) ? Notification::$notifications[$key] : null;
}
/**
* Adds specific variable to the Notifications array.
*
* <code>
* Notification::set('success', 'Data has been saved with success!');
* Notification::set('errors', 'Data not saved!');
* </code>
*
* @param string $key Variable name
* @param mixed $value Variable value
*/
public static function set($key, $value) {
// Redefine arguments
$key = (string) $key;
// Save specific variable to the Notifications array
$_SESSION[Notification::SESSION_KEY][$key] = $value;
}
/**
* Adds specific variable to the Notifications array for current page.
*
* <code>
* Notification::setNow('success', 'Success!');
* </code>
*
* @param string $var Variable name
* @param mixed $value Variable value
*/
public static function setNow($key, $value) {
// Redefine arguments
$key = (string) $key;
// Save specific variable for current page only
Notification::$notifications[$key] = $value;
}
/**
* Clears the Notifications array.
*
* <code>
* Notification::clean();
* </code>
*
* Data that previous pages stored will not be deleted, just the data that
* this page stored itself.
*/
public static function clean() {
$_SESSION[Notification::SESSION_KEY] = array();
}
/**
* Initializes the Notification service.
*
* <code>
* Notification::init();
* </code>
*
* This will read notification/flash data from the $_SESSION variable and load it into
* the $this->previous array.
*/
public static function init() {
// Get notification/flash data...
if ( ! empty($_SESSION[Notification::SESSION_KEY]) && is_array($_SESSION[Notification::SESSION_KEY])) {
Notification::$notifications = $_SESSION[Notification::SESSION_KEY];
}
$_SESSION[Notification::SESSION_KEY] = array();
}
}

View File

@@ -1,213 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Number Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Number {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Convert bytes in 'kb','mb','gb','tb','pb'
*
* <code>
* echo Number::byteFormat(10000);
* </code>
*
* @param integer $size Data to convert
* @return string
*/
public static function byteFormat($size) {
// Redefine vars
$size = (int) $size;
$unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
return @round($size/pow(1024, ($i=floor(log($size, 1024)))), 2).' '.$unit[$i];
}
/**
* Converts a number into a more readable human-type number.
*
* <code>
* echo Number::quantity(7000); // 7K
* echo Number::quantity(7500); // 8K
* echo Number::quantity(7500, 1); // 7.5K
* </code>
*
* @param integer $num Num to convert
* @param integer $decimals Decimals
* @return string
*/
public static function quantity($num, $decimals = 0) {
// Redefine vars
$num = (int) $num;
$decimals = (int) $decimals;
if ($num >= 1000 && $num < 1000000) {
return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000)).'K';
} elseif ($num >= 1000000 && $num < 1000000000) {
return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000)).'M';
} elseif ($num >= 1000000000) {
return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000000)).'B';
}
return $num;
}
/**
* Checks if the value is between the minimum and maximum (min & max included).
*
* <code>
* if (Number::between(2, 10, 5)) {
* // do something...
* }
* </code>
*
* @param float $minimum The minimum.
* @param float $maximum The maximum.
* @param float $value The value to validate.
* @return boolean
*/
public static function between($minimum, $maximum, $value) {
return ((float) $value >= (float) $minimum && (float) $value <= (float) $maximum);
}
/**
* Checks the value for an even number.
*
* <code>
* if (Number::even(2)) {
* // do something...
* }
* </code>
*
* @param integer $value The value to validate.
* @return boolean
*/
public static function even($value) {
return (((int) $value % 2) == 0);
}
/**
* Checks if the value is greather than a given minimum.
*
* <code>
* if (Number::greaterThan(2, 10)) {
* // do something...
* }
* </code>
*
* @param float $minimum The minimum as a float.
* @param float $value The value to validate.
* @return boolean
*/
public static function greaterThan($minimum, $value) {
return ((float) $value > (float) $minimum);
}
/**
* Checks if the value is smaller than a given maximum.
*
* <code>
* if (Number::smallerThan(2, 10)) {
* // do something...
* }
* </code>
*
* @param integer $maximum The maximum.
* @param integer $value The value to validate.
* @return boolean
*/
public static function smallerThan($maximum, $value) {
return ((int) $value < (int) $maximum);
}
/**
* Checks if the value is not greater than or equal a given maximum.
*
* <code>
* if (Number::maximum(2, 10)) {
* // do something...
* }
* </code>
*
* @param integer $maximum The maximum.
* @param integer $value The value to validate.
* @return boolean
*/
public static function maximum($maximum, $value) {
return ((int) $value <= (int) $maximum);
}
/**
* Checks if the value is greater than or equal to a given minimum.
*
* <code>
* if (Number::minimum(2, 10)) {
* // do something...
* }
* </code>
*
* @param integer $minimum The minimum.
* @param integer $value The value to validate.
* @return boolean
*/
public static function minimum($minimum, $value) {
return ((int) $value >= (int) $minimum);
}
/**
* Checks the value for an odd number.
*
* <code>
* if (Number::odd(2)) {
* // do something...
* }
* </code>
*
* @param integer $value The value to validate.
* @return boolean
*/
public static function odd($value) {
return ! Number::even((int) $value);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,161 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Request Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Request {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Redirects the browser to a page specified by the $url argument.
*
* <code>
* Request::redirect('test');
* </code>
*
* @param string $url The URL
* @param integer $status Status
* @param integer $delay Delay
*/
public static function redirect($url, $status = 302, $delay = null){
// Redefine vars
$url = (string) $url;
$status = (int) $status;
// Status codes
$messages = array();
$messages[301] = '301 Moved Permanently';
$messages[302] = '302 Found';
// Is Headers sent ?
if (headers_sent()) {
echo "<script>document.location.href='" . $url . "';</script>\n";
} else {
// Redirect headers
Request::setHeaders('HTTP/1.1 ' . $status . ' ' . Arr::get($messages, $status, 302));
// Delay execution
if ($delay !== null) sleep((int) $delay);
// Redirect
Request::setHeaders("Location: $url");
// Shutdown request
Request::shutdown();
}
}
/**
* Set one or multiple headers.
*
* <code>
* Request::setHeaders('Location: http://site.com/');
* </code>
*
* @param mixed $headers String or array with headers to send.
*/
public static function setHeaders($headers) {
// Loop elements
foreach ((array) $headers as $header) {
// Set header
header((string) $header);
}
}
/**
* Get
*
* <code>
* $action = Request::get('action');
* </code>
*
* @param string $key Key
* @param mixed
*/
public static function get($key) {
return Arr::get($_GET, $key);
}
/**
* Post
*
* <code>
* $login = Request::post('login');
* </code>
*
* @param string $key Key
* @param mixed
*/
public static function post($key) {
return Arr::get($_POST, $key);
}
/**
* Returns whether this is an ajax request or not
*
* <code>
* if (Request::isAjax()) {
* // do something...
* }
* </code>
*
* @return boolean
*/
public static function isAjax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest';
}
/**
* Terminate request
*
* <code>
* Request::shutdown();
* </code>
*
*/
public static function shutdown() {
exit(0);
}
}

View File

@@ -1,109 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Response Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Response {
/**
* HTTP status codes and messages
*
* @var array
*/
public static $messages = array(
// Informational 1xx
100 => 'Continue',
101 => 'Switching Protocols',
// Success 2xx
200 => 'OK',
201 => 'Created',
202 => 'Accepted',
203 => 'Non-Authoritative Information',
204 => 'No Content',
205 => 'Reset Content',
206 => 'Partial Content',
// Redirection 3xx
300 => 'Multiple Choices',
301 => 'Moved Permanently',
302 => 'Found', // 1.1
303 => 'See Other',
304 => 'Not Modified',
305 => 'Use Proxy',
// 306 is deprecated but reserved
307 => 'Temporary Redirect',
// Client Error 4xx
400 => 'Bad Request',
401 => 'Unauthorized',
402 => 'Payment Required',
403 => 'Forbidden',
404 => 'Not Found',
405 => 'Method Not Allowed',
406 => 'Not Acceptable',
407 => 'Proxy Authentication Required',
408 => 'Request Timeout',
409 => 'Conflict',
410 => 'Gone',
411 => 'Length Required',
412 => 'Precondition Failed',
413 => 'Request Entity Too Large',
414 => 'Request-URI Too Long',
415 => 'Unsupported Media Type',
416 => 'Requested Range Not Satisfiable',
417 => 'Expectation Failed',
// Server Error 5xx
500 => 'Internal Server Error',
501 => 'Not Implemented',
502 => 'Bad Gateway',
503 => 'Service Unavailable',
504 => 'Gateway Timeout',
505 => 'HTTP Version Not Supported',
509 => 'Bandwidth Limit Exceeded'
);
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Set header status
*
* <code>
* Response::status(404);
* </code>
*
* @param integer $status Status code
*/
public static function status($status) {
if (array_key_exists($status, Response::$messages)) header('HTTP/1.1 ' . $status . ' ' . Response::$messages[$status]);
}
}

View File

@@ -1,250 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Security module
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Security {
/**
* Key name for token storage
*
* @var string
*/
public static $token_name = 'security_token';
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Generate and store a unique token which can be used to help prevent
* [CSRF](http://wikipedia.org/wiki/Cross_Site_Request_Forgery) attacks.
*
* <code>
* $token = Security::token();
* </code>
*
* You can insert this token into your forms as a hidden field:
*
* <code>
* echo Form::hidden('csrf', Security::token());
* </code>
*
* This provides a basic, but effective, method of preventing CSRF attacks.
*
* @param boolean $new force a new token to be generated?. Default is false
* @return string
*/
public static function token($new = false) {
// Get the current token
$token = Session::get(Security::$token_name);
// Create a new unique token
if ($new === true or ! $token) {
// Generate a new unique token
$token = sha1(uniqid(mt_rand(), true));
// Store the new token
Session::set(Security::$token_name, $token);
}
// Return token
return $token;
}
/**
* Check that the given token matches the currently stored security token.
*
* <code>
* if (Security::check($token)) {
* // Pass
* }
* </code>
*
* @param string $token token to check
* @return boolean
*/
public static function check($token) {
return Security::token() === $token;
}
/**
* Encrypt password
*
* <code>
* $encrypt_password = Security::encryptPassword('password');
* </code>
*
* @param string $password Password to encrypt
*/
public static function encryptPassword($password) {
return md5(md5(trim($password) . MONSTRA_PASSWORD_SALT));
}
/**
* Create safe name. Use to create safe username, filename, pagename.
*
* <code>
* $safe_name = Security::safeName('hello world');
* </code>
*
* @param string $str String
* @param string $delimiter String delimiter
* @param boolean $lowercase String Lowercase
* @return string
*/
public static function safeName($str, $delimiter = '-', $lowercase = false) {
// Redefine vars
$str = (string) $str;
$delimiter = (string) $delimiter;
$lowercase = (bool) $lowercase;
$delimiter = (string) $delimiter;
// Remove tags
$str = filter_var($str, FILTER_SANITIZE_STRING);
// Decode all entities to their simpler forms
$str = html_entity_decode($str, ENT_QUOTES, 'UTF-8');
// Reserved characters (RFC 3986)
$reserved_characters = array(
'/', '?', ':', '@', '#', '[', ']',
'!', '$', '&', '\'', '(', ')', '*',
'+', ',', ';', '='
);
// Remove reserved characters
$str = str_replace($reserved_characters, ' ', $str);
// Set locale to en_US.UTF8
setlocale(LC_ALL, 'en_US.UTF8');
// Translit ua,ru => latin
$str = Text::translitIt($str);
// Convert string
$str = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
// Remove characters
$str = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $str );
$str = preg_replace("/[\/_|+ -]+/", $delimiter, $str );
$str = trim($str, $delimiter);
// Lowercase
if ($lowercase === true) $str = Text::lowercase($str);
// Return safe name
return $str;
}
/**
* Create safe url.
*
* <code>
* $url = Security::sanitizeURL('http://test.com');
* </code>
*
* @param string $url Url to sanitize
* @return string
*/
public static function sanitizeURL($url) {
$url = trim($url);
$url = rawurldecode($url);
$url = str_replace(array('--','&quot;','!','@','#','$','%','^','*','(',')','+','{','}','|',':','"','<','>',
'[',']','\\',';',"'",',','*','+','~','`','laquo','raquo',']>','&#8216;','&#8217;','&#8220;','&#8221;','&#8211;','&#8212;'),
array('-','-','','','','','','','','','','','','','','','','','','','','','','','','','','',''),
$url);
$url = str_replace('--', '-', $url);
$url = rtrim($url, "-");
$url = str_replace('..', '', $url);
$url = str_replace('//', '', $url);
$url = preg_replace('/^\//', '', $url);
$url = preg_replace('/^\./', '', $url);
return $url;
}
/**
* Sanitize URL to prevent XSS - Cross-site scripting
*/
public static function runSanitizeURL() {
$_GET = array_map('Security::sanitizeURL', $_GET);
}
/**
* That prevents null characters between ascii characters.
*
* @param string $str String
*/
public static function removeInvisibleCharacters($str) {
// Redefine vars
$str = (string) $str;
// Thanks to ci for this tip :)
$non_displayables = array('/%0[0-8bcef]/', '/%1[0-9a-f]/', '/[\x00-\x08]/', '/\x0b/', '/\x0c/', '/[\x0e-\x1f]/');
do {
$cleaned = $str;
$str = preg_replace($non_displayables, '', $str);
} while ($cleaned != $str);
// Return safe string
return $str;
}
/**
* Sanitize data to prevent XSS - Cross-site scripting
*
* @param string $str String
*/
public static function xssClean($str) {
// Remove invisible characters
$str = Security::removeInvisibleCharacters($str);
// Convert html to plain text
$str = Html::toText($str);
// Return safe string
return $str;
}
}

View File

@@ -1,197 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Session Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Session {
/**
* Starts the session.
*
* <code>
* Session::start();
* </code>
*
*/
public static function start() {
// Is session already started?
if ( ! session_id()) {
// Start the session
return @session_start();
}
// If already started
return true;
}
/**
* Deletes one or more session variables.
*
* <code>
* Session::delete('user');
* </code>
*
*/
public static function delete() {
// Loop all arguments
foreach (func_get_args() as $argument) {
// Array element
if (is_array($argument)) {
// Loop the keys
foreach ($argument as $key) {
// Unset session key
unset($_SESSION[(string) $key]);
}
} else {
// Remove from array
unset($_SESSION[(string) $argument]);
}
}
}
/**
* Destroys the session.
*
* <code>
* Session::destroy();
* </code>
*
*/
public static function destroy() {
// Destroy
if (session_id()) {
session_unset();
session_destroy();
$_SESSION = array();
}
}
/**
* Checks if a session variable exists.
*
* <code>
* if (Session::exists('user')) {
* // Do something...
* }
* </code>
*
* @return boolean
*/
public static function exists() {
// Start session if needed
if ( ! session_id()) Session::start();
// Loop all arguments
foreach (func_get_args() as $argument) {
// Array element
if (is_array($argument)) {
// Loop the keys
foreach ($argument as $key) {
// Does NOT exist
if ( ! isset($_SESSION[(string) $key])) return false;
}
} else {
// Does NOT exist
if ( ! isset($_SESSION[(string) $argument])) return false;
}
}
return true;
}
/**
* Gets a variable that was stored in the session.
*
* <code>
* echo Session::get('user');
* </code>
*
* @param string $key The key of the variable to get.
* @return mixed
*/
public static function get($key) {
// Start session if needed
if ( ! session_id()) self::start();
// Redefine key
$key = (string) $key;
// Fetch key
if (Session::exists((string) $key)) return $_SESSION[(string) $key];
// Key doesn't exist
return null;
}
/**
* Returns the sessionID.
*
* <code>
* echo Session::getSessionId();
* </code>
*
* @return string
*/
public static function getSessionId() {
if ( ! session_id()) Session::start();
return session_id();
}
/**
* Stores a variable in the session.
*
* <code>
* Session::set('user', 'Awilum');
* </code>
*
* @param string $key The key for the variable.
* @param mixed $value The value to store.
*/
public static function set($key, $value) {
// Start session if needed
if ( ! session_id()) self::start();
// Set key
$_SESSION[(string) $key] = $value;
}
}

View File

@@ -1,488 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Text Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Text {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Translit function ua,ru => latin
*
* <code>
* echo Text::translitIt('Привет');
* </code>
*
* @param string $str [ua,ru] string
* @return string $str
*/
public static function translitIt($str) {
// Redefine vars
$str = (string) $str;
$patern = array(
"А" => "A", "Б" => "B", "В" => "V", "Г" => "G",
"Д" => "D", "Е" => "E", "Ж" => "J", "З" => "Z",
"И" => "I", "Й" => "Y", "К" => "K", "Л" => "L",
"М" => "M", "Н" => "N", "О" => "O", "П" => "P",
"Р" => "R", "С" => "S", "Т" => "T", "У" => "U",
"Ф" => "F", "Х" => "H", "Ц" => "TS", "Ч" => "CH",
"Ш" => "SH", "Щ" => "SCH", "Ъ" => "", "Ы" => "YI",
"Ь" => "", "Э" => "E", "Ю" => "YU", "Я" => "YA",
"а" => "a", "б" => "b", "в" => "v", "г" => "g",
"д" => "d", "е" => "e", "ж" => "j", "з" => "z",
"и" => "i", "й" => "y", "к" => "k", "л" => "l",
"м" => "m", "н" => "n", "о" => "o","п" => "p",
"р" => "r", "с" => "s", "т" => "t", "у" => "u",
"ф" => "f", "х" => "h", "ц" => "ts", "ч" => "ch",
"ш" => "sh", "щ" => "sch", "ъ" => "y", "ї" => "i",
"Ї" => "Yi", "є" => "ie", "Є" => "Ye", "ы" => "yi",
"ь" => "", "э" => "e", "ю" => "yu", "я" => "ya", "ё" => "yo"
);
return strtr($str, $patern);
}
/**
* Removes any leading and traling slashes from a string
*
* <code>
* echo Text::trimSlashes('some text here/');
* </code>
*
* @param string $str String with slashes
* @return string
*/
public static function trimSlashes($str) {
// Redefine vars
$str = (string) $str;
return trim($str, '/');
}
/**
* Removes slashes contained in a string or in an array
*
* <code>
* echo Text::strpSlashes('some \ text \ here');
* </code>
*
* @param mixed $str String or array of strings with slashes
* @return mixed
*/
public static function strpSlashes($str) {
if (is_array($str)) {
foreach ($str as $key => $val) {
$result[$key] = stripslashes($val);
}
} else {
$result = stripslashes($str);
}
return $result;
}
/**
* Removes single and double quotes from a string
*
* <code>
* echo Text::stripQuotes('some "text" here');
* </code>
*
* @param string $str String with single and double quotes
* @return string
*/
public static function stripQuotes($str) {
// Redefine vars
$str = (string) $str;
return str_replace(array('"', "'"), '', $str);
}
/**
* Convert single and double quotes to entities
*
* <code>
* echo Text::quotesToEntities('some "text" here');
* </code>
*
* @param string $str String with single and double quotes
* @return string
*/
public static function quotesToEntities($str) {
// Redefine vars
$str = (string) $str;
return str_replace(array("\'", "\"", "'", '"'), array("&#39;", "&quot;", "&#39;", "&quot;"), $str);
}
/**
* Creates a random string of characters
*
* <code>
* echo Text::random();
* </code>
*
* @param string $type The type of string. Default is 'alnum'
* @param integer $length The number of characters. Default is 16
* @return string
*/
public static function random($type = 'alnum', $length = 16) {
// Redefine vars
$type = (string) $type;
$length = (int) $length;
switch($type) {
case 'basic':
return mt_rand();
break;
default:
case 'alnum':
case 'numeric':
case 'nozero':
case 'alpha':
case 'distinct':
case 'hexdec':
switch ($type) {
case 'alpha':
$pool = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
default:
case 'alnum':
$pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
break;
case 'numeric':
$pool = '0123456789';
break;
case 'nozero':
$pool = '123456789';
break;
case 'distinct':
$pool = '2345679ACDEFHJKLMNPRSTUVWXYZ';
break;
case 'hexdec':
$pool = '0123456789abcdef';
break;
}
$str = '';
for ($i=0; $i < $length; $i++) {
$str .= substr($pool, mt_rand(0, strlen($pool) -1), 1);
}
return $str;
break;
case 'unique':
return md5(uniqid(mt_rand()));
break;
case 'sha1' :
return sha1(uniqid(mt_rand(), true));
break;
}
}
/**
* Add's _1 to a string or increment the ending number to allow _2, _3, etc
*
* <code>
* $str = Text::increment($str);
* </code>
*
* @param string $str String to increment
* @param integer $first Start with
* @param string $separator Separator
* @return string
*/
public static function increment($str, $first = 1, $separator = '_') {
preg_match('/(.+)'.$separator.'([0-9]+)$/', $str, $match);
return isset($match[2]) ? $match[1].$separator.($match[2] + 1) : $str.$separator.$first;
}
/**
* Cut string
*
* <code>
* echo Text::cut('Some text here', 5);
* </code>
*
* @param string $str Input string
* @param integer $length Length after cut
* @param string $cut_msg Message after cut string
* @return string
*/
public static function cut($str, $length, $cut_msg = null) {
// Redefine vars
$str = (string) $str;
$length = (int) $length;
if (isset($cut_msg)) $msg = $cut_msg; else $msg = '...';
return function_exists('mb_substr') ? mb_substr($str, 0, $length, 'utf-8') . $msg : substr($str, 0, $length) . $msg;
}
/**
* Lowercase
*
* <code>
* echo Text::lowercase('Some text here');
* </code>
*
* @param string $str String
* @return string
*/
public static function lowercase($str) {
// Redefine vars
$str = (string) $str;
return function_exists('mb_strtolower') ? mb_strtolower($str, 'utf-8') : strtolower($str);
}
/**
* Uppercase
*
* <code>
* echo Text::uppercase('some text here');
* </code>
*
* @param string $str String
* @return string
*/
public static function uppercase($str) {
// Redefine vars
$str = (string) $str;
return function_exists('mb_strtoupper') ? mb_strtoupper($str, 'utf-8') : strtoupper($str);
}
/**
* Get length
*
* <code>
* echo Text::length('Some text here');
* </code>
*
* @param string $str String
* @return string
*/
public static function length($str) {
// Redefine vars
$str = (string) $str;
return function_exists('mb_strlen') ? mb_strlen($str, 'utf-8') : strlen($str);
}
/**
* Create a lorem ipsum text
*
* <code>
* echo Text::lorem(2);
* </code>
*
* @param integer $num Count
* @return string
*/
public static function lorem($num = 1) {
// Redefine vars
$num = (int) $num;
return str_repeat('Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', (int)$num);
}
/**
* Extract the last `$num` characters from a string.
*
* <code>
* echo Text::right('Some text here', 4);
* </code>
*
* @param string $str The string to extract the characters from.
* @param integer $num The number of characters to extract.
* @return string
*/
public static function right($str, $num){
// Redefine vars
$str = (string) $str;
$num = (int) $num;
return substr($str, Text::length($str)-$num, $num);
}
/**
* Extract the first `$num` characters from a string.
*
* <code>
* echo Text::left('Some text here', 4);
* </code>
*
* @param string $str The string to extract the characters from.
* @param integer $num The number of characters to extract.
* @return string
*/
public static function left($str, $num){
// Redefine vars
$str = (string) $str;
$num = (int) $num;
return substr($str, 0, $num);
}
/**
* Replaces newline with <br> or <br />.
*
* <code>
* echo Text::nl2br("Some \n text \n here");
* </code>
*
* @param string $str The input string
* @param boolean $xhtml Xhtml or not
* @return string
*/
public static function nl2br($str, $xhtml = true) {
// Redefine vars
$str = (string) $str;
$xhtml = (bool) $xhtml;
return str_replace(array("\r\n", "\n\r", "\n", "\r"), (($xhtml) ? '<br />' : '<br>'), $str);
}
/**
* Replaces <br> and <br /> with newline.
*
* <code>
* echo Text::br2nl("Some <br /> text <br /> here");
* </code>
*
* @param string $str The input string
* @return string
*/
public static function br2nl($str) {
// Redefine vars
$str = (string) $str;
return str_replace(array('<br>', '<br/>', '<br />'), "\n", $str);
}
/**
* Converts & to &amp;.
*
* <code>
* echo Text::ampEncode("M&CMS");
* </code>
*
* @param string $str The input string
* @return string
*/
public static function ampEncode($str) {
// Redefine vars
$str = (string) $str;
return str_replace('&', '&amp;', $str);
}
/**
* Converts &amp; to &.
*
* <code>
* echo Text::ampEncode("M&amp;CMS");
* </code>
*
* @param string $str The input string
* @return string
*/
public static function ampDecode($str) {
// Redefine vars
$str = (string) $str;
return str_replace('&amp;', '&', $str);
}
/**
* Convert plain text to html
*
* <code>
* echo Text::toHtml('test');
* </code>
*
* @param string $str String
* @return string
*/
public static function toHtml($str) {
// Redefine vars
$str = (string) $str;
return html_entity_decode($str, ENT_QUOTES, 'utf-8');
}
}

View File

@@ -1,171 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Uri Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Uri {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Default component
*
* @var string
*/
public static $default_component = 'pages';
/**
* Get uri and explode command/param1/param2
*
* <code>
* $segments = Uri::segments();
* </code>
*
* @return array
*/
public static function segments() {
// Get request uri and current script path
$request_uri = explode('/', $_SERVER['REQUEST_URI']);
$script_name = explode('/', $_SERVER['SCRIPT_NAME']);
// Delete script name
for ($i = 0; $i < sizeof($script_name); $i++) {
if ($request_uri[$i] == $script_name[$i]) {
unset($request_uri[$i]);
}
}
// Get all the values of an array
$uri = array_values($request_uri);
// Ability to pass parameters
foreach ($uri as $i => $u) {
if (isset($uri[$i])) { $pos = strrpos($uri[$i], "?"); if ($pos === false) { $uri[$i] = Security::sanitizeURL($uri[$i]); } else { $uri[$i] = Security::sanitizeURL(substr($uri[$i], 0, $pos)); } }
}
// Return uri segments
return $uri;
}
/**
* Get uri segment
*
* <code>
* $segment = Uri::segment(1);
* </code>
*
* @param integer $segment Segment
* @return mixed
*/
public static function segment($segment) {
$segments = Uri::segments();
return isset($segments[$segment]) ? $segments[$segment] : null;
}
/**
* Get command/component from registed components
*
* <code>
* $command = Uri::command();
* </code>
*
* @return array
*/
public static function command() {
// Get uri segments
$uri = Uri::segments();
if ( ! isset($uri[0])) {
$uri[0] = Uri::$default_component;
} else {
if ( ! in_array($uri[0], Plugin::$components) ) {
$uri[0] = Uri::$default_component;
} else {
$uri[0] = $uri[0];
}
}
return $uri[0];
}
/**
* Get uri parammeters
*
* <code>
* $params = Uri::params();
* </code>
*
* @return array
*/
public static function params() {
//Init data array
$data = array();
// Get URI
$uri = Uri::segments();
// http://site.com/ and http://site.com/index.php same main home pages
if ( ! isset($uri[0])) {
$uri[0] = '';
}
// param1/param2
if ($uri[0] !== Uri::$default_component) {
if (isset($uri[1])) {
$data[0] = $uri[0];
$data[1] = $uri[1];
// Some more uri parts :)
// site.ru/part1/part2/part3/part4/part5/part6/
if (isset($uri[2])) $data[2] = $uri[2];
if (isset($uri[3])) $data[3] = $uri[3];
if (isset($uri[4])) $data[4] = $uri[4];
if (isset($uri[5])) $data[5] = $uri[5];
} else { // default
$data[0] = $uri[0];
}
} else {
// This is good for box plugin Pages
// parent/child
if (isset($uri[2])) {
$data[0] = $uri[1];
$data[1] = $uri[2];
} else { // default
$data[0] = $uri[1];
}
}
return $data;
}
}

View File

@@ -1,131 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Url Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Url {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Takes a long url and uses the TinyURL API to return a shortened version.
*
* <code>
* echo Url::tiny('http:://sitename.com');
* </code>
*
* @param string $url Long url
* @return string
*/
public static function tiny($url) {
return file_get_contents('http://tinyurl.com/api-create.php?url='.(string)$url);
}
/**
* Check is url exists
*
* <code>
* if(Url::exists('http:://sitename.com')) {
* // Do something...
* }
* </code>
*
* @param string $url Url
* @return boolean
*/
public static function exists($url) {
$a_url = parse_url($url);
if ( ! isset($a_url['port'])) $a_url['port'] = 80;
$errno = 0;
$errstr = '';
$timeout = 30;
if (isset($a_url['host']) && $a_url['host']!=gethostbyname($a_url['host'])){
$fid = fsockopen($a_url['host'], $a_url['port'], $errno, $errstr, $timeout);
if ( ! $fid) return false;
$page = isset($a_url['path']) ? $a_url['path'] : '';
$page .= isset($a_url['query']) ? '?'.$a_url['query'] : '';
fputs($fid, 'HEAD '.$page.' HTTP/1.0'."\r\n".'Host: '.$a_url['host']."\r\n\r\n");
$head = fread($fid, 4096);
fclose($fid);
return preg_match('#^HTTP/.*\s+[200|302]+\s#i', $head);
} else {
return false;
}
}
/**
* Find url
*
* <code>
* // Outputs: http://sitename.com/home
* echo Url::find('home');
* </code>
*
* @global string $site_url Site url
* @param string $url URL - Uniform Resource Locator
* @return string
*/
public static function find($url) {
$https = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') ? 'https://' : 'http://';
$pos = strpos($url, $https);
if ($pos === false) { $url_output = Option::get('siteurl') . $url; } else { $url_output = $url; }
return $url_output;
}
/**
* Gets the base URL
*
* <code>
* echo Url::base();
* </code>
*
* @return string
*/
public static function base() {
$https = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on') ? 'https://' : 'http://';
return $https . rtrim(rtrim($_SERVER['HTTP_HOST'], '\\/') . dirname($_SERVER['PHP_SELF']), '\\/');
}
/**
* Gets current URL
*
* <code>
* echo Url::current();
* </code>
*
* @return string
*/
public static function current() {
return (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
}
}

View File

@@ -1,208 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Validation Helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Valid {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* Check an email address for correct format.
*
* <code>
* if (Valid::email('test@test.com')) {
* // Do something...
* }
* </code>
*
* @param string $email email address
* @return boolean
*/
public static function email($email) {
return (bool) filter_var((string)$email, FILTER_VALIDATE_EMAIL);
}
/**
* Check an ip address for correct format.
*
* <code>
* if (Valid::ip('127.0.0.1') || Valid::ip('0:0:0:0:0:0:7f00:1')) {
* // Do something...
* }
* </code>
*
* @param string $ip ip address
* @return boolean
*/
public static function ip($ip) {
return (bool) filter_var((string)$ip, FILTER_VALIDATE_IP);
}
/**
* Check an credit card for correct format.
*
* <code>
* if (Valid::creditCard(7711111111111111, 'Visa')) {
* // Do something...
* }
* </code>
*
* @param integer $num Credit card num
* @param string $type Credit card type:
* American - American Express
* Dinners - Diner's Club
* Discover - Discover Card
* Master - Mastercard
* Visa - Visa
* @return boolean
*/
public static function creditCard($num, $type) {
// Redefine vars
$num = (int) $num;
$type = (string) $type;
switch($type) {
case "American": return (bool) preg_match("/^([34|37]{2})([0-9]{13})$/", $num);
case "Dinners": return (bool) preg_match("/^([30|36|38]{2})([0-9]{12})$/", $num);
case "Discover": return (bool) preg_match("/^([6011]{4})([0-9]{12})$/", $num);
case "Master": return (bool) preg_match("/^([51|52|53|54|55]{2})([0-9]{14})$/", $num);
case "Visa": return (bool) preg_match("/^([4]{1})([0-9]{12,15})$/", $num);
}
}
/**
* Check an phone number for correct format.
*
* <code>
* if (Valid::phone(0661111117)) {
* // Do something...
* }
* </code>
*
* @param string $num Phone number
* @return boolean
*/
public static function phone($num) {
return (bool) preg_match("/^([0-9\(\)\/\+ \-]*)$/", (string)$num);
}
/**
* Check an url for correct format.
*
* <code>
* if (Valid::url('http://site.com/')) {
* // Do something...
* }
* </code>
*
* @param string $url Url
* @return boolean
*/
public static function url($url) {
return (bool) filter_var((string)$url, FILTER_VALIDATE_URL);
}
/**
* Check an date for correct format.
*
* <code>
* if (Valid::date('12/12/12')) {
* // Do something...
* }
* </code>
*
* @param string $str Date
* @return boolean
*/
public static function date($str) {
return (strtotime($str) !== false);
}
/**
* Checks whether a string consists of digits only (no dots or dashes).
*
* <code>
* if (Valid::digit('12')) {
* // Do something...
* }
* </code>
*
* @param string $str String
* @return boolean
*/
public static function digit($str) {
return (bool) preg_match ("/[^0-9]/", $str);
}
/**
* Checks whether a string is a valid number (negative and decimal numbers allowed).
*
* <code>
* if (Valid::numeric('3.14')) {
* // Do something...
* }
* </code>
*
* Uses {@link http://www.php.net/manual/en/function.localeconv.php locale conversion}
* to allow decimal point to be locale specific.
*
* @param string $str String
* @return boolean
*/
public static function numeric($str) {
$locale = localeconv();
return (bool) preg_match('/^-?[0-9'.$locale['decimal_point'].']++$/D', (string)$str);
}
/**
* Checks if the given regex statement is valid.
*
* @param string $regexp The value to validate.
* @return boolean
*/
public static function regexp($regexp) {
// dummy string
$dummy = 'Monstra - fast and simple cms';
// validate
return (@preg_match((string) $regexp, $dummy) !== false);
}
}

View File

@@ -1,385 +0,0 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Zip helper
*
* @package Monstra
* @subpackage Helpers
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version $Id$
* @since 1.0.0
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* Monstra is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYING.txt for copyright notices and details.
* @filesource
*/
class Zip {
var $zipdata = '';
var $directory = '';
var $entries = 0;
var $file_num = 0;
var $offset = 0;
var $now;
/**
* Constructor
*/
public function __construct() {
$this->now = time();
}
/**
* Zip factory
*
* <code>
* Zip::factory();
* </code>
*
* @return Zip
*/
public static function factory() {
return new Zip();
}
/**
* Add Directory
*
* <code>
* Zip::factory()->addDir('test');
* </code>
*
* @param mixed $directory The directory name. Can be string or array
*/
public function addDir($directory) {
foreach ((array)$directory as $dir) {
if ( ! preg_match("|.+/$|", $dir)) {
$dir .= '/';
}
$dir_time = $this->_get_mod_time($dir);
$this->_add_dir($dir, $dir_time['file_mtime'], $dir_time['file_mdate']);
}
return $this;
}
/**
* Get file/directory modification time
*
* @param string $dir Full path to the dir
* @return array
*/
protected function _get_mod_time($dir) {
// If this is a newly created file/dir, we will set the time to 'now'
$date = (@filemtime($dir)) ? filemtime($dir) : getdate($this->now);
$time['file_mtime'] = ($date['hours'] << 11) + ($date['minutes'] << 5) + $date['seconds'] / 2;
$time['file_mdate'] = (($date['year'] - 1980) << 9) + ($date['mon'] << 5) + $date['mday'];
return $time;
}
/**
* Add Directory
*
* @param string $dir The directory name
* @param integer $file_mtime File mtime
* @param integer $file_mdate File mdate
*/
private function _add_dir($dir, $file_mtime, $file_mdate) {
$dir = str_replace("\\", "/", $dir);
$this->zipdata .=
"\x50\x4b\x03\x04\x0a\x00\x00\x00\x00\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V', 0) // crc32
.pack('V', 0) // compressed filesize
.pack('V', 0) // uncompressed filesize
.pack('v', strlen($dir)) // length of pathname
.pack('v', 0) // extra field length
.$dir
// below is "data descriptor" segment
.pack('V', 0) // crc32
.pack('V', 0) // compressed filesize
.pack('V', 0); // uncompressed filesize
$this->directory .=
"\x50\x4b\x01\x02\x00\x00\x0a\x00\x00\x00\x00\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V',0) // crc32
.pack('V',0) // compressed filesize
.pack('V',0) // uncompressed filesize
.pack('v', strlen($dir)) // length of pathname
.pack('v', 0) // extra field length
.pack('v', 0) // file comment length
.pack('v', 0) // disk number start
.pack('v', 0) // internal file attributes
.pack('V', 16) // external file attributes - 'directory' bit set
.pack('V', $this->offset) // relative offset of local header
.$dir;
$this->offset = strlen($this->zipdata);
$this->entries++;
}
/**
* Add Data to Zip
*
* <code>
* Zip::factory()->addData('test.txt', 'Some test text here');
* </code>
*
* Lets you add files to the archive. If the path is included
* in the filename it will be placed within a directory. Make
* sure you use add_dir() first to create the folder.
*
* @param mixed $filepath Full path to the file
* @param string $data Data
*/
public function addData($filepath, $data = null) {
if (is_array($filepath)) {
foreach ($filepath as $path => $data) {
$file_data = $this->_get_mod_time($path);
$this->_add_data($path, $data, $file_data['file_mtime'], $file_data['file_mdate']);
}
} else {
$file_data = $this->_get_mod_time($filepath);
$this->_add_data($filepath, $data, $file_data['file_mtime'], $file_data['file_mdate']);
}
return $this;
}
/**
* Add Data to Zip
*
* @param string $filepath Full path to the file
* @param string $data The data to be encoded
* @param integer $file_mtime File mtime
* @param integer $file_mdate File mdate
*/
private function _add_data($filepath, $data, $file_mtime, $file_mdate) {
$filepath = str_replace("\\", "/", $filepath);
$uncompressed_size = strlen($data);
$crc32 = crc32($data);
$gzdata = gzcompress($data);
$gzdata = substr($gzdata, 2, -4);
$compressed_size = strlen($gzdata);
$this->zipdata .=
"\x50\x4b\x03\x04\x14\x00\x00\x00\x08\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V', $crc32)
.pack('V', $compressed_size)
.pack('V', $uncompressed_size)
.pack('v', strlen($filepath)) // length of filename
.pack('v', 0) // extra field length
.$filepath
.$gzdata; // "file data" segment
$this->directory .=
"\x50\x4b\x01\x02\x00\x00\x14\x00\x00\x00\x08\x00"
.pack('v', $file_mtime)
.pack('v', $file_mdate)
.pack('V', $crc32)
.pack('V', $compressed_size)
.pack('V', $uncompressed_size)
.pack('v', strlen($filepath)) // length of filename
.pack('v', 0) // extra field length
.pack('v', 0) // file comment length
.pack('v', 0) // disk number start
.pack('v', 0) // internal file attributes
.pack('V', 32) // external file attributes - 'archive' bit set
.pack('V', $this->offset) // relative offset of local header
.$filepath;
$this->offset = strlen($this->zipdata);
$this->entries++;
$this->file_num++;
}
/**
* Read the contents of a file and add it to the zip
*
* <code>
* Zip::factory()->readFile('test.txt');
* </code>
*
* @param string $path Path
* @param boolean $preserve_filepath Preserve filepath
* @return mixed
*/
function readFile($path, $preserve_filepath = false) {
if ( ! file_exists($path)) {
return false;
}
if (false !== ($data = file_get_contents($path))) {
$name = str_replace("\\", "/", $path);
if ($preserve_filepath === false) {
$name = preg_replace("|.*/(.+)|", "\\1", $name);
}
$this->addData($name, $data);
return $this;
}
return false;
}
/**
* Read a directory and add it to the zip.
*
* <code>
* Zip::factory()->readDir('test/');
* </code>
*
* This function recursively reads a folder and everything it contains (including
* sub-folders) and creates a zip based on it. Whatever directory structure
* is in the original file path will be recreated in the zip file.
*
* @param string $path Path to source
* @param boolean $preserve_filepath Preserve filepath
* @param string $root_path Root path
* @return mixed
*/
function readDir($path, $preserve_filepath = true, $root_path = null) {
if ( ! $fp = @opendir($path)) {
return false;
}
// Set the original directory root for child dir's to use as relative
if ($root_path === null) {
$root_path = dirname($path) . '/';
}
while (false !== ($file = readdir($fp))) {
if (substr($file, 0, 1) == '.') {
continue;
}
if (@is_dir($path.$file)) {
$this->readDir($path.$file."/", $preserve_filepath, $root_path);
} else {
if (false !== ($data = file_get_contents($path.$file))) {
$name = str_replace("\\", "/", $path);
if ($preserve_filepath === false) {
$name = str_replace($root_path, '', $name);
}
$this->addData($name.$file, $data);
}
}
}
return $this;
}
/**
* Get the Zip file
*
* <code>
* Zip::factory()->getZip();
* </code>
*
* @return string
*/
public function getZip() {
// Is there any data to return?
if ($this->entries == 0) {
return false;
}
$zip_data = $this->zipdata;
$zip_data .= $this->directory."\x50\x4b\x05\x06\x00\x00\x00\x00";
$zip_data .= pack('v', $this->entries); // total # of entries "on this disk"
$zip_data .= pack('v', $this->entries); // total # of entries overall
$zip_data .= pack('V', strlen($this->directory)); // size of central dir
$zip_data .= pack('V', strlen($this->zipdata)); // offset to start of central dir
$zip_data .= "\x00\x00"; // .zip file comment length
return $zip_data;
}
/**
* Write File to the specified directory
*
* <code>
* Zip::factory()->readDir('test1/')->readDir('test2/')->archive('test.zip');
* </code>
*
* @param string $filepath The file name
* @return boolean
*/
public function archive($filepath) {
if ( ! ($fp = @fopen($filepath, "w"))) {
return false;
}
flock($fp, LOCK_EX);
fwrite($fp, $this->getZip());
flock($fp, LOCK_UN);
fclose($fp);
return true;
}
/**
* Initialize Data
*
* <code>
* Zip::factory()->clearData();
* </code>
*
* Lets you clear current zip data. Useful if you need to create
* multiple zips with different data.
*/
public function clearData() {
$this->zipdata = '';
$this->directory = '';
$this->entries = 0;
$this->file_num = 0;
$this->offset = 0;
}
}

View File

@@ -1,74 +1,73 @@
<?php
// Add plugin navigation link
Navigation::add(__('Backups', 'backup'), 'system', 'backup', 3);
// Add plugin navigation link
Navigation::add(__('Backups', 'backup'), 'system', 'backup', 3);
/**
* Backup Admin Class
*/
class BackupAdmin extends Backend
{
/**
* Backup Admin Class
* Backup admin
*/
class BackupAdmin extends Backend {
public static function main()
{
$backups_path = ROOT . DS . 'backups';
$backups_list = array();
/**
* Backup admin
*/
public static function main() {
// Create backup
// -------------------------------------
if (Request::post('create_backup')) {
$backups_path = ROOT . DS . 'backups';
if (Security::check(Request::post('csrf'))) {
$backups_list = array();
@set_time_limit(0);
@ini_set("memory_limit", "512M");
// Create backup
// -------------------------------------
if (Request::post('create_backup')) {
$zip = Zip::factory();
if (Security::check(Request::post('csrf'))) {
// Add storage folder
$zip->readDir(STORAGE . DS, false);
@set_time_limit(0);
@ini_set("memory_limit", "512M");
// Add public folder
if (Request::post('add_public_folder')) $zip->readDir(ROOT . DS . 'public' . DS, false);
$zip = Zip::factory();
// Add plugins folder
if (Request::post('add_plugins_folder')) $zip->readDir(PLUGINS . DS, false);
// Add storage folder
$zip->readDir(STORAGE . DS, false);
$zip->archive($backups_path . DS . Date::format(time(), "Y-m-d-H-i-s").'.zip');
// Add public folder
if (Request::post('add_public_folder')) $zip->readDir(ROOT . DS . 'public' . DS, false);
// Add plugins folder
if (Request::post('add_plugins_folder')) $zip->readDir(PLUGINS . DS, false);
$zip->archive($backups_path . DS . Date::format(time(), "Y-m-d-H-i-s").'.zip');
} else { die('csrf detected!'); }
}
// Delete backup
// -------------------------------------
if (Request::get('id') == 'backup' && Request::get('delete_file')) {
if (Security::check(Request::get('token'))) {
File::delete($backups_path . DS . Request::get('delete_file'));
Request::redirect(Option::get('siteurl').'admin/index.php?id=backup');
} else { die('csrf detected!'); }
}
// Download backup
// -------------------------------------
if (Request::get('download')) {
if (Security::check(Request::get('token'))) {
File::download($backups_path . DS . Request::get('download'));
} else { die('csrf detected!'); }
}
// Get backup list
$backups_list = File::scan($backups_path, '.zip');
// Display view
View::factory('box/backup/views/backend/index')
->assign('backups_list', $backups_list)
->display();
} else { die('csrf detected!'); }
}
// Delete backup
// -------------------------------------
if (Request::get('id') == 'backup' && Request::get('delete_file')) {
if (Security::check(Request::get('token'))) {
File::delete($backups_path . DS . Request::get('delete_file'));
Request::redirect(Option::get('siteurl').'admin/index.php?id=backup');
} else { die('csrf detected!'); }
}
// Download backup
// -------------------------------------
if (Request::get('download')) {
if (Security::check(Request::get('token'))) {
File::download($backups_path . DS . Request::get('download'));
} else { die('csrf detected!'); }
}
// Get backup list
$backups_list = File::scan($backups_path, '.zip');
// Display view
View::factory('box/backup/views/backend/index')
->assign('backups_list', $backups_list)
->display();
}
}

View File

@@ -1,32 +1,29 @@
<?php
/**
* Backup plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.0.0
*
*/
/**
* Backup plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.0.0
*
*/
// Register plugin
Plugin::register( __FILE__,
__('Backup', 'backup'),
__('Backup manager', 'backup'),
'1.0.0',
'Awilum',
'http://monstra.org/',
null,
'box');
// Register plugin
Plugin::register( __FILE__,
__('Backup', 'backup'),
__('Backup manager', 'backup'),
'1.0.0',
'Awilum',
'http://monstra.org/',
null,
'box');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) {
// Include Backup Admin
Plugin::admin('backup', 'box');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) {
// Include Backup Admin
Plugin::admin('backup', 'box');
}
}

View File

@@ -2,10 +2,10 @@
return array(
'backup' => array(
'Backups' => 'Backups',
'Backups' => 'Backups',
'Backup date' => 'Backup Datum',
'Create backup' => 'Erstelle Backup',
'Delete' => 'Löschen',
'Create backup' => 'Erstelle Backup',
'Delete' => 'Löschen',
'storage' => 'Speicher',
'public' => 'Öffentliche',
'plugins' => 'Plugins',
@@ -14,4 +14,4 @@
'Delete backup: :backup' => 'Lösche Backup: :backup',
'Creating...' => 'Erstellen...',
)
);
);

View File

@@ -2,10 +2,10 @@
return array(
'backup' => array(
'Backups' => 'Backups',
'Backups' => 'Backups',
'Backup date' => 'Backup date',
'Create backup' => 'Create backup',
'Delete' => 'Delete',
'Create backup' => 'Create backup',
'Delete' => 'Delete',
'storage' => 'storage',
'public' => 'public',
'plugins' => 'plugins',
@@ -14,4 +14,4 @@
'Delete backup: :backup' => 'Delete backup: :backup',
'Creating...' => 'Creating...',
)
);
);

View File

@@ -2,10 +2,10 @@
return array(
'backup' => array(
'Backups' => 'Backups',
'Backups' => 'Backups',
'Backup date' => 'Data do backup',
'Create backup' => 'Criar',
'Delete' => 'Deletar',
'Create backup' => 'Criar',
'Delete' => 'Deletar',
'storage' => 'storage',
'public' => 'public',
'plugins' => 'plugins',
@@ -14,4 +14,4 @@
'Delete backup: :backup' => 'Deletar o backup: :backup',
'Creating...' => 'Criando backup...',
)
);
);

View File

@@ -34,16 +34,16 @@ $().ready(function(){$('[name=create_backup]').click(function(){$(this).button('
<td>
<?php $name = strtotime(str_replace('-', '', basename($backup, '.zip'))); ?>
<?php echo Html::anchor(Date::format($name, 'F jS, Y - g:i A'), Option::get('siteurl').'admin/index.php?id=backup&download='.$backup.'&token='.Security::token()); ?>
</td>
</td>
<td><?php echo Number::byteFormat(filesize(ROOT . DS . 'backups' . DS . $backup)); ?></td>
<td>
<td>
<div class="pull-right">
<?php echo Html::anchor(__('Delete', 'backup'),
'index.php?id=backup&delete_file='.$backup.'&token='.Security::token(),
array('class' => 'btn btn-small', 'onclick' => "return confirmDelete('".__('Delete backup: :backup', 'backup', array(':backup' => Date::format($name, 'F jS, Y - g:i A')))."')"));
?>
</div>
</td>
</td>
</tr>
<?php } ?>
</tbody>

View File

@@ -1,149 +1,146 @@
<?php
// Add plugin navigation link
Navigation::add(__('Blocks', 'blocks'), 'content', 'blocks', 2);
// Add plugin navigation link
Navigation::add(__('Blocks', 'blocks'), 'content', 'blocks', 2);
/**
* Blocks Admin Class
*/
class BlocksAdmin extends Backend
{
/**
* Blocks Admin Class
* Blocks admin function
*/
class BlocksAdmin extends Backend {
public static function main()
{
// Init vars
$blocks_path = STORAGE . DS . 'blocks' . DS;
$blocks_list = array();
$errors = array();
// Check for get actions
// -------------------------------------
if (Request::get('action')) {
/**
* Blocks admin function
*/
public static function main() {
// Init vars
$blocks_path = STORAGE . DS . 'blocks' . DS;
$blocks_list = array();
$errors = array();
// Check for get actions
// Switch actions
// -------------------------------------
if (Request::get('action')) {
switch (Request::get('action')) {
// Switch actions
// -------------------------------------
switch (Request::get('action')) {
// Add block
// -------------------------------------
case "add_block":
// Add block
// -------------------------------------
case "add_block":
if (Request::post('add_blocks') || Request::post('add_blocks_and_exit')) {
if (Request::post('add_blocks') || Request::post('add_blocks_and_exit')) {
if (Security::check(Request::post('csrf'))) {
if (Security::check(Request::post('csrf'))) {
if (trim(Request::post('name')) == '') $errors['blocks_empty_name'] = __('Required field', 'blocks');
if (file_exists($blocks_path.Security::safeName(Request::post('name')).'.block.html')) $errors['blocks_exists'] = __('This block already exists', 'blocks');
if (trim(Request::post('name')) == '') $errors['blocks_empty_name'] = __('Required field', 'blocks');
if (file_exists($blocks_path.Security::safeName(Request::post('name')).'.block.html')) $errors['blocks_exists'] = __('This block already exists', 'blocks');
if (count($errors) == 0) {
if (count($errors) == 0) {
// Save block
File::setContent($blocks_path.Security::safeName(Request::post('name')).'.block.html', XML::safe(Request::post('editor')));
// Save block
File::setContent($blocks_path.Security::safeName(Request::post('name')).'.block.html', XML::safe(Request::post('editor')));
Notification::set('success', __('Your changes to the block <i>:name</i> have been saved.', 'blocks', array(':name' => Security::safeName(Request::post('name')))));
Notification::set('success', __('Your changes to the block <i>:name</i> have been saved.', 'blocks', array(':name' => Security::safeName(Request::post('name')))));
if (Request::post('add_blocks_and_exit')) {
Request::redirect('index.php?id=blocks');
} else {
Request::redirect('index.php?id=blocks&action=edit_block&filename='.Security::safeName(Request::post('name')));
}
if (Request::post('add_blocks_and_exit')) {
Request::redirect('index.php?id=blocks');
} else {
Request::redirect('index.php?id=blocks&action=edit_block&filename='.Security::safeName(Request::post('name')));
}
}
} else { die('csrf detected!'); }
}
} else { die('csrf detected!'); }
}
// Save fields
if (Request::post('name')) $name = Request::post('name'); else $name = '';
if (Request::post('editor')) $content = Request::post('editor'); else $content = '';
// Save fields
if (Request::post('name')) $name = Request::post('name'); else $name = '';
if (Request::post('editor')) $content = Request::post('editor'); else $content = '';
// Display view
View::factory('box/blocks/views/backend/add')
->assign('content', $content)
->assign('name', $name)
->assign('errors', $errors)
->display();
break;
// Display view
View::factory('box/blocks/views/backend/add')
->assign('content', $content)
->assign('name', $name)
->assign('errors', $errors)
->display();
break;
// Edit block
// -------------------------------------
case "edit_block":
// Save current block action
if (Request::post('edit_blocks') || Request::post('edit_blocks_and_exit') ) {
// Edit block
// -------------------------------------
case "edit_block":
// Save current block action
if (Request::post('edit_blocks') || Request::post('edit_blocks_and_exit') ) {
if (Security::check(Request::post('csrf'))) {
if (Security::check(Request::post('csrf'))) {
if (trim(Request::post('name')) == '') $errors['blocks_empty_name'] = __('Required field', 'blocks');
if ((file_exists($blocks_path.Security::safeName(Request::post('name')).'.block.html')) and (Security::safeName(Request::post('blocks_old_name')) !== Security::safeName(Request::post('name')))) $errors['blocks_exists'] = __('This block already exists', 'blocks');
if (trim(Request::post('name')) == '') $errors['blocks_empty_name'] = __('Required field', 'blocks');
if ((file_exists($blocks_path.Security::safeName(Request::post('name')).'.block.html')) and (Security::safeName(Request::post('blocks_old_name')) !== Security::safeName(Request::post('name')))) $errors['blocks_exists'] = __('This block already exists', 'blocks');
// Save fields
if (Request::post('editor')) $content = Request::post('editor'); else $content = '';
if (count($errors) == 0) {
// Save fields
if (Request::post('editor')) $content = Request::post('editor'); else $content = '';
if (count($errors) == 0) {
$block_old_filename = $blocks_path.Request::post('blocks_old_name').'.block.html';
$block_new_filename = $blocks_path.Security::safeName(Request::post('name')).'.block.html';
if ( ! empty($block_old_filename)) {
if ($block_old_filename !== $block_new_filename) {
rename($block_old_filename, $block_new_filename);
$save_filename = $block_new_filename;
} else {
$save_filename = $block_new_filename;
}
$block_old_filename = $blocks_path.Request::post('blocks_old_name').'.block.html';
$block_new_filename = $blocks_path.Security::safeName(Request::post('name')).'.block.html';
if ( ! empty($block_old_filename)) {
if ($block_old_filename !== $block_new_filename) {
rename($block_old_filename, $block_new_filename);
$save_filename = $block_new_filename;
} else {
$save_filename = $block_new_filename;
}
// Save block
File::setContent($save_filename, XML::safe(Request::post('editor')));
Notification::set('success', __('Your changes to the block <i>:name</i> have been saved.', 'blocks', array(':name' => basename($save_filename, '.block.html'))));
if (Request::post('edit_blocks_and_exit')) {
Request::redirect('index.php?id=blocks');
} else {
Request::redirect('index.php?id=blocks&action=edit_block&filename='.Security::safeName(Request::post('name')));
}
} else {
$save_filename = $block_new_filename;
}
} else { die('csrf detected!'); }
}
if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename'));
if (Request::post('editor')) $content = Request::post('editor'); else $content = File::getContent($blocks_path.Request::get('filename').'.block.html');
// Save block
File::setContent($save_filename, XML::safe(Request::post('editor')));
Notification::set('success', __('Your changes to the block <i>:name</i> have been saved.', 'blocks', array(':name' => basename($save_filename, '.block.html'))));
// Display view
View::factory('box/blocks/views/backend/edit')
->assign('content', Text::toHtml($content))
->assign('name', $name)
->assign('errors', $errors)
->display();
break;
case "delete_block":
if (Security::check(Request::get('token'))) {
File::delete($blocks_path.Request::get('filename').'.block.html');
Notification::set('success', __('Block <i>:name</i> deleted', 'blocks', array(':name' => File::name(Request::get('filename')))));
Request::redirect('index.php?id=blocks');
if (Request::post('edit_blocks_and_exit')) {
Request::redirect('index.php?id=blocks');
} else {
Request::redirect('index.php?id=blocks&action=edit_block&filename='.Security::safeName(Request::post('name')));
}
}
} else { die('csrf detected!'); }
}
if (Request::post('name')) $name = Request::post('name'); else $name = File::name(Request::get('filename'));
if (Request::post('editor')) $content = Request::post('editor'); else $content = File::getContent($blocks_path.Request::get('filename').'.block.html');
break;
}
} else {
// Display view
View::factory('box/blocks/views/backend/edit')
->assign('content', Text::toHtml($content))
->assign('name', $name)
->assign('errors', $errors)
->display();
break;
case "delete_block":
if (Security::check(Request::get('token'))) {
// Get blocks
$blocks_list = File::scan($blocks_path, '.block.html');
File::delete($blocks_path.Request::get('filename').'.block.html');
Notification::set('success', __('Block <i>:name</i> deleted', 'blocks', array(':name' => File::name(Request::get('filename')))));
Request::redirect('index.php?id=blocks');
// Display view
View::factory('box/blocks/views/backend/index')
->assign('blocks_list', $blocks_list)
->display();
} else { die('csrf detected!'); }
break;
}
}
} else {
// Get blocks
$blocks_list = File::scan($blocks_path, '.block.html');
// Display view
View::factory('box/blocks/views/backend/index')
->assign('blocks_list', $blocks_list)
->display();
}
}
}

View File

@@ -1,118 +1,115 @@
<?php
/**
* Blocks plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.0.0
*
*/
// Register plugin
Plugin::register( __FILE__,
__('Blocks', 'blocks'),
__('Blocks manager plugin', 'blocks'),
'1.0.0',
'Awilum',
'http://monstra.org/',
null,
'box');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) {
// Include Admin
Plugin::admin('blocks', 'box');
}
// Add Plugin Javascript
Javascript::add('plugins/box/blocks/js/blocks.js', 'backend');
// Add shortcode {block get="blockname"}
Shortcode::add('block', 'Block::_content');
// Add shortcode {block_inline name="blockname"}
Shortcode::add('block_inline', 'Block::_inlineBlock');
// Add shortcode {block_inline_create name="blockname"} Block content here {/block_inline_create}
Shortcode::add('block_inline_create', 'Block::_createInlineBlock');
/**
* Block Class
*/
class Block
{
/**
* Blocks plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.0.0
* Inline Blocks
*
* @var array
*/
public static $inline_blocks = array();
// Register plugin
Plugin::register( __FILE__,
__('Blocks', 'blocks'),
__('Blocks manager plugin', 'blocks'),
'1.0.0',
'Awilum',
'http://monstra.org/',
null,
'box');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) {
// Include Admin
Plugin::admin('blocks', 'box');
/**
* Create Inline Block
*/
public static function _createInlineBlock($attributes, $content)
{
if (isset($attributes['name'])) {
Block::$inline_blocks[Security::safeName($attributes['name'], '_', true)] = array(
'content' => (string) $content,
);
}
}
// Add Plugin Javascript
Javascript::add('plugins/box/blocks/js/blocks.js', 'backend');
// Add shortcode {block get="blockname"}
Shortcode::add('block', 'Block::_content');
// Add shortcode {block_inline name="blockname"}
Shortcode::add('block_inline', 'Block::_inlineBlock');
// Add shortcode {block_inline_create name="blockname"} Block content here {/block_inline_create}
Shortcode::add('block_inline_create', 'Block::_createInlineBlock');
/**
* Draw Inline Block
*/
public static function _inlineBlock($attributes)
{
if (isset($attributes['name']) && isset(Block::$inline_blocks[$attributes['name']])) {
$content = Filter::apply('content', Text::toHtml(Block::$inline_blocks[$attributes['name']]['content']));
return $content;
} else {
return '';
}
}
/**
* Block Class
* Get block
*
* @param string $name Block file name
*/
class Block {
public static function get($name)
{
return Block::_content(array('get' => $name));
}
/**
* Returns block content for shortcode {block get="blockname"}
*
* @param array $attributes block filename
*/
public static function _content($attributes)
{
if (isset($attributes['get'])) $name = (string) $attributes['get']; else $name = '';
/**
* Inline Blocks
*
* @var array
*/
public static $inline_blocks = array();
$block_path = STORAGE . DS . 'blocks' . DS . $name . '.block.html';
if (File::exists($block_path)) {
ob_start();
include $block_path;
$block_contents = ob_get_contents();
ob_end_clean();
/**
* Create Inline Block
*/
public static function _createInlineBlock($attributes, $content) {
if (isset($attributes['name'])) {
Block::$inline_blocks[Security::safeName($attributes['name'], '_', true)] = array(
'content' => (string)$content,
);
}
}
/**
* Draw Inline Block
*/
public static function _inlineBlock($attributes) {
if (isset($attributes['name']) && isset(Block::$inline_blocks[$attributes['name']])) {
$content = Filter::apply('content', Text::toHtml(Block::$inline_blocks[$attributes['name']]['content']));
return $content;
} else {
return '';
}
}
/**
* Get block
*
* @param string $name Block file name
*/
public static function get($name) {
return Block::_content(array('get' => $name));
}
/**
* Returns block content for shortcode {block get="blockname"}
*
* @param array $attributes block filename
*/
public static function _content($attributes) {
if (isset($attributes['get'])) $name = (string)$attributes['get']; else $name = '';
$block_path = STORAGE . DS . 'blocks' . DS . $name . '.block.html';
if (File::exists($block_path)) {
ob_start();
include $block_path;
$block_contents = ob_get_contents();
ob_end_clean();
return Filter::apply('content', Text::toHtml($block_contents));
} else {
if (Session::exists('admin') && Session::get('admin') == true) {
return __('<b>Block <u>:name</u> is not found!</b>', 'blocks', array(':name' => $name));
}
return Filter::apply('content', Text::toHtml($block_contents));
} else {
if (Session::exists('admin') && Session::get('admin') == true) {
return __('<b>Block <u>:name</u> is not found!</b>', 'blocks', array(':name' => $name));
}
}
}
}

View File

@@ -5,12 +5,10 @@
<?php if (isset($errors['blocks_empty_name']) or isset($errors['blocks_exists'])) $error_class = 'error'; else $error_class = ''; ?>
<?php echo (Form::open()); ?>
<?php echo (Form::hidden('csrf', Security::token())); ?>
<?php echo (Form::label('name', __('Name', 'blocks'))); ?>
<?php echo (Form::input('name', $name, array('class' => (isset($errors['blocks_empty_name']) || isset($errors['blocks_exists'])) ? 'input-xxlarge error-field' : 'input-xxlarge'))); ?>
@@ -33,4 +31,3 @@
);
?>

View File

@@ -16,7 +16,6 @@
?>
<?php echo (Form::label('name', __('Name', 'blocks'))); ?>
<?php echo (Form::input('name', $name, array('class' => (isset($errors['blocks_empty_name']) || isset($errors['blocks_exists'])) ? 'input-xxlarge error-field' : 'input-xxlarge'))); ?>

View File

@@ -1,43 +1,42 @@
<?php
/**
* Editor plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.0.0
*
*/
// Register plugin
Plugin::register( __FILE__,
__('Editor', 'editor'),
__('Editor plugin', 'editor'),
'1.0.0',
'Awilum',
'http://monstra.org/',
null,
'box');
// Add action
Action::add('admin_editor', 'Editor::render', 10, array());
/**
* Editor class
*/
class Editor
{
/**
* Editor plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.0.0
* Render editor
*
* @param string $val editor data
*/
// Register plugin
Plugin::register( __FILE__,
__('Editor', 'editor'),
__('Editor plugin', 'editor'),
'1.0.0',
'Awilum',
'http://monstra.org/',
null,
'box');
// Add action
Action::add('admin_editor', 'Editor::render', 10, array());
/**
* Editor class
*/
class Editor {
/**
* Render editor
*
* @param string $val editor data
*/
public static function render($val = null) {
echo ('<div id="editor_panel"></div><div><textarea id="editor_area" name="editor" style="width:100%; height:320px;">'.$val.'</textarea></div>');
}
public static function render($val = null)
{
echo ('<div id="editor_panel"></div><div><textarea id="editor_area" name="editor" style="width:100%; height:320px;">'.$val.'</textarea></div>');
}
}

View File

@@ -1,162 +1,163 @@
<?php
// Add plugin navigation link
Navigation::add(__('Files', 'filesmanager'), 'content', 'filesmanager', 3);
// Add plugin navigation link
Navigation::add(__('Files', 'filesmanager'), 'content', 'filesmanager', 3);
/**
* Filesmanager Admin Class
*/
class FilesmanagerAdmin extends Backend
{
/**
* Filesmanager Admin Class
* Main function
*/
class FilesmanagerAdmin extends Backend {
public static function main()
{
// Array of forbidden types
$forbidden_types = array('html', 'htm', 'js', 'jsb', 'mhtml', 'mht',
'php', 'phtml', 'php3', 'php4', 'php5', 'phps',
'shtml', 'jhtml', 'pl', 'py', 'cgi', 'sh', 'ksh', 'bsh', 'c', 'htaccess', 'htpasswd',
'exe', 'scr', 'dll', 'msi', 'vbs', 'bat', 'com', 'pif', 'cmd', 'vxd', 'cpl');
/**
* Main function
*/
public static function main() {
// Array of image types
$image_types = array('jpg', 'png', 'bmp', 'gif', 'tif');
// Array of forbidden types
$forbidden_types = array('html', 'htm', 'js', 'jsb', 'mhtml', 'mht',
'php', 'phtml', 'php3', 'php4', 'php5', 'phps',
'shtml', 'jhtml', 'pl', 'py', 'cgi', 'sh', 'ksh', 'bsh', 'c', 'htaccess', 'htpasswd',
'exe', 'scr', 'dll', 'msi', 'vbs', 'bat', 'com', 'pif', 'cmd', 'vxd', 'cpl');
// Get Site url
$site_url = Option::get('siteurl');
// Array of image types
$image_types = array('jpg', 'png', 'bmp', 'gif', 'tif');
// Get Site url
$site_url = Option::get('siteurl');
// Init vars
if (Request::get('path')) $path = Request::get('path'); else $path = 'uploads/';
// Add slash if not exists
if (substr($path, -1, 1) != '/') {
$path .= '/';
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
// Upload corectly!
if ($path == 'uploads' || $path == 'uploads//') {
$path = 'uploads/';
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
// Only 'uploads' folder!
if (strpos($path, 'uploads') === false) {
$path = 'uploads/';
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
// Set default path value if path is empty
if ($path == '') {
$path = 'uploads/';
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
$files_path = ROOT . DS . 'public' . DS . $path;
$files_list = array();
$current = explode('/', $path);
// Get information about current path
$_list = FilesmanagerAdmin::fdir($files_path);
$files_list = array();
// Get files
if (isset($_list['files'])) {
foreach ($_list['files'] as $files) {
$files_list[] = $files;
}
}
$dir_list = array();
// Get dirs
if (isset($_list['dirs'])) {
foreach ($_list['dirs'] as $dirs) {
if (strpos($dirs, '.') === false) $dir_list[] = $dirs;
}
}
// Delete file
// -------------------------------------
if (Request::get('id') == 'filesmanager' && Request::get('delete_file')) {
if (Security::check(Request::get('token'))) {
File::delete($files_path.Request::get('delete_file'));
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
} else { die('csrf detected!'); }
}
// Delete dir
// -------------------------------------
if (Request::get('id') == 'filesmanager' && Request::get('delete_dir')) {
if (Security::check(Request::get('token'))) {
Dir::delete($files_path.Request::get('delete_dir'));
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
} else { die('csrf detected!'); }
}
// Upload file
// -------------------------------------
if (Request::post('upload_file')) {
if (Security::check(Request::post('csrf'))) {
if ($_FILES['file']) {
if ( ! in_array(File::ext($_FILES['file']['name']), $forbidden_types)) {
move_uploaded_file($_FILES['file']['tmp_name'], $files_path.Security::safeName(basename($_FILES['file']['name'], File::ext($_FILES['file']['name'])), '-', true).'.'.File::ext($_FILES['file']['name']));
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
}
} else { die('csrf detected!'); }
}
// Display view
View::factory('box/filesmanager/views/backend/index')
->assign('path', $path)
->assign('current', $current)
->assign('files_list', $files_list)
->assign('dir_list', $dir_list)
->assign('forbidden_types', $forbidden_types)
->assign('image_types', $image_types)
->assign('site_url', $site_url)
->assign('files_path', $files_path)
->display();
// Init vars
if (Request::get('path')) $path = Request::get('path'); else $path = 'uploads/';
// Add slash if not exists
if (substr($path, -1, 1) != '/') {
$path .= '/';
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
// Upload corectly!
if ($path == 'uploads' || $path == 'uploads//') {
$path = 'uploads/';
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
/**
* Get directories and files in current path
*/
protected static function fdir($dir, $type = null) {
$files = array();
$c = 0;
$_dir = $dir;
if (is_dir($dir)) {
$dir = opendir ($dir);
while (false !== ($file = readdir($dir))) {
if (($file !=".") && ($file !="..")) {
$c++;
if (is_dir($_dir.$file)) {
$files['dirs'][$c] = $file;
} else {
$files['files'][$c] = $file;
}
}
}
closedir($dir);
return $files;
} else {
return false;
// Only 'uploads' folder!
if (strpos($path, 'uploads') === false) {
$path = 'uploads/';
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
// Set default path value if path is empty
if ($path == '') {
$path = 'uploads/';
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
$files_path = ROOT . DS . 'public' . DS . $path;
$files_list = array();
$current = explode('/', $path);
// Get information about current path
$_list = FilesmanagerAdmin::fdir($files_path);
$files_list = array();
// Get files
if (isset($_list['files'])) {
foreach ($_list['files'] as $files) {
$files_list[] = $files;
}
}
$dir_list = array();
// Get dirs
if (isset($_list['dirs'])) {
foreach ($_list['dirs'] as $dirs) {
if (strpos($dirs, '.') === false) $dir_list[] = $dirs;
}
}
// Delete file
// -------------------------------------
if (Request::get('id') == 'filesmanager' && Request::get('delete_file')) {
if (Security::check(Request::get('token'))) {
File::delete($files_path.Request::get('delete_file'));
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
} else { die('csrf detected!'); }
}
// Delete dir
// -------------------------------------
if (Request::get('id') == 'filesmanager' && Request::get('delete_dir')) {
if (Security::check(Request::get('token'))) {
Dir::delete($files_path.Request::get('delete_dir'));
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
} else { die('csrf detected!'); }
}
// Upload file
// -------------------------------------
if (Request::post('upload_file')) {
if (Security::check(Request::post('csrf'))) {
if ($_FILES['file']) {
if ( ! in_array(File::ext($_FILES['file']['name']), $forbidden_types)) {
move_uploaded_file($_FILES['file']['tmp_name'], $files_path.Security::safeName(basename($_FILES['file']['name'], File::ext($_FILES['file']['name'])), '-', true).'.'.File::ext($_FILES['file']['name']));
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
}
} else { die('csrf detected!'); }
}
// Display view
View::factory('box/filesmanager/views/backend/index')
->assign('path', $path)
->assign('current', $current)
->assign('files_list', $files_list)
->assign('dir_list', $dir_list)
->assign('forbidden_types', $forbidden_types)
->assign('image_types', $image_types)
->assign('site_url', $site_url)
->assign('files_path', $files_path)
->display();
}
/**
* Get directories and files in current path
*/
protected static function fdir($dir, $type = null)
{
$files = array();
$c = 0;
$_dir = $dir;
if (is_dir($dir)) {
$dir = opendir ($dir);
while (false !== ($file = readdir($dir))) {
if (($file !=".") && ($file !="..")) {
$c++;
if (is_dir($_dir.$file)) {
$files['dirs'][$c] = $file;
} else {
$files['files'][$c] = $file;
}
}
}
closedir($dir);
return $files;
} else {
return false;
}
}
}

View File

@@ -1,34 +1,32 @@
<?php
/**
* Files manager plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.0.0
*
*/
/**
* Files manager plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.0.0
*
*/
// Register plugin
Plugin::register( __FILE__,
__('Files manager', 'filesmanager'),
__('Files manager', 'filesmanager'),
'1.0.0',
'Awilum',
'http://monstra.org/',
null,
'box');
// Register plugin
Plugin::register( __FILE__,
__('Files manager', 'filesmanager'),
__('Files manager', 'filesmanager'),
'1.0.0',
'Awilum',
'http://monstra.org/',
null,
'box');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) {
// Include Admin
Plugin::admin('filesmanager', 'box');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) {
}
// Include Admin
Plugin::admin('filesmanager', 'box');
}
// Add Plugin Javascript
Javascript::add('plugins/box/filesmanager/js/filesmanager.js', 'backend');
// Add Plugin Javascript
Javascript::add('plugins/box/filesmanager/js/filesmanager.js', 'backend');

View File

@@ -6,25 +6,23 @@
/**
* Information Admin Class
*/
class InformationAdmin extends Backend {
class InformationAdmin extends Backend
{
/**
* Information main function
*/
public static function main() {
public static function main()
{
// Init vars
$php_modules = array();
// Get array with the names of all modules compiled and loaded
$php_modules = get_loaded_extensions();
// Display view
// Display view
View::factory('box/information/views/backend/index')
->assign('php_modules', $php_modules)
->display();
}
}

View File

@@ -11,7 +11,6 @@
*
*/
// Register plugin
Plugin::register( __FILE__,
__('Information', 'information'),
@@ -22,7 +21,6 @@
null,
'box');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) {
// Include Information Admin

View File

@@ -1,281 +1,273 @@
<?php
// Add plugin navigation link
Navigation::add(__('Menu', 'menu'), 'content', 'menu', 4);
// Add plugin navigation link
Navigation::add(__('Menu', 'menu'), 'content', 'menu', 4);
/**
* Menu Admin Class
*/
class MenuAdmin extends Backend
{
/**
* Menu table
*
* @var object
*/
public static $menu = null;
/**
* Menu Admin Class
* Main
*/
class MenuAdmin extends Backend {
public static function main()
{
// Get menu table
MenuAdmin::$menu = new Table('menu');
// Get pages table
$pages = new Table('pages');
/**
* Menu table
*
* @var object
*/
public static $menu = null;
// Create target array
$menu_item_target_array = array( '' => '',
'_blank' => '_blank',
'_parent' => '_parent',
'_top' => '_top');
// Create order array
$menu_item_order_array = range(0, 20);
/**
* Main
*/
public static function main() {
// Check for get actions
// ---------------------------------------------
if (Request::get('action')) {
// Get menu table
MenuAdmin::$menu = new Table('menu');
// Switch actions
// -----------------------------------------
switch (Request::get('action')) {
// Get pages table
$pages = new Table('pages');
// Create target array
$menu_item_target_array = array( '' => '',
'_blank' => '_blank',
'_parent' => '_parent',
'_top' => '_top');
// Create order array
$menu_item_order_array = range(0, 20);
// Check for get actions
// ---------------------------------------------
if (Request::get('action')) {
// Switch actions
// Edit menu item
// -----------------------------------------
switch (Request::get('action')) {
case "edit":
// Edit menu item
// -----------------------------------------
case "edit":
// Select item
$item = MenuAdmin::$menu->select('[id="'.Request::get('item_id').'"]', null);
// Select item
$item = MenuAdmin::$menu->select('[id="'.Request::get('item_id').'"]', null);
$menu_item_name = $item['name'];
$menu_item_link = $item['link'];
$menu_item_category = $item['category'];
$menu_item_target = $item['target'];
$menu_item_order = $item['order'];
$menu_item_name = $item['name'];
$menu_item_link = $item['link'];
$menu_item_category = $item['category'];
$menu_item_target = $item['target'];
$menu_item_order = $item['order'];
$errors = array();
$errors = array();
// Edit current menu item
if (Request::post('menu_add_item')) {
// Edit current menu item
if (Request::post('menu_add_item')) {
if (Security::check(Request::post('csrf'))) {
if (Security::check(Request::post('csrf'))) {
if (trim(Request::post('menu_item_name')) == '') {
if (trim(Request::post('menu_item_name')) == '') {
if (Request::post('menu_item_name')) $menu_item_name = Request::post('menu_item_name'); else $menu_item_name = $item['name'];
if (Request::post('menu_item_link')) $menu_item_link = Request::post('menu_item_link'); else $menu_item_link = $item['link'];
if (Request::post('menu_item_category')) $menu_item_category = Request::post('menu_item_category'); else $menu_item_category = $item['category'];
if (Request::post('menu_item_target')) $menu_item_target = Request::post('menu_item_target'); else $menu_item_target = $item['target'];
if (Request::post('menu_item_order')) $menu_item_order = Request::post('menu_item_order'); else $menu_item_order = $item['order'];
if (Request::post('menu_item_name')) $menu_item_name = Request::post('menu_item_name'); else $menu_item_name = $item['name'];
if (Request::post('menu_item_link')) $menu_item_link = Request::post('menu_item_link'); else $menu_item_link = $item['link'];
if (Request::post('menu_item_category')) $menu_item_category = Request::post('menu_item_category'); else $menu_item_category = $item['category'];
if (Request::post('menu_item_target')) $menu_item_target = Request::post('menu_item_target'); else $menu_item_target = $item['target'];
if (Request::post('menu_item_order')) $menu_item_order = Request::post('menu_item_order'); else $menu_item_order = $item['order'];
$errors['menu_item_name_empty'] = __('Required field', 'menu');
}
$errors['menu_item_name_empty'] = __('Required field', 'menu');
}
// Update menu item
if (count($errors) == 0) {
MenuAdmin::$menu->update(Request::get('item_id'),
array('name' => Request::post('menu_item_name'),
'link' => Request::post('menu_item_link'),
'category' => Security::safeName(Request::post('menu_item_category'), '-', true),
'target' => Request::post('menu_item_target'),
'order' => Request::post('menu_item_order')));
// Update menu item
if (count($errors) == 0) {
MenuAdmin::$menu->update(Request::get('item_id'),
array('name' => Request::post('menu_item_name'),
'link' => Request::post('menu_item_link'),
'category' => Security::safeName(Request::post('menu_item_category'), '-', true),
'target' => Request::post('menu_item_target'),
'order' => Request::post('menu_item_order')));
Request::redirect('index.php?id=menu');
}
Request::redirect('index.php?id=menu');
}
} else { die('csrf detected!'); }
} else { die('csrf detected!'); }
}
// Display view
View::factory('box/menu/views/backend/edit')
->assign('menu_item_name', $menu_item_name)
->assign('menu_item_link', $menu_item_link)
->assign('menu_item_category', $menu_item_category)
->assign('menu_item_target', $menu_item_target)
->assign('menu_item_order', $menu_item_order)
->assign('menu_item_target_array', $menu_item_target_array)
->assign('menu_item_order_array', $menu_item_order_array)
->assign('errors', $errors)
->assign('categories', MenuAdmin::getCategories())
->assign('pages_list', MenuAdmin::getPages())
->assign('components_list', MenuAdmin::getComponents())
->display();
break;
// Add menu item
// -----------------------------------------
case "add":
$menu_item_name = '';
$menu_item_link = '';
$menu_item_category = '';
$menu_item_target = '';
$menu_item_order = '';
$errors = array();
// Get current category
$menu_item_category = $current_category = (Request::get('category')) ? Request::get('category') : '' ;
// Add new menu item
if (Request::post('menu_add_item')) {
if (Security::check(Request::post('csrf'))) {
if (trim(Request::post('menu_item_name')) == '') {
if (Request::post('menu_item_name')) $menu_item_name = Request::post('menu_item_name'); else $menu_item_name = '';
if (Request::post('menu_item_link')) $menu_item_link = Request::post('menu_item_link'); else $menu_item_link = '';
if (Request::post('menu_item_category')) $menu_item_category = Request::post('menu_item_category'); else $menu_item_category = $current_category;
if (Request::post('menu_item_target')) $menu_item_target = Request::post('menu_item_target'); else $menu_item_target = '';
if (Request::post('menu_item_order')) $menu_item_order = Request::post('menu_item_order'); else $menu_item_order = '';
$errors['menu_item_name_empty'] = __('Required field', 'menu');
}
// Insert new menu item
if (count($errors) == 0) {
MenuAdmin::$menu->insert(array('name' => Request::post('menu_item_name'),
'link' => Request::post('menu_item_link'),
'category' => Security::safeName(Request::post('menu_item_category'), '-', true),
'target' => Request::post('menu_item_target'),
'order' => Request::post('menu_item_order')));
Request::redirect('index.php?id=menu');
}
} else { die('csrf detected!'); }
}
// Display view
View::factory('box/menu/views/backend/add')
->assign('menu_item_name', $menu_item_name)
->assign('menu_item_link', $menu_item_link)
->assign('menu_item_category', $menu_item_category)
->assign('menu_item_target', $menu_item_target)
->assign('menu_item_order', $menu_item_order)
->assign('menu_item_target_array', $menu_item_target_array)
->assign('menu_item_order_array', $menu_item_order_array)
->assign('errors', $errors)
->assign('categories', MenuAdmin::getCategories())
->assign('pages_list', MenuAdmin::getPages())
->assign('components_list', MenuAdmin::getComponents())
->display();
break;
}
} else {
// Delete menu item
if (Request::get('delete_item')) {
MenuAdmin::$menu->delete((int)Request::get('delete_item'));
}
// Display view
View::factory('box/menu/views/backend/index')
->assign('categories', MenuAdmin::getCategories())
->assign('menu', MenuAdmin::$menu)
->display();
}
}
/**
* Get categories
*/
public static function getCategories() {
$categories = array();
$_categories = MenuAdmin::$menu->select(null, 'all', null, array('category'));
foreach($_categories as $category) {
$categories[] = $category['category'];
}
return array_unique($categories);
}
/**
* Get pages
*/
protected static function getPages() {
// Init vars
$pages_array = array();
$count = 0;
// Get pages table
$pages = new Table('pages');
// Get Pages List
$pages_list = $pages->select('[slug!="error404" and status="published"]');
foreach ($pages_list as $page) {
$pages_array[$count]['title'] = Html::toText($page['title']);
$pages_array[$count]['parent'] = $page['parent'];
$pages_array[$count]['date'] = $page['date'];
$pages_array[$count]['author'] = $page['author'];
$pages_array[$count]['slug'] = ($page['slug'] == Option::get('defaultpage')) ? '' : $page['slug'] ;
if (isset($page['parent'])) {
$c_p = $page['parent'];
} else {
$c_p = '';
}
if ($c_p != '') {
$_page = $pages->select('[slug="'.$page['parent'].'"]', null);
if (isset($_page['title'])) {
$_title = $_page['title'];
} else {
$_title = '';
}
$pages_array[$count]['sort'] = $_title . ' ' . $page['title'];
} else {
$pages_array[$count]['sort'] = $page['title'];
}
$_title = '';
$count++;
// Display view
View::factory('box/menu/views/backend/edit')
->assign('menu_item_name', $menu_item_name)
->assign('menu_item_link', $menu_item_link)
->assign('menu_item_category', $menu_item_category)
->assign('menu_item_target', $menu_item_target)
->assign('menu_item_order', $menu_item_order)
->assign('menu_item_target_array', $menu_item_target_array)
->assign('menu_item_order_array', $menu_item_order_array)
->assign('errors', $errors)
->assign('categories', MenuAdmin::getCategories())
->assign('pages_list', MenuAdmin::getPages())
->assign('components_list', MenuAdmin::getComponents())
->display();
break;
// Add menu item
// -----------------------------------------
case "add":
$menu_item_name = '';
$menu_item_link = '';
$menu_item_category = '';
$menu_item_target = '';
$menu_item_order = '';
$errors = array();
// Get current category
$menu_item_category = $current_category = (Request::get('category')) ? Request::get('category') : '' ;
// Add new menu item
if (Request::post('menu_add_item')) {
if (Security::check(Request::post('csrf'))) {
if (trim(Request::post('menu_item_name')) == '') {
if (Request::post('menu_item_name')) $menu_item_name = Request::post('menu_item_name'); else $menu_item_name = '';
if (Request::post('menu_item_link')) $menu_item_link = Request::post('menu_item_link'); else $menu_item_link = '';
if (Request::post('menu_item_category')) $menu_item_category = Request::post('menu_item_category'); else $menu_item_category = $current_category;
if (Request::post('menu_item_target')) $menu_item_target = Request::post('menu_item_target'); else $menu_item_target = '';
if (Request::post('menu_item_order')) $menu_item_order = Request::post('menu_item_order'); else $menu_item_order = '';
$errors['menu_item_name_empty'] = __('Required field', 'menu');
}
// Insert new menu item
if (count($errors) == 0) {
MenuAdmin::$menu->insert(array('name' => Request::post('menu_item_name'),
'link' => Request::post('menu_item_link'),
'category' => Security::safeName(Request::post('menu_item_category'), '-', true),
'target' => Request::post('menu_item_target'),
'order' => Request::post('menu_item_order')));
Request::redirect('index.php?id=menu');
}
} else { die('csrf detected!'); }
}
// Display view
View::factory('box/menu/views/backend/add')
->assign('menu_item_name', $menu_item_name)
->assign('menu_item_link', $menu_item_link)
->assign('menu_item_category', $menu_item_category)
->assign('menu_item_target', $menu_item_target)
->assign('menu_item_order', $menu_item_order)
->assign('menu_item_target_array', $menu_item_target_array)
->assign('menu_item_order_array', $menu_item_order_array)
->assign('errors', $errors)
->assign('categories', MenuAdmin::getCategories())
->assign('pages_list', MenuAdmin::getPages())
->assign('components_list', MenuAdmin::getComponents())
->display();
break;
}
// Sort pages
$_pages_list = Arr::subvalSort($pages_array, 'sort');
} else {
// return
return $_pages_list;
}
/**
* Get components
*/
protected static function getComponents() {
$components = array();
if (count(Plugin::$components) > 0) {
foreach (Plugin::$components as $component) {
if ($component !== 'pages' && $component !== 'sitemap') $components[] = Text::lowercase($component);
}
// Delete menu item
if (Request::get('delete_item')) {
MenuAdmin::$menu->delete((int) Request::get('delete_item'));
}
return $components;
// Display view
View::factory('box/menu/views/backend/index')
->assign('categories', MenuAdmin::getCategories())
->assign('menu', MenuAdmin::$menu)
->display();
}
}
/**
* Get categories
*/
public static function getCategories()
{
$categories = array();
$_categories = MenuAdmin::$menu->select(null, 'all', null, array('category'));
foreach ($_categories as $category) {
$categories[] = $category['category'];
}
return array_unique($categories);
}
/**
* Get pages
*/
protected static function getPages()
{
// Init vars
$pages_array = array();
$count = 0;
// Get pages table
$pages = new Table('pages');
// Get Pages List
$pages_list = $pages->select('[slug!="error404" and status="published"]');
foreach ($pages_list as $page) {
$pages_array[$count]['title'] = Html::toText($page['title']);
$pages_array[$count]['parent'] = $page['parent'];
$pages_array[$count]['date'] = $page['date'];
$pages_array[$count]['author'] = $page['author'];
$pages_array[$count]['slug'] = ($page['slug'] == Option::get('defaultpage')) ? '' : $page['slug'] ;
if (isset($page['parent'])) {
$c_p = $page['parent'];
} else {
$c_p = '';
}
if ($c_p != '') {
$_page = $pages->select('[slug="'.$page['parent'].'"]', null);
if (isset($_page['title'])) {
$_title = $_page['title'];
} else {
$_title = '';
}
$pages_array[$count]['sort'] = $_title . ' ' . $page['title'];
} else {
$pages_array[$count]['sort'] = $page['title'];
}
$_title = '';
$count++;
}
// Sort pages
$_pages_list = Arr::subvalSort($pages_array, 'sort');
// return
return $_pages_list;
}
/**
* Get components
*/
protected static function getComponents()
{
$components = array();
if (count(Plugin::$components) > 0) {
foreach (Plugin::$components as $component) {
if ($component !== 'pages' && $component !== 'sitemap') $components[] = Text::lowercase($component);
}
}
return $components;
}
}

View File

@@ -1,63 +1,58 @@
<?php
/**
* Menu plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.0.0
*
*/
// Register plugin
Plugin::register( __FILE__,
__('Menu', 'menu'),
__('Menu manager', 'menu'),
'1.0.0',
'Awilum',
'http://monstra.org/',
null,
'box');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) {
// Include Admin
Plugin::admin('menu', 'box');
}
// Add Plugin Javascript
Javascript::add('plugins/box/menu/js/menu.js', 'backend');
/**
* Menu Class
*/
class Menu
{
/**
* Menu plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.0.0
* Get menu
*
* @param string $category Category name
*/
public static function get($category = '')
{
// Get menu table
$menu = new Table('menu');
// Register plugin
Plugin::register( __FILE__,
__('Menu', 'menu'),
__('Menu manager', 'menu'),
'1.0.0',
'Awilum',
'http://monstra.org/',
null,
'box');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) {
// Include Admin
Plugin::admin('menu', 'box');
// Display view
View::factory('box/menu/views/frontend/index')
->assign('items', $menu->select('[category="'.$category.'"]', 'all', null, array('id', 'name', 'link', 'target', 'order', 'category'), 'order', 'ASC'))
->assign('uri', Uri::segments())
->assign('defpage', Option::get('defaultpage'))
->display();
}
// Add Plugin Javascript
Javascript::add('plugins/box/menu/js/menu.js', 'backend');
/**
* Menu Class
*/
class Menu {
/**
* Get menu
*
* @param string $category Category name
*/
public static function get($category = '') {
// Get menu table
$menu = new Table('menu');
// Display view
View::factory('box/menu/views/frontend/index')
->assign('items', $menu->select('[category="'.$category.'"]', 'all', null, array('id', 'name', 'link', 'target', 'order', 'category'), 'order', 'ASC'))
->assign('uri', Uri::segments())
->assign('defpage', Option::get('defaultpage'))
->display();
}
}
}

Some files were not shown because too many files have changed in this diff Show More