1
0
mirror of https://github.com/monstra-cms/monstra.git synced 2025-07-31 18:30:20 +02:00

Add Monstra from HG Commit 683dcb70c4cc

This commit is contained in:
Awilum
2012-09-25 19:09:50 +03:00
parent d2db42b2bb
commit 4a5fea5f5b
251 changed files with 35026 additions and 0 deletions

26
.htaccess Normal file
View File

@@ -0,0 +1,26 @@
#
# Monstra CMS :: php & apache settings
#
# Set default charset utf-8
AddDefaultCharset UTF-8
# Don't show directory listings for URLs which map to a directory.
Options -Indexes
# PHP 5, Apache 1 and 2.
<IfModule mod_php5.c>
php_flag magic_quotes_gpc off
php_flag magic_quotes_sybase off
php_flag register_globals off
</IfModule>
# Setting rewrite rules.
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /%siteurlhere%/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

153
admin/index.php Normal file
View File

@@ -0,0 +1,153 @@
<?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.
*/
// Main engine defines
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', rtrim(str_replace(array('admin'), array(''), dirname(__FILE__)), '\\/'));
define('BACKEND', true);
define('MONSTRA_ACCESS', true);
// Load bootstrap file
require_once(ROOT . DS . 'monstra' . DS . 'bootstrap.php');
// Errors var when users login failed
$login_error = '';
// Admin login
if (Request::post('login_submit')) {
// Sleep MONSTRA_LOGIN_SLEEP seconds for blocking Brute Force Attacks
sleep(MONSTRA_LOGIN_SLEEP);
// Get users Table
$users = new Table('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();
// Reset password
if (Request::post('reset_password_submit')) {
// Get users Table
$users = new Table('users');
// Get user
$user = $users->select("[login='" . trim(Request::post('login')) . "']", null);
// Check
if (count($user) == 0) $errors['users_doesnt_exist'] = __('This user does not exist', 'users');
if (Option::get('captcha_installed') == 'true' && ! CryptCaptcha::check(Request::post('answer'))) $errors['users_captcha_wrong'] = __('Captcha code is wrong', 'captcha');
// If Errors Count is 0
if (count($errors) == 0) {
// Generate new password
$new_password = Text::random('alnum', 6);
// Update user profile
$users->updateWhere("[login='" . trim(Request::post('login')) . "']", array('password' => Security::encryptPassword($new_password)));
// Message
$message = "Login: {$user['login']}\nNew Password: {$new_password}";
// Send
@mail($user['email'], 'MonstraPasswordReset', $message);
}
Notification::setNow('reset_password_error', 'reset_password_error');
}
// If admin user is login = true then set is_admin = true
if (Session::exists('admin')) {
if (Session::get('admin') == true) {
$is_admin = true;
}
} else {
$is_admin = false;
}
// Logout user from system
if (Request::get('logout') && Request::get('logout') == 'do') {
Session::destroy();
}
// If is admin then load admin area
if ($is_admin) {
// If id is empty then redirect to default plugin PAGES
if (Request::get('id')) {
if (Request::get('sub_id')) {
$area = Request::get('sub_id');
} else {
$area = Request::get('id');
}
} else {
Request::redirect('index.php?id=pages');
}
$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

@@ -0,0 +1,445 @@
/************************************
Monstra
http://monstra.org
styles.css, v1.0.0
12 Septemper 2012
*************************************
CONTENTS
1. GENERAL
2. HEADER
3. CONTENT
4. LEFT MENU
5. AUTHORIZATION
6. TABLE
7. BUTTONS
8. TABS
9. MISC
*************************************
1. GENERAL
*************************************/
body {
padding-top: 60px;
margin: 0;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 13px;
line-height: 18px;
color: #333333;
background-color: #ffffff;
}
h1,
h2,
h3,
h4,
h5,
h6 {
margin: 0;
font-family: inherit;
font-weight: bold;
color: inherit;
text-rendering: optimizelegibility;
}
h1 small,
h2 small,
h3 small,
h4 small,
h5 small,
h6 small {
font-weight: normal;
color: #999999;
}
h1 {
font-size: 30px;
line-height: 36px;
}
h1 small {
font-size: 18px;
}
h2 {
font-size: 24px;
line-height: 36px;
}
h2 small {
font-size: 18px;
}
h3 {
line-height: 27px;
font-size: 16px;
}
h3 small {
font-size: 14px;
}
h4,
h5,
h6 {
line-height: 18px;
}
h4 {
font-size: 14px;
}
h4 small {
font-size: 12px;
}
h5 {
font-size: 12px;
}
h6 {
font-size: 11px;
color: #999999;
text-transform: uppercase;
}
/**************************************
2. HEADER
*************************************/
.monstra-header {
top: 0;
left: 0;
right: 0;
margin-top:-60px;
position: relative;
z-index:999;
}
.monstra-header h3 a:hover, .monstra-header .brand:hover, .monstra-header ul .active > a {
color: #ffffff;
text-decoration: none;
}
.monstra-header h3 {
position: relative;
}
.monstra-header h3 a, .monstra-header .brand {
float: left;
display: block;
padding-top:6px;
padding-left:1px;
margin-left: 0px;
color: #fdfdfd;
font-family: arial;
font-weight: 600;
line-height: 1;
font-size: 24px;
text-shadow: 0 1px 2px rgba(0,0,0,.5);
width:188px;
}
.monstra-header p {
margin: 0;
line-height: 60px;
}
.monstra-header-inner, .topbar .fill {
background-color: #ccc;
background: url('@theme_admin_url/img/header.png');
-webkit-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1);
-moz-box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1);
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.25), inset 0 -1px 0 rgba(0, 0, 0, 0.1);
}
/*************************************
3. CONTENT
*************************************/
.monstra-content {
padding-top:20px;
}
/*************************************
4. LEFT MENU
*************************************/
.monstra-menu-category-separator {
border: 0;
border-bottom: 1px solid #ccc;
margin-top:5px;
margin-bottom:8px;
}
.monstra-menu-sidebar {
background: url('@theme_admin_url/img/sidebar_bg.png');
background-color:#ccc;
max-width:192px!important;
min-width:136px!important;
margin-bottom: 20px;
padding: 19px;
border-bottom:2px solid #ccc;
}
.monstra-menu-sidebar ul {
clear: both;
margin: 0;
padding: 0;
font-family: 'lucida grande','Lucida Sans Unicode', Tahoma, sans-serif;
}
.monstra-menu-sidebar li {
list-style: none;
margin: 0 0 0 -22px;
padding: 0;
}
.monstra-menu-sidebar li a {
width:97%;
color: #333;
padding-left: 23px;
text-decoration: none;
display: inline-block;
height: 20px;
line-height: 20px;
text-shadow: 0 1px 0 #fff;
margin: 2px 0;
}
.monstra-menu-sidebar li a.current {
color: #000;
padding-top:3px;
cursor: pointer;
display: inline-block;
background-color: #e6e6e6;
background-repeat: no-repeat;
background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#ffffff), color-stop(25%, #ffffff), to(#e6e6e6));
background-image: -webkit-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
background-image: -moz-linear-gradient(top, #ffffff, #ffffff 25%, #e6e6e6);
background-image: -ms-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
background-image: -o-linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
background-image: linear-gradient(#ffffff, #ffffff 25%, #e6e6e6);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#e6e6e6', GradientType=0);
text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75);
line-height: normal;
border: 1px solid #ccc;
border-bottom-color: #bbb;
border-right:2px solid #ccc;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
-moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
-webkit-transition: 0.1s linear all;
-moz-transition: 0.1s linear all;
-ms-transition: 0.1s linear all;
-o-transition: 0.1s linear all;
transition: 0.1s linear all;
}
.monstra-menu-sidebar li a:hover {
color: #000;
background:#fff;
}
.nav-list > .active > a,
.nav-list > .active > a:hover {
color: #ffffff;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2);
background-color: #0088cc;
}
/*************************************
5. AUTHORIZATION
*************************************/
.authorization-block {
margin: 0 auto;
float: none!important;
}
.authorization-block-footer {
margin: 0 auto;
float: none!important;
margin-top:10px;
margin-bottom:10px;
}
.login-body {
background:#F2F2F2;
}
/*************************************
6. TABLE
*************************************/
table {
max-width: 100%;
border-collapse: collapse;
border-spacing: 0;
background-color: transparent;
}
.table {
width: 100%;
margin-bottom: 18px;
}
.table th,
.table td {
padding: 8px;
line-height: 18px;
text-align: left;
border-top: 1px solid #dddddd;
}
.table th {
font-weight: bold;
}
.table thead th {
vertical-align: bottom;
}
.table colgroup + thead tr:first-child th,
.table colgroup + thead tr:first-child td,
.table thead:first-child tr:first-child th,
.table thead:first-child tr:first-child td {
border-top: 0;
}
.table tbody + tbody {
border-top: 2px solid #dddddd;
}
.table-condensed th,
.table-condensed td {
padding: 4px 5px;
}
.table-bordered {
border: 1px solid #dddddd;
border-left: 0;
border-collapse: separate;
*border-collapse: collapsed;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.table-bordered th:first-child,
.table-bordered td:first-child {
border-left: 1px solid #dddddd;
}
.table-bordered td:first-child {
padding-left:15px;
}
.table-bordered thead:first-child tr:first-child th,
.table-bordered tbody:first-child tr:first-child th,
.table-bordered tbody:first-child tr:first-child td {
border-top: 0;
}
.table-bordered thead:first-child tr:first-child th:first-child,
.table-bordered tbody:first-child tr:first-child td:first-child {
-webkit-border-radius: 4px 0 0 0;
-moz-border-radius: 4px 0 0 0;
border-radius: 4px 0 0 0;
}
.table-bordered thead:first-child tr:first-child th:last-child,
.table-bordered tbody:first-child tr:first-child td:last-child {
-webkit-border-radius: 0 4px 0 0;
-moz-border-radius: 0 4px 0 0;
border-radius: 0 4px 0 0;
}
.table-bordered thead:last-child tr:last-child th:first-child,
.table-bordered tbody:last-child tr:last-child td:first-child {
-webkit-border-radius: 0 0 0 4px;
-moz-border-radius: 0 0 0 4px;
border-radius: 0 0 0 4px;
}
.table-bordered thead tr td {
font-weight:bold;
background-color: #f5f5f5;
background-repeat: repeat-x;
background-image: -khtml-gradient(linear, left top, left bottom, from(#ffffff), to(#f5f5f5));
background-image: -moz-linear-gradient(top, #ffffff, #f5f5f5);
background-image: -ms-linear-gradient(top, #ffffff, #f5f5f5);
background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #ffffff), color-stop(100%, #f5f5f5));
background-image: -webkit-linear-gradient(top, #ffffff, #f5f5f5);
background-image: -o-linear-gradient(top, #ffffff, #f5f5f5);
background-image: linear-gradient(top, #ffffff, #f5f5f5);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#f5f5f5', GradientType=0);
border-top: 1px solid #fff;
}
.table-bordered thead:last-child tr:last-child th:last-child,
.table-bordered tbody:last-child tr:last-child td:last-child {
-webkit-border-radius: 0 0 4px 0;
-moz-border-radius: 0 0 4px 0;
border-radius: 0 0 4px 0;
}
.table-striped tbody tr:nth-child(odd) td,
.table-striped tbody tr:nth-child(odd) th {
background-color: #f9f9f9;
}
.table tbody tr:hover td,
.table tbody tr:hover th {
background-color: #f5f5f5;
}
.table-bordered th, .table-bordered td {
border-left: none;
}
td, th {
display: table-cell;
vertical-align: inherit!important;
}
/*************************************
7. BUTTONS
*************************************/
.btn-toolbar {
margin:0;
}
.btn-group .btn {
margin-left: 5px;
}
.btn-actions-default {
-webkit-border-top-left-radius: 4px!important;
-moz-border-radius-topleft: 4px!important;
border-top-left-radius: 4px!important;
-webkit-border-bottom-left-radius: 4px!important;
-moz-border-radius-bottomleft: 4px!important;
border-bottom-left-radius: 4px!important;
}
/*************************************
8. TABS
*************************************/
.tab-pane > table {
margin-top:-18px;
}
.tab-pane > table {
border-top:none!important;
}
.tab-content {
overflow: visible;
}
/*************************************
9. MISC
*************************************/
.small-grey-text {
color:#333;
font-size: 10px;
}
.small-grey-text:hover {
color:#000;
}
.small-white-text {
color:#fff;
font-size: 10px;
}
.small-white-text:hover {
color:#fdfdfd;
}
.error-none {display:none;}
.error {color:red;}
.container-fluid {padding-left:0px;}
img {max-width:none;}

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 B

View File

@@ -0,0 +1,106 @@
<?php if ( ! defined('MONSTRA_ACCESS')) exit('No direct script access allowed'); ?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Monstra :: <?php echo __('Administration', 'system'); ?></title>
<meta name="description" content="Monstra admin area" />
<link rel="icon" href="<?php echo Option::get('siteurl'); ?>favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="<?php echo Option::get('siteurl'); ?>favicon.ico" type="image/x-icon" />
<!-- Styles -->
<?php Stylesheet::add('public/assets/css/bootstrap.css', 'backend', 1); ?>
<?php Stylesheet::add('public/assets/css/bootstrap-responsive.css', 'backend', 2); ?>
<?php Stylesheet::add('admin/themes/default/css/default.css', 'backend', 3); ?>
<?php Stylesheet::load(); ?>
<!-- JavaScripts -->
<?php Javascript::add('public/assets/js/jquery.js', 'backend', 1); ?>
<?php Javascript::add('public/assets/js/bootstrap.js', 'backend', 2); ?>
<?php Javascript::add('admin/themes/default/js/default.js', 'backend', 3); ?>
<?php Javascript::load(); ?>
<?php Action::run('admin_header'); ?>
<!--[if lt IE 9]>
<link rel="stylesheet" href="css/ie.css" type="text/css" media="screen" />
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<!-- Block_topbar -->
<div class="monstra-header">
<div class="monstra-header-inner">
<div class="container-fluid">
<a class="brand" href="<?php echo Option::get('siteurl'); ?>admin"><img src="<?php echo Option::get('siteurl'); ?>public/assets/img/monstra-logo-black.png" height="44" width="191"></a>
<p class="pull-right">
<?php Navigation::draw('top', Navigation::TOP); ?>
</p>
</div>
</div>
</div>
<!-- /Block_topbar -->
<!-- Block_container -->
<div class="container-fluid">
<div class="row-fluid">
<!-- Block_sidebar -->
<div class="span2 monstra-menu-sidebar">
<h3><?php echo __('Content', 'pages'); ?></h3>
<ul>
<?php Navigation::draw('content'); ?>
</ul>
<div class="monstra-menu-category-separator"></div>
<?php if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) { ?>
<h3><?php echo __('Extends', 'system'); ?></h3>
<ul>
<?php Navigation::draw('extends'); ?>
</ul>
<div class="monstra-menu-category-separator"></div>
<?php } ?>
<h3><?php echo __('System', 'system'); ?></h3>
<ul>
<?php Navigation::draw('system'); ?>
</ul>
</div>
<!-- /Block_sidebar -->
<!-- Block_content -->
<div class="span10 monstra-content">
<div id="update-monstra"></div>
<div><?php Action::run('admin_pre_template'); ?></div>
<div>
<?php
if ($plugin_admin_area) {
if (is_callable(ucfirst(Plugin::$plugins[$area]['id']).'Admin::main')) {
call_user_func(ucfirst(Plugin::$plugins[$area]['id']).'Admin::main');
} else {
echo '<div class="message-error">'.__('Plugin main admin function does not exist', 'system').'</div>';
}
} else {
echo '<div class="message-error">'.__('Plugin does not exist', 'system').'</div>';
}
?>
</div>
<div><?php Action::run('admin_post_template'); ?></div>
</div>
<!-- /Block_content -->
</div>
<!-- Block_footer -->
<footer>
<p align="right"><span class="badge"><span class="small-white-text">© 2012 <a href="http://monstra.org" class="small-white-text" target="_blank">Monstra</a> <?php echo __('Version', 'system'); ?> <?php echo MONSTRA_VERSION; ?></span></span></p>
</footer>
<!-- /Block_footer -->
</div>
<!-- /Block_container -->
</body>
</html>

View File

@@ -0,0 +1,19 @@
/**
* Monstra JS module
* @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.
* @filesource
*/
/* Confirm delete */
function confirmDelete(msg){var data=confirm(msg+" ?"); return data;}

View File

@@ -0,0 +1,120 @@
<?php if ( ! defined('MONSTRA_ACCESS')) exit('No direct script access allowed'); ?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Monstra :: <?php echo __('Administration', 'system'); ?></title>
<meta name="description" content="Monstra Admin Area">
<link rel="icon" href="<?php echo Option::get('siteurl'); ?>favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="<?php echo Option::get('siteurl'); ?>favicon.ico" type="image/x-icon" />
<!-- Styles -->
<?php Stylesheet::add('public/assets/css/bootstrap.css', 'backend', 1); ?>
<?php Stylesheet::add('public/assets/css/bootstrap-responsive.css', 'backend', 2); ?>
<?php Stylesheet::add('admin/themes/default/css/default.css', 'backend', 3); ?>
<?php Stylesheet::load(); ?>
<!-- JavaScripts -->
<?php Javascript::add('public/assets/js/jquery.js', 'backend', 1); ?>
<?php Javascript::add('public/assets/js/bootstrap.js', 'backend', 2); ?>
<?php Javascript::add('admin/themes/default/js/default.js', 'backend', 3); ?>
<?php Javascript::load(); ?>
<script type="text/javascript">
$().ready(function () {
<?php if (Notification::get('reset_password_error') == 'reset_password_error') { ?>
$('.reset-password-area, .administration-btn').show();
$('.administration-area, .reset-password-btn').hide();
<?php } else { ?>
$('.reset-password-area, .administration-btn').hide();
$('.administration-area, .reset-password-btn').show();
<?php } ?>
$('.reset-password-btn').click(function() {
$('.reset-password-area, .administration-btn').show();
$('.administration-area, .reset-password-btn').hide();
});
$('.administration-btn').click(function() {
$('.reset-password-area, .administration-btn').hide();
$('.administration-area, .reset-password-btn').show();
});
});
</script>
<?php Action::run('admin_header'); ?>
<!--[if lt IE 9]>
<link rel="stylesheet" href="css/ie.css" type="text/css" media="screen" />
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body class="login-body">
<div class="row">
<div class="well span3 authorization-block">
<div style="text-align:center;"><a class="brand" href="<?php echo Option::get('siteurl'); ?>admin"><img src="<?php echo Option::get('siteurl'); ?>public/assets/img/monstra-logo-black.png" height="44" width="191"></a></div>
<div class="administration-area">
<hr>
<div>
<h2 style="text-align:center;"><?php echo __('Administration', 'system'); ?></h2><br />
<form method="post">
<label><?php echo __('Username', 'users'); ?></label>
<input class="span3" name="login" type="text" />
<label><?php echo __('Password', 'users'); ?></label>
<input class="span3" name="password" type="password" />
<br />
<?php if (isset($login_error) && $login_error !== '') { ?><div class="alert alert-error"><?php echo $login_error; ?></div><?php } ?>
<input type="submit" name="login_submit" class="btn" value="<?php echo __('Enter', 'users'); ?>" />
</form>
</div>
</div>
<div class="reset-password-area">
<hr>
<div>
<h2 style="text-align:center;"><?php echo __('Reset Password', 'users'); ?></h2><br />
<form method="post">
<label><?php echo __('Username', 'users'); ?></label>
<input name="login" class="span3" type="text" />
<?php if (Option::get('captcha_installed') == 'true') { ?>
<label><?php echo __('Captcha'); ?><label>
<input type="text" name="answer" class="span3">
<?php CryptCaptcha::draw(); ?>
<?php } ?>
<br>
<?php
if (count($errors) > 0) {
foreach($errors as $error) {
Alert::error($error);
}
}
?>
<input type="submit" name="reset_password_submit" class="btn" value="<?php echo __('Send New Password', 'users')?>" />
</form>
</div>
</div>
<hr>
<div>
<div style="text-align:center;">
<a class="small-grey-text" href="<?php echo Option::get('siteurl'); ?>"><?php echo __('< Back to Website', 'system');?></a> -
<a class="small-grey-text reset-password-btn" href="javascript:;"><?php echo __('Forgot your password? >', 'system');?></a>
<a class="small-grey-text administration-btn" href="javascript:;"><?php echo __('Administration >', 'system');?></a>
</div>
</div>
</div>
</div>
<div class="row">
<div class="span4 authorization-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 MONSTRA_VERSION; ?></span>
</div>
</div>
</div>
</body>
</html>

0
backups/.empty Normal file
View File

1
backups/.htaccess Normal file
View File

@@ -0,0 +1 @@
Deny from all

110
changelog.txt Normal file
View File

@@ -0,0 +1,110 @@
Monstra 2.0.0, xxxx-xx-xx
------------------------
- Idiorm Added! Idiorm - a lightweight nearly-zero-configuration object-relational mapper and fluent query builder for PHP5.
- Add new Crypt Capthca Plugin
- Users Plugin: add ability to close users frontend registration. Updated frontend and backend templates. Using Capthca Plugin instead of Captca Helper for more secure.
- Admin Password Reset Page: Capthca Plugin added.
- Backup Plugin: Loading state button added. Shows "Creating..." while site backups create.
- Improved Admin Theme - built with best frontend optimization practice. Updated architecture and User Interface. Admin theme more responsive now!
- Added Twitter Bootstrap 2.1.1.
- New Default Theme: built with best frontend optimization practice.
- Options API: update get() method. Return empty string if option value doesnt exists.
- CSS variables: Added - @theme_site_url @theme_admin_url Deleted - @theme_url
- Themes Plugin: add ability to create/edit/clone JavaScripts. Add ability to change admin theme in one click.
- Apply filter 'content' to Blocks
- Array Helper: get() method improved. New methods keyExists() isAssoc() set() delete() random() added.
- Plugins API: Fix Javascript and Stylesheet class.
- New options theme_admin_name theme_site_name users_frontend_registration added.
- Update translates.
- Path updates.
- And a lot of general engine improvements.
Monstra 1.3.1, 2012-09-02
------------------------
- Fix Plugins Output
Monstra 1.3.0, 2012-09-01
------------------------
- Improve Multi-user system. Front-end registration, authorization, profile editing added.
- Improve Default Monstra theme.
- Security: Fix Script Insertion Vulnerability.
- Blocks and Snippets plugins code fix. Issue #35, Issue #34
- XMLDB: new method updateField()
- Plugin API: path updates.
- Dir Helper: new method size()
- Filesmanager: shows directory size.
- Security Helper: update safeName() method.
- Pages Plugin: new method children() Get children pages for a specific parent page.
- Update translates.
- And a lot of general engine improvements.
Monstra 1.2.1, 2012-08-09
------------------------
- Admin styles: add .error class
- Fix translates
- Security: fix Cross Site Request Forgery
- Site Module: fix template() function
- Html Helper: fix nbsp() function
- Site Module: fix template() function
Monstra 1.2.0, 2012-07-03
------------------------
- Improve I18N
- Improve Monstra Check Version: set priority 9999
- XMLDB: fix updateWhere function
- Fix Agent Helper
- Sitemap: use time() instead of mktime()
- Security Helper: add Tokenizer
Monstra 1.1.6, 2012-06-12
------------------------
- Sitemap Plugin: return content instead of displaying.
- Improve content filtering.
Monstra 1.1.5, 2012-06-10
------------------------
- Improve Monstra Error Handler
- Cookie Helper: fix set() function
Monstra 1.1.4, 2012-06-09
------------------------
- Improve Monstra Error Handler
Monstra 1.1.3, 2012-06-06
------------------------
- Improve Monstra Error Handler
Monstra 1.1.2, 2012-06-05
------------------------
- Remove Fatal Error Handler
- File helper: fix writable() function
Monstra 1.1.1, 2012-06-04
------------------------
- Fix error reporting!
- Themes Plugin: fix Chunk class
Monstra 1.1.0, 2012-06-02
------------------------
- Menu plugin: added ability to add plugins(components) to site menu.
- Improve installation script: add ability to change Monstra language.
- Improve installation script: better error checking.
- Improve monstra check version
- Update Users table autoincrement value to 0
- Pages Plugin: return empty meta robots if current component is not pages
- Html Helper: fix arrow() function.
- XMLDB: fix select function.
- Themes Plugin: fix theme navigation item order. set 2
- Time Zones updates
- Fix translates
Monstra 1.0.1, 2012-04-26
------------------------
- Cleanup minify during saving the theme
- add new css variables: @site_url and @theme_url
- Remove deprecated @url css variable
Monstra 1.0.0, 2012-04-24
------------------------
- Initial release

BIN
favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 31 KiB

67
index.php Normal file
View File

@@ -0,0 +1,67 @@
<?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 engine defines
define('DS', DIRECTORY_SEPARATOR);
define('ROOT', rtrim(dirname(__FILE__), '\\/'));
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';
}
} 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')) {
// Mosntra 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();
}

444
install.php Normal file
View File

@@ -0,0 +1,444 @@
<?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 = 'Kwajalein';
// Include engine core
include 'monstra/bootstrap.php';
// Setting error display depending on debug mode or not
// Get php version id
if ( ! defined('PHP_VERSION_ID')){
$version = PHP_VERSION;
define('PHP_VERSION_ID', ($version{0} * 10000 + $version{2} * 100 + $version{4}));
}
// 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 = str_replace(array("index.php", "install.php"), "", $_SERVER['PHP_SELF']);
// Errors array
$errors = array();
// Directories to check
$dir_array = array('public', 'storage', 'backups', 'tmp');
// Select Monstra language
if (isset($_GET['language'])) {
if (in_array($_GET['language'], array('en', 'ru'))) {
if (Option::update('language', $_GET['language'])) {
Request::redirect($site_url);
}
} else {
Request::redirect($site_url);
}
}
// If pressed <Install> button then try to install
if (isset($_POST['install_submit'])) {
if (empty($_POST['sitename'])) $errors['sitename'] = __('Field "Site name" is empty', 'system');
if (empty($_POST['siteurl'])) $errors['siteurl'] = __('Field "Site url" is empty', 'system');
if (empty($_POST['login'])) $errors['login'] = __('Field "Username" is empty', 'system');
if (empty($_POST['password'])) $errors['password'] = __('Field "Password" is empty', 'system');
if (empty($_POST['email'])) $errors['email'] = __('Field "Email" is empty', 'system');
if ( ! Valid::email($_POST['email'])) $errors['email_valid'] = __('Email not valid', 'system');
if (trim($_POST['php']) !== '') $errors['php'] = true;
if (trim($_POST['simplexml']) !== '') $errors['simplexml'] = true;
if (trim($_POST['mod_rewrite']) !== '') $errors['mod_rewrite'] = true;
if (trim($_POST['htaccess']) !== '') $errors['htaccess'] = true;
if (trim($_POST['sitemap']) !== '') $errors['sitemap'] = true;
if (trim($_POST['install']) !== '') $errors['install'] = true;
if (trim($_POST['public']) !== '') $errors['public'] = true;
if (trim($_POST['storage']) !== '') $errors['storage'] = true;
if (trim($_POST['backups']) !== '') $errors['backups'] = true;
if (trim($_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_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'),
'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="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>
.install-languages {
margin: 0 auto;
float: none!important;
margin-bottom:5px;
padding-right:20px;
}
.install-block {
margin: 0 auto;
float: none!important;
}
.install-block-footer {
margin: 0 auto;
float: none!important;
margin-top:10px;
margin-bottom:10px;
}
.install-body {
background:#F2F2F2;
}
.error {
color:#8E0505;
}
.ok {
color:#00853F;
}
.warn {
color: #F74C18;
}
.sep {
color:#ccc;
}
.language-link {
color:#7A7A7C;
}
.language-link:hover {
color:#000;
}
.language-link-current {
color:#000;
}
</style>
</head>
<body class="install-body">
<!-- Block_wrapper -->
<?php
if (PHP_VERSION_ID < 50200) {
$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';
}
}
?>
<!-- Block_wrapper -->
<div class="row">
<div class="span4 install-languages">
<a class="language-link<?php if (Option::get('language') == 'en') echo ' language-link-current';?>" href="<?php echo $site_url.'?language=en'; ?>">en</a> <span class="sep">|</span>
<a class="language-link<?php if (Option::get('language') == 'ru') echo ' language-link-current';?>" href="<?php echo $site_url.'?language=ru'; ?>">ru</a>
</div>
</div>
<div class="row">
<div class="well span4 install-block">
<div style="text-align:center;"><a class="brand" href="#"><img src="<?php echo $site_url; ?>public/assets/img/monstra-logo-black.png"></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="span4" name="sitename" type="text" value="<?php if(isset($_POST['sitename'])) echo Html::toText($_POST['sitename']); ?>" />
<br />
<label><?php echo __('Site url', 'system'); ?></label>
<input class="span4" name="siteurl" type="text" value="<?php echo Html::toText($site_url); ?>" />
<br />
<label><?php echo __('Username', 'users'); ?></label>
<input class="span4" class="login" name="login" value="<?php if(isset($_POST['login'])) echo Html::toText($_POST['login']); ?>" type="text" />
<br />
<label><?php echo __('Password', 'users'); ?></label>
<input class="span4" name="password" type="password" />
<br />
<label><?php echo __('Time zone', 'system'); ?></label>
<select class="span4" 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="span4" value="<?php if(isset($_POST['email'])) echo Html::toText($_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 (PHP_VERSION_ID < 50200) {
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 not writable').'</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>
<div class="row">
<div class="span4 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 MONSTRA_VERSION; ?></span>
</div>
</div>
</div>
<!-- /Block_wrapper -->
</body>
</html>

220
license.txt Normal file
View File

@@ -0,0 +1,220 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
<EFBFBD>This License<73> refers to version 3 of the GNU General Public License.
<EFBFBD>Copyright<EFBFBD> also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
<EFBFBD>The Program<61> refers to any copyrightable work licensed under this License. Each licensee is addressed as <20>you<6F>. <20>Licensees<65> and <20>recipients<74> may be individuals or organizations.
To <20>modify<66> a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a <20>modified version<6F> of the earlier work or a work <20>based on<6F> the earlier work.
A <20>covered work<72> means either the unmodified Program or a work based on the Program.
To <20>propagate<74> a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To <20>convey<65> a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays <20>Appropriate Legal Notices<65> to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The <20>source code<64> for a work means the preferred form of the work for making modifications to it. <20>Object code<64> means any non-source form of a work.
A <20>Standard Interface<63> means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The <20>System Libraries<65> of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A <20>Major Component<6E>, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The <20>Corresponding Source<63> for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to <20>keep intact all notices<65>.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an <20>aggregate<74> if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A <20>User Product<63> is either (1) a <20>consumer product<63>, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, <20>normally used<65> refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
<EFBFBD>Installation Information<6F> for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
<EFBFBD>Additional permissions<6E> are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered <20>further restrictions<6E> within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An <20>entity transaction<6F> is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A <20>contributor<6F> is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's <20>contributor version<6F>.
A contributor's <20>essential patent claims<6D> are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, <20>control<6F> includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a <20>patent license<73> is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To <20>grant<6E> such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. <20>Knowingly relying<6E> means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is <20>discriminatory<72> if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License <20>or any later version<6F> applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM <20>AS IS<49> WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the <20>copyright<68> line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an <20>about box<6F>.
You should also get your employer (if you work as a programmer) or school, if any, to sign a <20>copyright disclaimer<65> for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

148
monstra/boot/defines.php Normal file
View File

@@ -0,0 +1,148 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Monstra CMS Defines
*/
/**
* Set gzip output
*/
define('MONSTRA_GZIP', false);
/**
* Set gzip styles
*/
define('MONSTRA_GZIP_STYLES', false);
/**
* Set Monstra version
*/
define('MONSTRA_VERSION', '1.3.1');
/**
* Set Monstra version id
*/
define('MONSTRA_VERSION_ID', 10301);
/**
* Set Monstra site url
*/
define('MONSTRA_SITEURL', 'http://monstra.org');
/**
* 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 login sleep value
*/
define('MONSTRA_LOGIN_SLEEP', 1);
/**
* 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);
/**
* Monstra CMS mobile detection
*/
define('MONSTRA_MOBILE', true);
/**
* Monstra database settings
*/
define('MONSTRA_DB_DSN', 'mysql:dbname=monstra;host=localhost;port=3306');
define('MONSTRA_DB_USER', 'root');
define('MONSTRA_DB_PASSWORD', 'password');

21
monstra/boot/filters.php Normal file
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);

7
monstra/boot/hooks.php Normal file
View File

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

81
monstra/bootstrap.php Normal file
View File

@@ -0,0 +1,81 @@
<?php defined('MONSTRA_ACCESS') or die('No direct script access.');
/**
* Include engine core
*/
include ROOT . DS . 'monstra' . DS . 'engine' . DS . 'core.php';
/**
* Set core environment
*
* Monstra has four predefined environments:
* Core::DEVELOPMENT - The development environment.
* Core::TESTING - The test environment.
* Core::STAGING - The staging environment.
* Core::PRODUCTION - The production environment.
*/
Core::$environment = Core::PRODUCTION;
/**
* Include defines
*/
include ROOT . DS . 'monstra' . DS . 'boot' . DS . 'defines.php';
/**
* Monstra requires PHP 5.2.0 or greater
*/
if (version_compare(PHP_VERSION, "5.2.0", "<")) {
exit("Monstra requires PHP 5.2.0 or greater.");
}
/**
* Report Errors
*/
if (Core::$environment == Core::PRODUCTION) {
error_reporting(0);
} else {
error_reporting(-1);
}
/**
* 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');
}
/**
* Initialize core
*/
Core::init();

390
monstra/engine/core.php Normal file
View File

@@ -0,0 +1,390 @@
<?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;
/**
* 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() {
// 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
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 filters
require_once(BOOT . DS . 'filters.php');
// Load default hooks
require_once(BOOT . DS . 'hooks.php');
// 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
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;
}
/**
* 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;
}
}

167
monstra/engine/options.php Normal file
View File

@@ -0,0 +1,167 @@
<?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.'"]');
}
}

1206
monstra/engine/plugins.php Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,133 @@
<?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 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;
}
/**
* 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];
}
}
}
return $prefix . call_user_func(Shortcode::$shortcode_tags[$shortcode], $attributes, $matches[5], $shortcode) . $suffix;
}
}

257
monstra/engine/site.php Normal file
View File

@@ -0,0 +1,257 @@
<?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() {
// Get title
$title = call_user_func(ucfirst(Uri::command()).'::title');
return $title;
}
/**
* Get page description
*
* <code>
* echo Site::description();
* </code>
*
* @return string
*/
public static function description() {
// Get description
$description = call_user_func(ucfirst(Uri::command()).'::description');
if (trim($description) !== '') {
return Html::toText($description);
} else {
return Html::toText(Option::get('description'));
}
}
/**
* Get page keywords
*
* <code>
* echo Site::keywords();
* </code>
*
* @return string
*/
public static function keywords() {
// Get keywords
$keywords = call_user_func(ucfirst(Uri::command()).'::keywords');
if (trim($keywords) !== '') {
return Html::toText($keywords);
} else {
return Html::toText(Option::get('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() {
// Get content
$content = call_user_func(ucfirst(Uri::command()).'::content');
return Filter::apply('content', $content);
}
/**
* Get compressed template
*
* <code>
* echo Site::template();
* </code>
*
* @return mixed
*/
public static function template() {
// Get current theme
$current_theme = Option::get('theme_site_name');
// 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="' . MONSTRA_SITEURL . '" target="_blank">Monstra</a> ' . MONSTRA_VERSION;
}
}
// Add new shortcode {siteurl}
Shortcode::add('siteurl', 'returnSiteUrl');
function returnSiteUrl() { return Option::get('siteurl'); }

1008
monstra/engine/xmldb.php Normal file

File diff suppressed because it is too large Load Diff

171
monstra/helpers/agent.php Normal file
View File

@@ -0,0 +1,171 @@
<?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);
}
}

97
monstra/helpers/alert.php Normal file
View File

@@ -0,0 +1,97 @@
<?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>';
}
}

193
monstra/helpers/arr.php Normal file
View File

@@ -0,0 +1,193 @@
<?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'));
}
}

225
monstra/helpers/cache.php Normal file
View File

@@ -0,0 +1,225 @@
<?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

@@ -0,0 +1,84 @@
<?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;
}
}

113
monstra/helpers/cookie.php Normal file
View File

@@ -0,0 +1,113 @@
<?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]);
}
}

153
monstra/helpers/curl.php Normal file
View File

@@ -0,0 +1,153 @@
<?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];
}
}

432
monstra/helpers/date.php Normal file
View File

@@ -0,0 +1,432 @@
<?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;
}
}

124
monstra/helpers/debug.php Normal file
View File

@@ -0,0 +1,124 @@
<?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;
}
}

215
monstra/helpers/dir.php Normal file
View File

@@ -0,0 +1,215 @@
<?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;
}
}

596
monstra/helpers/file.php Normal file
View File

@@ -0,0 +1,596 @@
<?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;
}
}

363
monstra/helpers/form.php Normal file
View File

@@ -0,0 +1,363 @@
<?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 {
/**
* Protected constructor since this is a static class.
*
* @access protected
*/
protected function __construct() {
// Nothing here
}
/**
* 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 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;
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;
$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>';
}
}

277
monstra/helpers/html.php Normal file
View File

@@ -0,0 +1,277 @@
<?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
}
/**
* 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;
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');
}
}

673
monstra/helpers/image.php Normal file
View File

@@ -0,0 +1,673 @@
<?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

@@ -0,0 +1,238 @@
<?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

@@ -0,0 +1,98 @@
<?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

@@ -0,0 +1,150 @@
<?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();
}
}

213
monstra/helpers/number.php Normal file
View File

@@ -0,0 +1,213 @@
<?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);
}
}

1141
monstra/helpers/orm.php Normal file

File diff suppressed because it is too large Load Diff

161
monstra/helpers/request.php Normal file
View File

@@ -0,0 +1,161 @@
<?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

@@ -0,0 +1,109 @@
<?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

@@ -0,0 +1,250 @@
<?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;
}
}

198
monstra/helpers/session.php Normal file
View File

@@ -0,0 +1,198 @@
<?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;
}
}

470
monstra/helpers/text.php Normal file
View File

@@ -0,0 +1,470 @@
<?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 string $str String with slashes
* @return string
*/
public static function strpSlashes($str) {
// Redefine vars
$str = (string) $str;
if (is_array($str)) {
foreach ($str as $key => $val) {
$str[$key] = stripslashes($val);
}
} else {
$str = stripslashes($str);
}
return $str;
}
/**
* 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;
}
}
/**
* 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');
}
}

171
monstra/helpers/uri.php Normal file
View File

@@ -0,0 +1,171 @@
<?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;
}
}

115
monstra/helpers/url.php Normal file
View File

@@ -0,0 +1,115 @@
<?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) {
$pos = strpos($url, 'http://');
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() {
return 'http://' . rtrim(rtrim($_SERVER['HTTP_HOST'], '\\/') . dirname($_SERVER['PHP_SELF']), '\\/');
}
}

208
monstra/helpers/valid.php Normal file
View File

@@ -0,0 +1,208 @@
<?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) preg_match('/^[-_a-z0-9\'+*$^&%=~!?{}]++(?:\.[-_a-z0-9\'+*$^&%=~!?{}]+)*+@(?:(?![-.])[-a-z0-9.]+(?<![-.])\.[a-z]{2,6}|\d{1,3}(?:\.\d{1,3}){3})(?::\d++)?$/iD', (string)$email);
}
/**
* Check an ip address for correct format.
*
* <code>
* if (Valid::ip('127.0.0.1')) {
* // Do something...
* }
* </code>
*
* @param string $ip ip address
* @return boolean
*/
public static function ip($ip) {
return (bool) preg_match("^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}^", (string)$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) preg_match("|^http(s)?://[a-z0-9-]+(.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i", (string)$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);
}
}

385
monstra/helpers/zip.php Normal file
View File

@@ -0,0 +1,385 @@
<?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;
}
}

1
plugins/.htaccess Normal file
View File

@@ -0,0 +1 @@
Deny from all

View File

@@ -0,0 +1,60 @@
<?php
class BackupAdmin extends Backend {
/**
* Backup admin
*/
public static function main() {
$backups_path = ROOT . DS . 'backups';
$backups_list = array();
// Create backup
// -------------------------------------
if (Request::post('create_backup')) {
@set_time_limit(0);
@ini_set("memory_limit", "512M");
$zip = Zip::factory();
// Add storage folder
$zip->readDir(STORAGE . DS, false);
// 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');
}
// Delete backup
// -------------------------------------
if (Request::get('sub_id') == 'backup') {
if (Request::get('delete_file')) {
File::delete($backups_path . DS . Request::get('delete_file'));
Request::redirect(Option::get('siteurl').'admin/index.php?id=backup');
}
}
// Download backup
// -------------------------------------
if (Request::get('download')) {
File::download('../backups/'.Request::get('download'));
}
// 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

@@ -0,0 +1,34 @@
<?php
/**
* 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');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin'))) {
Navigation::add(__('Backups', 'backup'), 'system', 'backup', 3);
// Include Backup Admin
Plugin::admin('backup', 'box');
}

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<plugin_location>plugins/box/backup/backup.plugin.php</plugin_location>
<plugin_status>active</plugin_status>
<plugin_priority>8</plugin_priority>
<plugin_name>Backup</plugin_name>
<plugin_description>Backup plugin</plugin_description>
<plugin_version>1.0.0</plugin_version>
<plugin_author>Awilum</plugin_author>
<plugin_author_uri>http://monstra.org/</plugin_author_uri>
</root>

View File

@@ -0,0 +1,17 @@
<?php
return array(
'backup' => array(
'Backups' => 'Backups',
'Backup date' => 'Backup date',
'Create backup' => 'Create backup',
'Delete' => 'Delete',
'storage' => 'storage',
'public' => 'public',
'plugins' => 'plugins',
'Size' => 'Size',
'Actions' => 'Actions',
'Delete backup: :backup' => 'Delete backup: :backup',
'Creating...' => 'Creating...',
)
);

View File

@@ -0,0 +1,17 @@
<?php
return array(
'backup' => array(
'Backups' => 'Бекапы',
'Backup date' => 'Бекап',
'Create backup' => 'Сделать бекап',
'Delete' => 'Удалить',
'storage' => 'данные',
'public' => 'публичная',
'plugins' => 'плагины',
'Size' => 'Размер',
'Actions' => 'Действия',
'Delete backup: :backup' => 'Удалить бекап: :backup',
'Creating...' => 'Создание...',
)
);

View File

@@ -0,0 +1,48 @@
<h2><?php echo __('Backups', 'backup'); ?></h2>
<br />
<?php if (Notification::get('success')) Alert::success(Notification::get('success')); ?>
<script>
$().ready(function(){$('[name=create_backup]').click(function(){$(this).button('loading');});});
</script>
<?php
echo (
Form::open() .
Form::checkbox('add_storage_folder', null, true, array('disabled' => 'disabled')) . ' ' . __('storage', 'backup') . ' ' . Html::nbsp(2) .
Form::checkbox('add_public_folder') . ' ' . __('public', 'backup') . ' ' . Html::nbsp(2) .
Form::checkbox('add_plugins_folder') . ' ' . __('plugins', 'backup') . ' ' . Html::nbsp(2) .
Form::submit('create_backup', __('Create backup', 'backup'), array('class' => 'btn default btn-small', 'data-loading-text' => __('Creating...', 'backup'))).
Form::close()
);
?>
<!-- Backup_list -->
<table class="table table-bordered">
<thead>
<tr>
<td><?php echo __('Backup date', 'backup'); ?></td>
<td><?php echo __('Size', 'backup'); ?></td>
<td width="30%"><?php echo __('Actions', 'backup'); ?></td>
</tr>
</thead>
<tbody>
<?php if (count($backups_list) > 0) rsort($backups_list); foreach ($backups_list as $backup) { ?>
<tr>
<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); ?>
</td>
<td><?php echo Number::byteFormat(filesize(ROOT . DS . 'backups' . DS . $backup)); ?></td>
<td>
<?php echo Html::anchor(__('Delete', 'backup'),
'index.php?id=system&sub_id=backup&delete_file='.$backup,
array('class' => 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete backup: :backup', 'backup', array(':backup' => Date::format($name, 'F jS, Y - g:i A')))."')"));
?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<!-- /Backup_list -->

View File

@@ -0,0 +1,139 @@
<?php
Navigation::add(__('Blocks', 'blocks'), 'content', 'blocks', 2);
class BlocksAdmin extends Backend {
/**
* Blocks admin function
*/
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')) {
// Switch actions
// -------------------------------------
switch (Request::get('action')) {
// Add block
// -------------------------------------
case "add_block":
if (Request::post('add_blocks') || Request::post('add_blocks_and_exit')) {
if (Security::check(Request::post('csrf'))) {
if (trim(Request::post('name')) == '') $errors['blocks_empty_name'] = __('This field should not be empty', '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) {
// 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')))));
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!'); }
}
// 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;
// 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 (trim(Request::post('name')) == '') $errors['blocks_empty_name'] = __('This field should not be empty', '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) {
$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;
}
} 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 { 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');
// 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":
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');
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

@@ -0,0 +1,73 @@
<?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 shortcode {block get="blockname"}
Shortcode::add('block', 'Block::_content');
class Block {
/**
* 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));
}
}
}
}

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<plugin_location>plugins/box/blocks/blocks.plugin.php</plugin_location>
<plugin_frontend>yes</plugin_frontend>
<plugin_backend>yes</plugin_backend>
<plugin_status>active</plugin_status>
<plugin_priority>6</plugin_priority>
<plugin_name>Blocks</plugin_name>
<plugin_description>Blocks manager plugin</plugin_description>
<plugin_version>1.0.0</plugin_version>
<plugin_author>Awilum</plugin_author>
<plugin_author_uri>http://monstra.org/</plugin_author_uri>
</root>

View File

@@ -0,0 +1,25 @@
<?php
return array(
'blocks' => array(
'Blocks' => 'Blocks',
'Blocks manager' => 'Blocks manager',
'Delete' => 'Delete',
'Edit' => 'Edit',
'Name' => 'Name',
'Create new block' => 'Create new block',
'New block' => 'New block',
'Edit block' => 'Edit block',
'Save' => 'Save',
'Save and exit' => 'Save and exit',
'Actions' => 'Actions',
'This field should not be empty' => 'This field should not be empty',
'This block already exists' => 'This block already exists',
'This block does not exist' => 'This block does not exist',
'Delete block: :block' => 'Delete block: :block',
'Block content' => 'Block content',
'Block <i>:name</i> deleted' => 'Block <i>:name</i> deleted',
'Your changes to the block <i>:name</i> have been saved.' => 'Your changes to the block <i>:name</i> have been saved.',
'Delete block: :block' => 'Delete block: :block',
)
);

View File

@@ -0,0 +1,25 @@
<?php
return array(
'blocks' => array(
'Blocks' => 'Блоки',
'Blocks manager' => 'Менеджер блоков',
'Delete' => 'Удалить',
'Edit' => 'Редактировать',
'New block' => 'Новый блок',
'Create new block' => 'Создать новый блок',
'Name' => 'Название',
'Edit block' => 'Редактирование блока',
'Save' => 'Сохранить',
'Actions' => 'Действия',
'Save and exit' => 'Сохранить и выйти',
'This field should not be empty' => 'Это поле не должно быть пустым',
'This block already exists' => 'Такой блок уже существует',
'This block does not exist' => 'Такого блока не существует',
'Delete block: :block' => 'Удалить блок: :block',
'Block content' => 'Содержимое блока',
'Block <i>:name</i> deleted' => 'Сниппет <i>:name</i> удален',
'Your changes to the block <i>:name</i> have been saved.' => 'Ваши изменения к блоку <i>:name</i> были сохранены.',
'Delete block: :block' => 'Удалить блок: :block',
)
);

View File

@@ -0,0 +1,36 @@
<h2><?php echo __('New block', 'blocks'); ?></h2>
<br />
<?php if (Notification::get('success')) Alert::success(Notification::get('success')); ?>
<?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' => 'span5'))); ?>
<?php
if (isset($errors['blocks_empty_name'])) echo '&nbsp;&nbsp;&nbsp;<span style="color:red">'.$errors['blocks_empty_name'].'</span>';
if (isset($errors['blocks_exists'])) echo '&nbsp;&nbsp;&nbsp;<span style="color:red">'.$errors['blocks_exists'].'</span>';
?>
<br /><br />
<?php
Action::run('admin_editor', array(Html::toText($content)));
echo (
Html::br().
Form::submit('add_blocks_and_exit', __('Save and exit', 'blocks'), array('class' => 'btn')).Html::nbsp(2).
Form::submit('add_blocks', __('Save', 'blocks'), array('class' => 'btn')).
Form::close()
);
?>

View File

@@ -0,0 +1,44 @@
<h2><?php echo __('Edit block', 'blocks'); ?></h2>
<br />
<?php if (Notification::get('success')) Alert::success(Notification::get('success')); ?>
<?php
if ($content !== null) {
if (isset($errors['blocks_empty_name']) or isset($errors['blocks_exists'])) $error_class = 'error'; else $error_class = '';
echo (Form::open());
echo (Form::hidden('csrf', Security::token()));
echo (Form::hidden('blocks_old_name', Request::get('filename')));
?>
<?php echo (Form::label('name', __('Name', 'blocks'))); ?>
<?php echo (Form::input('name', $name, array('class' => 'span5'))); ?>
<?php
if (isset($errors['blocks_empty_name'])) echo '&nbsp;&nbsp;&nbsp;<span style="color:red">'.$errors['blocks_empty_name'].'</span>';
if (isset($errors['blocks_exists'])) echo '&nbsp;&nbsp;&nbsp;<span style="color:red">'.$errors['blocks_exists'].'</span>';
?>
<br /><br />
<?php
Action::run('admin_editor', array(Html::toText($content)));
echo (
Html::br().
Form::submit('edit_blocks_and_exit', __('Save and exit', 'blocks'), array('class' => 'btn default')).Html::nbsp(2).
Form::submit('edit_blocks', __('Save', 'blocks'), array('class' => 'btn default')). Html::nbsp().
Form::close()
);
} else {
echo '<div class="message-error">'.__('This block does not exist', 'blocks').'</div>';
}
?>

View File

@@ -0,0 +1,34 @@
<h2><?php echo __('Blocks', 'blocks'); ?></h2>
<br />
<?php if(Notification::get('success')) Alert::success(Notification::get('success')); ?>
<?php
echo (
Html::anchor(__('Create new block', 'blocks'), 'index.php?id=blocks&action=add_block', array('title' => __('Create new block', 'blocks'), 'class' => 'btn default btn-small')). Html::nbsp(3)
);
?>
<br /><br />
<!-- Blocks_list -->
<table class="table table-bordered">
<thead>
<tr><td><?php echo __('Blocks', 'blocks'); ?></td><td width="30%"><?php echo __('Actions', 'blocks'); ?></td></tr>
</thead>
<tbody>
<?php if (count($blocks_list) != 0) foreach ($blocks_list as $block) { ?>
<tr>
<td><?php echo basename($block, '.block.html'); ?></td>
<td>
<?php echo Html::anchor(__('Edit', 'blocks'), 'index.php?id=blocks&action=edit_block&filename='.basename($block, '.block.html'), array('class' => 'btn btn-actions')); ?>
<?php echo Html::anchor(__('Delete', 'blocks'),
'index.php?id=blocks&action=delete_block&filename='.basename($block, '.block.html'),
array('class' => 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete block: :block', 'blocks', array(':block' => basename($block, '.block.html')))."')"));
?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<!-- /Blocks_list -->

View File

@@ -0,0 +1,43 @@
<?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 {
/**
* 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>');
}
}

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<plugin_location>plugins/box/editor/editor.plugin.php</plugin_location>
<plugin_status>active</plugin_status>
<plugin_priority>1</plugin_priority>
<plugin_name>Editor</plugin_name>
<plugin_description>Editor plugin</plugin_description>
<plugin_version>1.0.0</plugin_version>
<plugin_author>Awilum</plugin_author>
<plugin_author_uri>http://monstra.org/</plugin_author_uri>
</root>

View File

@@ -0,0 +1,8 @@
<?php
return array(
'Editor' => array(
'Editor' => 'Editor',
'Editor plugin' => 'Editor plugin',
)
);

View File

@@ -0,0 +1,8 @@
<?php
return array(
'Editor' => array(
'Editor' => 'Редактор',
'Editor plugin' => 'Редактор плагин',
)
);

View File

@@ -0,0 +1,146 @@
<?php
Navigation::add(__('Files', 'filesmanager'), 'content', 'filesmanager', 2);
class FilesmanagerAdmin extends Backend {
/**
* Main function
*/
public static function main() {
// Array of forbidden types
$forbidden_types = array('php', 'htaccess', 'html', 'htm', 'empty');
// 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') {
if (Request::get('delete_file')) {
File::delete($files_path.Request::get('delete_file'));
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
}
// Delete dir
// -------------------------------------
if (Request::get('id') == 'filesmanager') {
if (Request::get('delete_dir')) {
Dir::delete($files_path.Request::get('delete_dir'));
Request::redirect($site_url.'admin/index.php?id=filesmanager&path='.$path);
}
}
// Upload file
// -------------------------------------
if (Request::post('upload_file')) {
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);
}
}
}
// 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

@@ -0,0 +1,31 @@
<?php
/**
* 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');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) {
// Include Admin
Plugin::admin('filesmanager', 'box');
}

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<plugin_location>plugins/box/filesmanager/filesmanager.plugin.php</plugin_location>
<plugin_status>active</plugin_status>
<plugin_priority>2</plugin_priority>
<plugin_name>FilesManager</plugin_name>
<plugin_description>Simple file manger for Monstra</plugin_description>
<plugin_version>1.0.0</plugin_version>
<plugin_author>Awilum</plugin_author>
<plugin_author_uri>http://monstra.org/</plugin_author_uri>
</root>

View File

@@ -0,0 +1,17 @@
<?php
return array(
'filesmanager' => array(
'Files' => 'Files',
'Files manager' => 'Files manager',
'Name' => 'Name',
'Actions' => 'Actions',
'Delete' => 'Delete',
'Upload' => 'Upload',
'directory' => 'directory',
'Delete directory: :dir' => 'Delete directory: :dir',
'Delete file: :file' => 'Delete file :file',
'Extension' => 'Extension',
'Size' => 'Size',
)
);

View File

@@ -0,0 +1,17 @@
<?php
return array(
'filesmanager' => array(
'Files' => 'Файлы',
'Files manager' => 'Менеджер файлов',
'Name' => 'Название',
'Actions' => 'Действия',
'Delete' => 'Удалить',
'Upload' => 'Загрузить',
'directory' => 'директория',
'Delete directory: :dir' => 'Удалить директорию: :dir',
'Delete file: :file' => 'Удалить файл :file',
'Extension' => 'Расширение',
'Size' => 'Размер',
)
);

View File

@@ -0,0 +1,80 @@
<h2><?php echo __('Files', 'filesmanager'); ?></h2>
<br />
<!-- Filesmanager_upload_files -->
<?php
echo (
Form::open(null, array('enctype' => 'multipart/form-data')).
Form::input('file', null, array('type' => 'file', 'size' => '25')).Html::br().
Form::submit('upload_file', __('Upload', 'filesmanager'), array('class' => 'btn default btn-small')).
Form::close()
)
?>
<!-- /Filesmanager_upload_files -->
<!-- Filesmanger_path -->
<ul class="breadcrumb">
<?php
$path_parts = explode ('/',$path);
$s = '';
foreach ($path_parts as $p) {
$s .= $p.'/';
if($p == $current[count($current)-2]) $active = ' class="active"'; else $active = '';
echo '<span class="divider">/<span> <li'.$active.'><a href="index.php?id=filesmanager&path='.$s.'">'.$p.'</a></li>';
}
?>
</ul>
<!-- /Filesmanger_path -->
<table class="table table-bordered">
<thead>
<tr>
<td><?php echo __('Name', 'filesmanager'); ?></td>
<td><?php echo __('Extension', 'filesmanager'); ?></td>
<td><?php echo __('Size', 'filesmanager'); ?></td>
<td width="30%"><?php echo __('Actions', 'filesmanager'); ?></td>
</tr>
</thead>
<tbody>
<?php if (isset($dir_list)) foreach ($dir_list as $dir) { ?>
<tr>
<td>
<b><?php echo Html::anchor($dir, 'index.php?id=filesmanager&path='.$path.$dir.'/'); ?></b>
</td>
<td>
</td>
<td>
<?php echo Number::byteFormat(Dir::size(UPLOADS . DS . $dir)); ?>
</td>
<td>
<?php echo Html::anchor(__('Delete', 'filesmanager'),
'index.php?id=filesmanager&delete_dir='.$dir.'&path='.$path,
array('class' => 'btn', 'onclick' => "return confirmDelete('".__('Delete directory: :dir', 'filesmanager', array(':dir' => $dir))."')"));
?>
</td>
</tr>
<?php } ?>
<?php if (isset($files_list)) foreach ($files_list as $file) { $ext = File::ext($file); ?>
<?php if ( ! in_array($ext, $forbidden_types)) { ?>
<tr>
<td>
<?php echo Html::anchor(File::name($file), $site_url.'public' . DS .$path.$file, array('target'=>'_blank'));?>
</td>
<td>
<?php echo $ext; ?>
</td>
<td>
<?php echo Number::byteFormat(filesize($files_path. DS .$file)); ?>
</td>
<td>
<?php echo Html::anchor(__('Delete', 'filesmanager'),
'index.php?id=filesmanager&delete_file='.$file.'&path='.$path,
array('class' => 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete file: :file', 'filesmanager', array(':file' => $file))."')"));
?>
</td>
</tr>
<?php } } ?>
</tbody>
</table>

View File

@@ -0,0 +1,20 @@
<?php
Navigation::add(__('Information', 'information'), 'system', 'information', 5);
class InformationAdmin extends Backend {
/**
* Information main function
*/
public static function main() {
// Display view
View::factory('box/information/views/backend/index')->display();
}
}

View File

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

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<plugin_location>plugins/box/information/information.plugin.php</plugin_location>
<plugin_status>active</plugin_status>
<plugin_priority>7</plugin_priority>
<plugin_name>Information</plugin_name>
<plugin_description>Information plugin</plugin_description>
<plugin_version>1.0.0</plugin_version>
<plugin_author>Awilum</plugin_author>
<plugin_author_uri>http://awilum.webdevart.ru/</plugin_author_uri>
</root>

View File

@@ -0,0 +1,27 @@
<?php
return array(
'information' => array(
'Information' => 'Information',
'Debuging' => 'Debuging',
'Name' => 'Name',
'Value' => 'Value',
'Security' => 'Security',
'System' => 'System',
'on' => 'on',
'off'=> 'off',
'System version' => 'System version',
'System version ID' => 'System version ID',
'Security check results' => 'Security check results',
'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' =>
'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.',
'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod -R a-w :path</code>' =>
'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod -R a-w :path</code>',
'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod a-w :path</code>' =>
'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod a-w :path</code>',
'The Monstra index.php file has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod a-w :path</code>' =>
'The Monstra index.php file has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod a-w :path</code>',
'Due to the type and amount of information an error might give intruders when Core::$environment = Core::DEVELOPMENT, we strongly advise setting Core::PRODUCTION in production systems.',
'Due to the type and amount of information an error might give intruders when Core::$environment = Core::DEVELOPMENT, we strongly advise setting Core::PRODUCTION in production systems.',
)
);

View File

@@ -0,0 +1,27 @@
<?php
return array(
'information' => array(
'Information' => 'Информация',
'Debuging' => 'Дебагинг',
'Name' => 'Название',
'Value' => 'Значение',
'Security' => 'Безопасность',
'System' => 'Система',
'on' => 'включен',
'off'=> 'выключен',
'System version' => 'Версия системы',
'System version ID' => 'Версия системы ID',
'Security check results' => 'Результаты проверки безопасности',
'The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.' =>
'Конфигурационный файл доступен для записи. Мы рекомендуем вам удалить права записи на файл defines.php на живом сайте.',
'The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod -R a-w :path</code>' =>
'Директория Monstra (":path") доступна для записи. Мы рекомендуем вам удалить права записи на директорию (":path") на живом сайте. <br/> Вы можете сделать это на UNIX системах так: <code>chmod -R a-w :path</code>',
'The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod a-w :path</code>' =>
'Главный .htaccess доступен для записи. Мы рекомендуем вам удалить права записи на главный .htaccess файл. <br/> Вы можете сделать это на UNIX системах так: <code>chmod -R a-w :path</code>',
'The Monstra index.php file has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod a-w :path</code>' =>
'Главный index.php файл доступен для записи. Мы рекомендуем вам удалить права записи на главный index.php файл. <br/> Вы можете сделать это на UNIX системах так: <code>chmod -R a-w :path</code>',
'Due to the type and amount of information an error might give intruders when Core::$environment = Core::DEVELOPMENT, we strongly advise setting Core::PRODUCTION in production systems.' =>
'Система работает в режиме Core::DEVELOPMENT Мы рекомендуем вам установить режим Core::PRODUCTION на живом сайте.',
)
);

View File

@@ -0,0 +1,89 @@
<h2><?php echo __('Information', 'information'); ?></h2>
<br />
<div class="tabbable">
<ul class="nav nav-tabs">
<li class="active"><a href="#system" data-toggle="tab"><?php echo __('System', 'information'); ?></a></li>
<li><a href="#security" data-toggle="tab"><?php echo __('Security', 'information'); ?></a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="system">
<table class="table table-bordered">
<thead>
<tr>
<td><?php echo __('Name', 'information'); ?></td>
<td><?php echo __('Value', 'information'); ?></td>
</tr>
</thead>
<tbody>
<tr>
<td><?php echo __('System version', 'information'); ?></td>
<td><?php echo MONSTRA_VERSION; ?></td>
</tr>
<tr>
<td><?php echo __('System version ID', 'information'); ?></td>
<td><?php echo MONSTRA_VERSION_ID; ?></td>
</tr>
<tr>
<td><?php echo __('GZIP', 'information'); ?></td>
<td><?php if (MONSTRA_GZIP) { echo __('on', 'information'); } else { echo __('off', 'information'); } ?></td>
</tr>
<tr>
<td><?php echo __('Debuging', 'information'); ?></td>
<td><?php if (Core::$environment == Core::DEVELOPMENT) { echo __('on', 'information'); } else { echo __('off', 'information'); } ?></td>
</tr>
</tbody>
</table>
</div>
<div class="tab-pane" id="security">
<?php clearstatcache(); ?>
<table class="table table-bordered">
<thead>
<tr>
<td colspan="2"><?php echo __('Security check results', 'information'); ?></td>
</tr>
</thead>
<tbody>
<?php if (File::writable(BOOT . DS . 'defines.php')) { ?>
<tr>
<td><span class="badge badge-error" style="padding-left:5px; padding-right:5px;"><b>!</b></span> </td>
<td><?php echo __('The configuration file has been found to be writable. We would advise you to remove all write permissions on defines.php on production systems.', 'information'); ?></td>
</tr>
<?php } ?>
<?php if (File::writable(MONSTRA . DS)) { ?>
<tr>
<td><span class="badge badge-error" style="padding-left:5px; padding-right:5px;"><b>!</b></span> </td>
<td><?php echo __('The Monstra core directory (":path") and/or files underneath it has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod -R a-w :path</code>', 'information', array(':path' => MONSTRA . DS)); ?></td>
</tr>
<?php } ?>
<?php if (File::writable(ROOT . DS . '.htaccess')) { ?>
<tr>
<td><span class="badge badge-error" style="padding-left:5px; padding-right:5px;"><b>!</b></span> </td>
<td><?php echo __('The Monstra .htaccess file has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod a-w :path</code>', 'information', array(':path' => ROOT . DS . '.htaccess')); ?></td>
</tr>
<?php } ?>
<?php if (File::writable(ROOT . DS . 'index.php')) { ?>
<tr>
<td><span class="badge badge-error" style="padding-left:5px; padding-right:5px;"><b>!</b></span> </td>
<td><?php echo __('The Monstra index.php file has been found to be writable. We would advise you to remove all write permissions. <br/>You can do this on unix systems with: <code>chmod a-w :path</code>', 'information', array(':path' => ROOT . DS . 'index.php')); ?></td>
</tr>
<?php } ?>
<?php if (Core::$environment == Core::DEVELOPMENT) { ?>
<tr>
<td><span class="badge badge-warning" style="padding-left:5px; padding-right:5px;"><b>!</b></span> </td>
<td><?php echo __('Due to the type and amount of information an error might give intruders when Core::$environment = Core::DEVELOPMENT, we strongly advise setting Core::PRODUCTION in production systems.', 'information'); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
</div>

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<plugin_location>plugins/box/menu/menu.plugin.php</plugin_location>
<plugin_status>active</plugin_status>
<plugin_priority>4</plugin_priority>
<plugin_name>Menu</plugin_name>
<plugin_description>Menu managment plugin</plugin_description>
<plugin_version>1.0.0</plugin_version>
<plugin_author>Awilum</plugin_author>
<plugin_author_uri>http://monstra.org/</plugin_author_uri>
</root>

View File

@@ -0,0 +1,24 @@
<?php
return array(
'menu' => array(
'Menu' => 'Menu',
'Menu manager' => 'Menu manager',
'Edit' => 'Edit',
'Name' => 'Name',
'Delete' => 'Delete',
'Order' => 'Order',
'Actions' => 'Actions',
'Create new item' => 'Create new item',
'New item' => 'New item',
'Item name' => 'Item name',
'Item order' => 'Item order',
'Item target' => 'Item target',
'Item link' => 'Item link',
'Save' => 'Save',
'Edit item' => 'Edit item',
'Delete item :name' => 'Delete item :name',
'Add page' => 'Add page',
'Select page' => 'Select page',
)
);

View File

@@ -0,0 +1,24 @@
<?php
return array(
'menu' => array(
'Menu' => 'Меню',
'Menu manager' => 'Менеджер меню',
'Edit' => 'Редактировать',
'Name' => 'Название',
'Delete' => 'Удалить',
'Order' => 'Порядок',
'Actions' => 'Действия',
'Create new item' => 'Создать новый пункт меню',
'New item' => 'Новый пункт меню',
'Item name' => 'Название',
'Item order' => 'Порядок',
'Item target' => 'Цель',
'Item link' => 'Ссылка',
'Save' => 'Сохранить',
'Edit item' => 'Редактирование пункта меню',
'Delete item :name' => 'Удалить пункт меню :name',
'Add page' => 'Добавить страницу',
'Select page' => 'Выбрать страницу',
)
);

View File

@@ -0,0 +1,198 @@
<?php
// Add plugin navigation link
Navigation::add(__('Menu', 'menu'), 'content', 'menu', 3);
Action::add('admin_header', 'menuAdminHeaders');
function menuAdminHeaders() {
echo ("
<script>
function addMenuPage(slug, title) {
$('input[name=menu_item_link]').val(slug);
$('input[name=menu_item_name]').val(title);
$('#addMenuPageModal').modal('hide');
}
</script>
");
}
class MenuAdmin extends Backend {
public static function main() {
// Get menu table
$menu = new Table('menu');
// 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
// -----------------------------------------
switch (Request::get('action')) {
// Edit menu item
// -----------------------------------------
case "edit":
// Select item
$item = $menu->select('[id="'.Request::get('item_id').'"]', null);
$menu_item_name = $item['name'];
$menu_item_link = $item['link'];
$menu_item_target = $item['target'];
$menu_item_order = $item['order'];
$errors = array();
// Edit current 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 = $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_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'] = __('This field should not be empty', 'menu');
}
// Update menu item
if (count($errors) == 0) {
$menu->update(Request::get('item_id'), array('name' => Request::post('menu_item_name'),
'link' => Request::post('menu_item_link'),
'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/edit')
->assign('menu_item_name', $menu_item_name)
->assign('menu_item_link', $menu_item_link)
->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('pages_list', $pages->select('[slug!="error404" and parent=""]'))
->assign('components_list', MenuAdmin::getComponents())
->display();
break;
// Add menu item
// -----------------------------------------
case "add":
$menu_item_name = '';
$menu_item_link = '';
$menu_item_target = '';
$menu_item_order = '';
$errors = array();
// 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_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'] = __('This field should not be empty', 'menu');
}
// Insert new menu item
if (count($errors) == 0) {
$menu->insert(array('name' => Request::post('menu_item_name'),
'link' => Request::post('menu_item_link'),
'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_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('pages_list', $pages->select('[slug!="error404" and parent=""]'))
->assign('components_list', MenuAdmin::getComponents())
->display();
break;
}
} else {
// Delete menu item
if (Request::get('delete_item')) {
$menu->delete((int)Request::get('delete_item'));
}
// Select all items
$items = $menu->select(null, 'all', null, array('id', 'name', 'link', 'target', 'order'), 'order', 'ASC');
// Display view
View::factory('box/menu/views/backend/index')
->assign('items', $items)
->display();
}
}
/**
* Get components
*/
protected static function getComponents() {
$components = array();
if (count(Plugin::$components) > 0) {
foreach (Plugin::$components as $component) {
if ($component !== 'pages' && $component !== 'sitemap') $components[] = ucfirst($component);
}
}
return $components;
}
}

View File

@@ -0,0 +1,53 @@
<?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');
}
class Menu {
public static function get() {
// Get menu table
$menu = new Table('menu');
// Select all items
$items = $menu->select(null, 'all', null, array('id', 'name', 'link', 'target', 'order'), 'order', 'ASC');
// Display view
View::factory('box/menu/views/frontend/index')
->assign('items', $items)
->assign('uri', Uri::segments())
->assign('defpage', Option::get('defaultpage'))
->display();
}
}

View File

@@ -0,0 +1,62 @@
<h2><?php echo __('New item', 'menu'); ?></h2>
<br />
<?php echo (Form::open()); ?>
<?php echo (Form::hidden('csrf', Security::token())); ?>
<?php if (isset($errors['menu_item_name_empty'])) $error_class = ' error'; else $error_class = ''; ?>
<a href="javascript:;" style="text-decoration:none; color:#333; border-bottom:1px dashed #333;" data-toggle="modal" onclick="$('#addMenuPageModal').modal('show').width(270);" ><?php echo __('Add page', 'menu'); ?></a><br /><br />
<?php
echo Form::label('menu_item_name', __('Item name', 'menu'));
echo Form::input('menu_item_name', $menu_item_name, array('class' => 'span6'.$error_class));
if (isset($errors['menu_item_name_empty'])) echo Html::nbsp(4).'<span class="error">'.$errors['menu_item_name_empty'].'</span>';
echo (
Form::label('menu_item_link', __('Item link', 'menu')).
Form::input('menu_item_link', $menu_item_link, array('class' => 'span6'))
);
?>
<?php
echo (
Html::br().
Form::label('menu_item_target', __('Item target', 'menu')).
Form::select('menu_item_target', $menu_item_target_array, $menu_item_target)
);
echo (
Html::br().
Form::label('menu_item_order', __('Item order', 'menu')).
Form::select('menu_item_order', $menu_item_order_array, $menu_item_order)
);
echo (
Html::br(2).
Form::submit('menu_add_item', __('Save', 'menu'), array('class' => 'btn')).
Form::close()
);
?>
<div class="modal hide" id="addMenuPageModal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3><?php echo __('Select page', 'menu'); ?></h3>
</div>
<div class="modal-body">
<p>
<ul class="unstyled">
<?php if (count($pages_list) > 0) foreach($pages_list as $page) { ?>
<li><a href="javascript:;" onclick="addMenuPage('<?php echo $page['slug']; ?>', '<?php echo $page['title']; ?>');"><?php echo $page['title']; ?></a></li>
<?php } ?>
<?php if (count($components_list) > 0) foreach($components_list as $component) { ?>
<li><a href="javascript:;" onclick="addMenuPage('<?php echo Text::lowercase($component); ?>', '<?php echo __($component); ?>');"><?php echo __($component); ?></a></li>
<?php } ?>
</ul>
</p>
</div>
</div>

View File

@@ -0,0 +1,62 @@
<h2><?php echo __('Edit item', 'menu'); ?></h2>
<br />
<?php echo (Form::open()); ?>
<?php echo (Form::hidden('csrf', Security::token())); ?>
<?php if (isset($errors['menu_item_name_empty'])) $error_class = ' error'; else $error_class = ''; ?>
<a href="javascript:;" style="text-decoration:none; color:#333; border-bottom:1px dashed #333;" data-toggle="modal" onclick="$('#addMenuPageModal').modal('show').width(270);" ><?php echo __('Add page', 'menu'); ?></a><br /><br />
<?php
echo Form::label('menu_item_name', __('Item name', 'menu'));
echo Form::input('menu_item_name', $menu_item_name, array('class' => 'span6'.$error_class));
if (isset($errors['menu_item_name_empty'])) echo Html::nbsp(4).'<span class="error">'.$errors['menu_item_name_empty'].'</span>';
echo (
Form::label('menu_item_link', __('Item link', 'menu')).
Form::input('menu_item_link', $menu_item_link, array('class' => 'span6'))
);
?>
<?php
echo (
Html::br().
Form::label('menu_item_target', __('Item target', 'menu')).
Form::select('menu_item_target', $menu_item_target_array, $menu_item_target)
);
echo (
Html::br().
Form::label('menu_item_order', __('Item order', 'menu')).
Form::select('menu_item_order', $menu_item_order_array, $menu_item_order)
);
echo (
Html::br(2).
Form::submit('menu_add_item', __('Save', 'menu'), array('class' => 'btn')).
Form::close()
);
?>
<div class="modal hide" id="addMenuPageModal">
<div class="modal-header">
<a class="close" data-dismiss="modal">×</a>
<h3><?php echo __('Select page', 'menu'); ?></h3>
</div>
<div class="modal-body">
<p>
<ul class="unstyled">
<?php if (count($pages_list) > 0) foreach($pages_list as $page) { ?>
<li><a href="javascript:;" onclick="addMenuPage('<?php echo $page['slug']; ?>', '<?php echo $page['title']; ?>');"><?php echo $page['title']; ?></a></li>
<?php } ?>
<?php if (count($components_list) > 0) foreach($components_list as $component) { ?>
<li><a href="javascript:;" onclick="addMenuPage('<?php echo Text::lowercase($component); ?>', '<?php echo __($component); ?>');"><?php echo __($component); ?></a></li>
<?php } ?>
</ul>
</p>
</div>
</div>

View File

@@ -0,0 +1,51 @@
<h2><?php echo __('Menu', 'menu'); ?></h2>
<br />
<?php
echo (
Html::anchor(__('Create new item', 'menu'), 'index.php?id=menu&action=add', array('title' => __('Create new page', 'menu'), 'class' => 'btn btn-small'))
);
?>
<br /><br />
<table class="table table-bordered">
<thead>
<tr>
<td><?php echo __('Name', 'menu'); ?></td>
<td class="span2"><?php echo __('Order', 'menu'); ?></td>
<td width="30%"><?php echo __('Actions', 'menu'); ?></td>
</tr>
</thead>
<tbody>
<?php foreach ($items as $item) { ?>
<?php
$item['link'] = Html::toText($item['link']);
$item['name'] = Html::toText($item['name']);
$pos = strpos($item['link'], 'http://');
if ($pos === false) {
$link = Option::get('siteurl').$item['link'];
} else {
$link = $item['link'];
}
?>
<tr>
<td>
<a target="_blank" href="<?php echo $link; ?>"><?php echo $item['name']; ?></a>
</td>
<td>
<?php echo $item['order']; ?>
</td>
<td>
<?php echo Html::anchor(__('Edit', 'menu'), 'index.php?id=menu&action=edit&item_id='.$item['id'], array('class' => 'btn btn-actions')); ?>
<?php echo Html::anchor(__('Delete', 'menu'),
'index.php?id=menu&delete_item='.$item['id'],
array('class' => 'btn btn-actions', 'onclick' => "return confirmDelete('".__('Delete item :name', 'menu', array(':name' => $item['name']))."')"));
?>
</td>
</tr>
<?php } ?>
</tbody>
</table>

View File

@@ -0,0 +1,52 @@
<?php
$anchor_active = '';
$li_active = '';
$target = '';
if (count($items) > 0) {
foreach ($items as $item) {
$item['link'] = Html::toText($item['link']);
$item['name'] = Html::toText($item['name']);
$pos = strpos($item['link'], 'http://');
if ($pos === false) {
$link = Option::get('siteurl').$item['link'];
} else {
$link = $item['link'];
}
if (isset($uri[1])) {
$child_link = explode("/",$item['link']);
if (isset($child_link[1])) {
if (in_array($child_link[1], $uri)) {
$anchor_active = ' class="current" ';
$li_active = ' class="active"';
}
}
}
if (isset($uri[0]) && $uri[0] !== '') {
if (in_array($item['link'], $uri)) {
$anchor_active = ' class="current" ';
$li_active = ' class="active"';
}
} else {
if ($defpage == trim($item['link'])) {
$anchor_active = ' class="current" ';
$li_active = ' class="active"';
}
}
if (trim($item['target']) !== '') {
$target = ' target="'.$item['target'].'" ';
}
echo '<li'.$li_active.'>'.'<a href="'.$link.'"'.$anchor_active.$target.'>'.$item['name'].'</a>'.'</li>';
$anchor_active = '';
$li_active = '';
$target = '';
}
}

View File

@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<root>
<plugin_location>plugins/box/pages/pages.plugin.php</plugin_location>
<plugin_status>active</plugin_status>
<plugin_priority>1</plugin_priority>
<plugin_name>Pages</plugin_name>
<plugin_description>Pages managment plugin</plugin_description>
<plugin_version>1.0.0</plugin_version>
<plugin_author>Awilum</plugin_author>
<plugin_author_uri>http://monstra.org/</plugin_author_uri>
</root>

View File

@@ -0,0 +1,47 @@
<?php
return array(
'pages' => array(
'Pages' => 'Pages',
'Pages manager' => 'Pages manager',
'Content' => 'Content',
'Create new page' => 'Create new page',
'New page' => 'New page',
'Edit page' => 'Edit page',
'Date' => 'Date',
'Clone' => 'Clone',
'Edit' => 'Edit',
'Delete' => 'Delete',
'Delete page: :page' => 'Delete page: :page',
'Title' => 'Title',
'Name' => 'Name',
'Author' => 'Author',
'Name (slug)' => 'Name (slug)',
'Description' => 'Description',
'Keywords' => 'Keywords',
'Parent' => 'Parent',
'Template' => 'Template',
'Year' => 'Year',
'Day' => 'day',
'Month' => 'Month',
'Hour' => 'Hour',
'Minute' => 'Minute',
'Second' => 'Second',
'This field should not be empty' => 'This field should not be empty',
'This page already exists' => 'This page already exists',
'Extra' => 'Extra',
'Save' => 'Save',
'Save and exit' => 'Save and exit',
'Your changes to the page <i>:page</i> have been saved.' => 'Your changes to the page <i> :page </i> have been saved.',
'The page <i>:page</i> cloned.' => 'The page <i>:page</i> cloned.',
'Status' => 'Status',
'Actions' => 'Actions',
'Add' => 'Add',
'Published' => 'Published',
'Draft' => 'Draft',
'Published on' => 'Published on',
'Edit 404 page' => 'Edit 404 page',
'Page <i>:page</i> deleted' => 'Page <i>:page</i> deleted',
'Search Engines Robots' => 'Search Engines Robots',
)
);

View File

@@ -0,0 +1,47 @@
<?php
return array(
'pages' => array(
'Pages' => 'Страницы',
'Pages manager' => 'Менеджер страниц',
'Content' => 'Контент',
'Create new page' => 'Создать новую страницу',
'New page' => 'Новая страница',
'Edit page' => 'Редактирование страницы',
'Date' => 'Дата',
'Clone' => 'Клонировать',
'Edit' => 'Редактировать',
'Delete' => 'Удалить',
'Delete page: :page' => 'Удалить страницу: :page',
'Title' => 'Заголовок',
'Name' => 'Название',
'Author' => 'Автор',
'Name (slug)' => 'Название (slug)',
'Description' => 'Описание',
'Keywords' => 'Ключевые слова',
'Parent' => 'Родитель',
'Template' => 'Шаблон',
'Year' => 'Год',
'Day' => 'День',
'Month' => 'Месяц',
'Hours' => 'Час',
'Minute' => 'Минута',
'Second' => 'Секунда',
'This field should not be empty' => 'Это поле не должно быть пустым',
'This page already exists' => 'Такая страница уже существует',
'Extra' => 'Дополнительно',
'Save' => 'Сохранить',
'Save and exit' => 'Сохранить и выйти',
'Your changes to the page <i>:page</i> have been saved.' => 'Ваши изменения к странице <i>:page</i> были сохранены.',
'The page <i>:page</i> cloned.' => 'Страница <i>:page</i> клонирована.',
'Status' => 'Статус',
'Actions' => 'Действия',
'Add' => 'Добавить',
'Published' => 'Опубликовано',
'Draft' => 'Черновик',
'Published on' => 'Опубликовано',
'Edit 404 page' => 'Редактировать страницу 404',
'Page <i>:page</i> deleted' => 'Страница <i>:page</i> удалена',
'Search Engines Robots' => 'Поисковые роботы',
),
);

View File

@@ -0,0 +1,499 @@
<?php
Navigation::add(__('Pages', 'pages'), 'content', 'pages', 1);
class PagesAdmin extends Backend {
/**
* Pages admin function
*/
public static function main() {
$current_theme = Option::get('theme_site_name');
$site_url = Option::get('siteurl');
$templates_path = THEMES_SITE;
$errors = array();
$pages = new Table('pages');
$users = new Table('users');
$user = $users->select('[id='.Session::get('user_id').']', null);
$user['firstname'] = Html::toText($user['firstname']);
$user['lastname'] = Html::toText($user['lastname']);
// Page author
if (isset($user['firstname']) && trim($user['firstname']) !== '') {
if (trim($user['lastname']) !== '') $lastname = ' '.$user['lastname']; else $lastname = '';
$author = $user['firstname'] . $lastname;
} else {
$author = Session::get('user_login');
}
// Status array
$status_array = array('published' => __('Published', 'pages'),
'draft' => __('Draft', 'pages'));
// Check for get actions
// ---------------------------------------------
if (Request::get('action')) {
// Switch actions
// -----------------------------------------
switch (Request::get('action')) {
// Clone page
// -------------------------------------
case "clone_page":
// Generate rand page name
$rand_page_name = Request::get('name').'_clone_'.date("Ymd_His");
// Get original page
$orig_page = $pages->select('[slug="'.Request::get('name').'"]', null);
// Clone page
if($pages->insert(array('slug' => $rand_page_name,
'template' => $orig_page['template'],
'parent' => $orig_page['parent'],
'robots_index' => $orig_page['robots_index'],
'robots_follow'=> $orig_page['robots_follow'],
'status' => $orig_page['status'],
'title' => $rand_page_name,
'description' => $orig_page['description'],
'keywords' => $orig_page['keywords'],
'date' => $orig_page['date'],
'author' => $orig_page['author']))) {
// Get cloned page ID
$last_id = $pages->lastId();
// Save cloned page content
File::setContent(STORAGE . DS . 'pages' . DS . $last_id . '.page.txt',
File::getContent(STORAGE . DS . 'pages' . DS . $orig_page['id'] . '.page.txt'));
// Send notification
Notification::set('success', __('The page <i>:page</i> cloned.', 'pages', array(':page' => Security::safeName(Request::get('name'), '-', true))));
}
// Run add extra actions
Action::run('admin_pages_action_clone');
// Redirect
Request::redirect('index.php?id=pages');
break;
// Add page
// -------------------------------------
case "add_page":
// Add page
if (Request::post('add_page') || Request::post('add_page_and_exit')) {
if (Security::check(Request::post('csrf'))) {
// Get pages parent
if (Request::post('pages') == '0') {
$parent_page = '';
} else {
$parent_page = Request::post('pages');
}
// Validate
//--------------
if (trim(Request::post('page_name')) == '') $errors['pages_empty_name'] = __('This field should not be empty', 'pages');
$page = $pages->select('[slug="'.Security::safeName(Request::post('page_name'), '-', true).'"]');
if (count($page) != 0) $errors['pages_exists'] = __('This page already exists', 'pages');
if (trim(Request::post('page_title')) == '') $errors['pages_empty_title'] = __('This field should not be empty', 'pages');
// Generate date
$date = mktime(Request::post('hour'),
Request::post('minute'),
Request::post('second'),
Request::post('month'),
Request::post('day'),
Request::post('year'));
if (Request::post('robots_index')) $robots_index = 'noindex'; else $robots_index = 'index';
if (Request::post('robots_follow')) $robots_follow = 'nofollow'; else $robots_follow = 'follow';
// If no errors then try to save
if (count($errors) == 0) {
// Insert new page
if($pages->insert(array('slug' => Security::safeName(Request::post('page_name'), '-', true),
'template' => Request::post('templates'),
'parent' => $parent_page,
'status' => Request::post('status'),
'robots_index' => $robots_index,
'robots_follow'=> $robots_follow,
'title' => Request::post('page_title'),
'description' => Request::post('page_description'),
'keywords' => Request::post('page_keywords'),
'date' => $date,
'author' => $author))) {
// Get inserted page ID
$last_id = $pages->lastId();
// Save content
File::setContent(STORAGE . DS . 'pages' . DS . $last_id . '.page.txt', XML::safe(Request::post('editor')));
// Send notification
Notification::set('success', __('Your changes to the page <i>:page</i> have been saved.', 'pages', array(':page' => Security::safeName(Request::post('page_title'), '-', true))));
}
// Run add extra actions
Action::run('admin_pages_action_add');
// Redirect
if (Request::post('add_page_and_exit')) {
Request::redirect('index.php?id=pages');
} else {
Request::redirect('index.php?id=pages&action=edit_page&name='.Security::safeName(Request::post('page_name'), '-', true));
}
}
} else { die('csrf detected!'); }
}
// Get all pages
$pages_list = $pages->select('[slug!="error404" and parent=""]');
$pages_array[] = '-none-';
foreach ($pages_list as $page) {
$pages_array[$page['slug']] = $page['title'];
}
// Get all templates
$templates_list = File::scan($templates_path, '.template.php');
foreach ($templates_list as $file) {
$templates_array[basename($file, '.template.php')] = basename($file, '.template.php');
}
// Save fields
if (Request::post('pages')) $parent_page = Request::post('pages'); else $parent_page = '';
if (Request::post('page_name')) $post_name = Request::post('page_name'); else $post_name = '';
if (Request::post('page_title')) $post_title = Request::post('page_title'); else $post_title = '';
if (Request::post('page_keywords')) $post_keywords = Request::post('page_keywords'); else $post_keywords = '';
if (Request::post('page_description')) $post_description = Request::post('page_description'); else $post_description = '';
if (Request::post('editor')) $post_content = Request::post('editor'); else $post_content = '';
if (Request::post('templates')) $post_template = Request::post('templates'); else $post_template = 'index';
if (Request::post('robots_index')) $post_robots_index = true; else $post_robots_index = false;
if (Request::post('robots_follow')) $post_robots_follow = true; else $post_robots_follow = false;
if (Request::post('parent_page')) {
$post_template = Request::post('pages');
} else {
if(Request::get('parent_page')) {
$parent_page = trim(Request::get('parent_page'));
}
}
//--------------
// Generate date
$date = explode('-', Date::format(time(), 'Y-m-d-H-i-s'));
// Display view
View::factory('box/pages/views/backend/add')
->assign('post_name', $post_name)
->assign('post_title', $post_title)
->assign('post_description', $post_description)
->assign('post_keywords', $post_keywords)
->assign('post_content', $post_content)
->assign('pages_array', $pages_array)
->assign('parent_page', $parent_page)
->assign('templates_array', $templates_array)
->assign('post_template', $post_template)
->assign('status_array', $status_array)
->assign('date', $date)
->assign('post_robots_index', $post_robots_index)
->assign('post_robots_follow', $post_robots_follow)
->assign('errors', $errors)
->display();
break;
// Edit page
// -------------------------------------
case "edit_page":
if (Request::post('edit_page') || Request::post('edit_page_and_exit')) {
if (Security::check(Request::post('csrf'))) {
// Get pages parent
if (Request::post('pages') == '0') {
$parent_page = '';
} else {
$parent_page = Request::post('pages');
}
// Save field
$post_parent = Request::post('pages');
// Validate
//--------------
if (trim(Request::post('page_name')) == '') $errors['pages_empty_name'] = __('This field should not be empty', 'pages');
$_page = $pages->select('[slug="'.Security::safeName(Request::post('page_name'), '-', true).'"]');
if ((count($_page) != 0) and (Security::safeName(Request::post('page_old_name'), '-', true) !== Security::safeName(Request::post('page_name'), '-', true))) $errors['pages_exists'] = __('This page already exists', 'pages');
if (trim(Request::post('page_title')) == '') $errors['pages_empty_title'] = __('This field should not be empty', 'pages');
// Save fields
if (Request::post('page_name')) $post_name = Request::post('page_name'); else $post_name = '';
if (Request::post('page_title')) $post_title = Request::post('page_title'); else $post_title = '';
if (Request::post('page_keywords')) $post_keywords = Request::post('page_keywords'); else $post_keywords = '';
if (Request::post('page_description')) $post_description = Request::post('page_description'); else $post_description = '';
if (Request::post('editor')) $post_content = Request::post('editor'); else $post_content = '';
if (Request::post('templates')) $post_template = Request::post('templates'); else $post_template = 'index';
if (Request::post('robots_index')) $post_robots_index = true; else $post_robots_index = false;
if (Request::post('robots_follow')) $post_robots_follow = true; else $post_robots_follow = false;
//--------------
// Generate date
$date = mktime(Request::post('hour'),
Request::post('minute'),
Request::post('second'),
Request::post('month'),
Request::post('day'),
Request::post('year'));
if (Request::post('robots_index')) $robots_index = 'noindex'; else $robots_index = 'index';
if (Request::post('robots_follow')) $robots_follow = 'nofollow'; else $robots_follow = 'follow';
if (count($errors) == 0) {
// Update parents in all childrens
if ((Security::safeName(Request::post('page_name'), '-', true)) !== (Security::safeName(Request::post('page_old_name'), '-', true)) and (Request::post('old_parent') == '')) {
$pages->updateWhere('[parent="'.Request::get('name').'"]', array('parent' => Text::translitIt(trim(Request::post('page_name')))));
if ($pages->updateWhere('[slug="'.Request::get('name').'"]',
array('slug' => Security::safeName(Request::post('page_name'), '-', true),
'template' => Request::post('templates'),
'parent' => $parent_page,
'title' => Request::post('page_title'),
'description' => Request::post('page_description'),
'keywords' => Request::post('page_keywords'),
'robots_index' => $robots_index,
'robots_follow'=> $robots_follow,
'status' => Request::post('status'),
'date' => $date,
'author' => $author))) {
File::setContent(STORAGE . DS . 'pages' . DS . Request::post('page_id') . '.page.txt', XML::safe(Request::post('editor')));
Notification::set('success', __('Your changes to the page <i>:page</i> have been saved.', 'pages', array(':page' => Security::safeName(Request::post('page_title'), '-', true))));
}
// Run edit extra actions
Action::run('admin_pages_action_edit');
} else {
if ($pages->updateWhere('[slug="'.Request::get('name').'"]',
array('slug' => Security::safeName(Request::post('page_name'), '-', true),
'template' => Request::post('templates'),
'parent' => $parent_page,
'title' => Request::post('page_title'),
'description' => Request::post('page_description'),
'keywords' => Request::post('page_keywords'),
'robots_index' => $robots_index,
'robots_follow'=> $robots_follow,
'status' => Request::post('status'),
'date' => $date,
'author' => $author))) {
File::setContent(STORAGE . DS . 'pages' . DS . Request::post('page_id') . '.page.txt', XML::safe(Request::post('editor')));
Notification::set('success', __('Your changes to the page <i>:page</i> have been saved.', 'pages', array(':page' => Security::safeName(Request::post('page_title'), '-', true))));
}
// Run edit extra actions
Action::run('admin_pages_action_edit');
}
// Redirect
if (Request::post('edit_page_and_exit')) {
Request::redirect('index.php?id=pages');
} else {
Request::redirect('index.php?id=pages&action=edit_page&name='.Security::safeName(Request::post('page_name'), '-', true));
}
}
} else { die('csrf detected!'); }
}
// Get all pages
$pages_list = $pages->select();
$pages_array[] = '-none-';
// Foreach pages find page whithout parent
foreach ($pages_list as $page) {
if (isset($page['parent'])) {
$c_p = $page['parent'];
} else {
$c_p = '';
}
if ($c_p == '') {
// error404 is system "constant" and no child for it
if ($page['slug'] !== 'error404' && $page['slug'] !== Request::get('name')) {
$pages_array[$page['slug']] = $page['title'];
}
}
}
// Get all templates
$templates_list = File::scan($templates_path,'.template.php');
foreach ($templates_list as $file) {
$templates_array[basename($file,'.template.php')] = basename($file, '.template.php');
}
$page = $pages->select('[slug="'.Request::get('name').'"]', null);
if ($page) {
$page_content = File::getContent(STORAGE . DS . 'pages' . DS . $page['id'] . '.page.txt');
// Safe fields or load fields
if (Request::post('page_name')) $slug_to_edit = Request::post('page_name'); else $slug_to_edit = $page['slug'];
if (Request::post('page_title')) $title_to_edit = Request::post('page_title'); else $title_to_edit = $page['title'];
if (Request::post('page_description')) $description_to_edit = Request::post('page_description'); else $description_to_edit = $page['description'];
if (Request::post('page_keywords')) $keywords_to_edit = Request::post('page_keywords'); else $keywords_to_edit = $page['keywords'];
if (Request::post('editor')) $to_edit = Request::post('editor'); else $to_edit = Text::toHtml($page_content);
if (Request::post('robots_index')) $post_robots_index = true; else if ($page['robots_index'] == 'noindex') $post_robots_index = true; else $post_robots_index = false;
if (Request::post('robots_follow')) $post_robots_follow = true; else if ($page['robots_follow'] == 'nofollow') $post_robots_follow = true; else $post_robots_follow = false;
if (Request::post('pages')) {
// Get pages parent
if (post('pages') == '-none-') {
$parent_page = '';
} else {
$parent_page = Request::post('pages');
}
// Save field
$parent_page = Request::post('pages');
} else {
$parent_page = $page['parent'];
}
if (Request::post('templates')) $template = Request::post('templates'); else $template = $page['template'];
if (Request::post('status')) $status = Request::post('status'); else $status = $page['status'];
$date = explode('-', Date::format($page['date'],'Y-m-d-H-i-s'));
// Display view
View::factory('box/pages/views/backend/edit')
->assign('slug_to_edit', $slug_to_edit)
->assign('title_to_edit', $title_to_edit)
->assign('description_to_edit', $description_to_edit)
->assign('keywords_to_edit', $keywords_to_edit)
->assign('page', $page)
->assign('to_edit', $to_edit)
->assign('pages_array', $pages_array)
->assign('parent_page', $parent_page)
->assign('templates_array', $templates_array)
->assign('template', $template)
->assign('status_array', $status_array)
->assign('status', $status)
->assign('date', $date)
->assign('post_robots_index', $post_robots_index)
->assign('post_robots_follow', $post_robots_follow)
->assign('errors', $errors)
->display();
}
break;
// Delete page
// -------------------------------------
case "delete_page":
// Error 404 page can not be removed
if (Request::get('name') !== 'error404') {
// Get page title, delete page and update <parent> fields
$page = $pages->select('[slug="'.Request::get('name').'"]', null);
if ($pages->deleteWhere('[slug="'.Request::get('name').'" ]')) {
$pages->updateWhere('[parent="'.Request::get('name').'"]', array('parent' => ''));
File::delete(STORAGE . DS . 'pages' . DS . $page['id'] . '.page.txt');
Notification::set('success', __('Page <i>:page</i> deleted', 'pages', array(':page' => Html::toText($page['title']))));
}
// Run delete extra actions
Action::run('admin_pages_action_delete');
// Redirect
Request::redirect('index.php?id=pages');
}
break;
}
// Its mean that you can add your own actions for this plugin
Action::run('admin_pages_extra_actions');
} else { // Load main template
$pages_list = $pages->select(null, 'all', null, array('slug', 'title', 'status', 'date', 'author', 'parent'));
$pages_array = array();
$count = 0;
foreach ($pages_list as $page) {
$pages_array[$count]['title'] = $page['title'];
$pages_array[$count]['parent'] = $page['parent'];
$pages_array[$count]['status'] = $status_array[$page['status']];
$pages_array[$count]['date'] = $page['date'];
$pages_array[$count]['author'] = $page['author'];
$pages_array[$count]['slug'] = $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 = Arr::subvalSort($pages_array, 'sort');
// Display view
View::factory('box/pages/views/backend/index')
->assign('pages', $pages)
->assign('site_url', $site_url)
->display();
}
}
}

View File

@@ -0,0 +1,392 @@
<?php
/**
* Pages plugin
*
* @package Monstra
* @subpackage Plugins
* @author Romanenko Sergey / Awilum
* @copyright 2012 Romanenko Sergey / Awilum
* @version 1.0.0
*
*/
// Register plugin
Plugin::register( __FILE__,
__('Pages' , 'pages'),
__('Pages manager', 'pages'),
'1.0.0',
'Awilum',
'http://monstra.org/',
'pages',
'box');
if (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor'))) {
// Include Admin
Plugin::Admin('pages', 'box');
}
class Pages extends Frontend {
/**
* Current page data
*
* @var object
*/
public static $page = null;
/**
* Pages tables
*
* @var object
*/
public static $pages = null;
/**
* Requested page
*
* @var string
*/
public static $requested_page = null;
/**
* Main function
*/
public static function main() {
if (BACKEND == false) {
$pages = new Table('pages');
Pages::$pages = $pages;
$page = Pages::pageLoader();
Pages::$page = $page;
}
}
/**
* Page loader
*
* @param boolean $return_data data
* @return array
*/
public static function pageLoader($return_data = true) {
$requested_page = Pages::lowLoader(Uri::segments());
Pages::$requested_page = $requested_page;
return Pages::$pages->select('[slug="'.$requested_page.'"]', null);
}
/**
* Load current page
*
* @global string $defpage default page
* @param array $data uri
* @return string
*/
public static function lowLoader($data) {
$defpage = Option::get('defaultpage');
// If data count 2 then it has Parent/Child
if (count($data) >= 2) {
// If exists parent file
if (count(Pages::$pages->select('[slug="'.$data[0].'"]')) !== 0) {
// Get child file and get parent page name
$child_page = Pages::$pages->select('[slug="'.$data[1].'"]', null);
// If child page parent is not empty then get his parent
if (count($child_page) == 0) {
$c_p = '';
} else {
if ($child_page['parent'] != '') {
$c_p = $child_page['parent'];
} else {
$c_p = '';
}
}
// Check is child_parent -> request parent
if ($c_p == $data[0]) {
// Checking only for the parent and one child, the remaining issue 404
if (count($data) < 3) {
$id = $data[1]; // Get real request page
} else {
$id = 'error404';
Response::status(404);
}
} else {
$id = 'error404';
Response::status(404);
}
} else {
$id = 'error404';
Response::status(404);
}
} else { // Only parent page come
if(empty($data[0])) {
$id = $defpage;
} else {
// Get current page
$current_page = Pages::$pages->select('[slug="'.$data[0].'"]', null);
if (count($current_page) != 0) {
if ($current_page['parent'] != '') {
$c_p = $current_page['parent'];
} else {
$c_p = '';
}
} else {
$c_p = '';
}
// Check if this page has parent
if ($c_p !== '') {
if ($c_p == $data[0]) {
if (count(Pages::$pages->select('[slug="'.$data[0].'"]', null)) != 0) {
if (($current_page['status'] == 'published') or (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor')))) {
$id = $data[0];
} else {
$id = 'error404';
Response::status(404);
}
} else {
$id = 'error404';
Response::status(404);
}
} else {
$id = 'error404';
Response::status(404);
}
} else {
if (count(Pages::$pages->select('[slug="'.$data[0].'"]', null)) != 0) {
if (($current_page['status'] == 'published') or (Session::exists('user_role') && in_array(Session::get('user_role'), array('admin', 'editor')))) {
$id = $data[0];
} else {
$id = 'error404';
Response::status(404);
}
} else {
$id = 'error404';
Response::status(404);
}
}
}
}
// Return page name/id to load
return $id;
}
/**
* Get pages template
*
* @return string
*/
public static function template() {
if (Pages::$page['template'] == '') return 'index'; else return Pages::$page['template'];
}
/**
* Get pages contents
*
* @return string
*/
public static function content() {
return Text::toHtml(File::getContent(STORAGE . DS . 'pages' . DS . Pages::$page['id'] . '.page.txt'));
}
/**
* Get pages title
*
* <code>
* echo Page::title();
* </code>
*
* @return string
*/
public static function title() {
return Pages::$page['title'];
}
/**
* Get pages Description
*
* <code>
* echo Page::description();
* </code>
*
* @return string
*/
public static function description() {
return Pages::$page['description'];
}
/**
* Get pages Keywords
*
* <code>
* echo Page::keywords();
* </code>
*
* @return string
*/
public static function keywords() {
return Pages::$page['keywords'];
}
}
class Page extends Pages {
/**
* Get date of current page
*
* <code>
* echo Page::date();
* </code>
*
* @return string
*/
public static function date() {
return Date::format(Pages::$page['date'], 'Y-m-d');
}
/**
* Get author of current page
*
* <code>
* echo Page::author();
* </code>
*
* @return string
*/
public static function author() {
return Pages::$page['author'];
}
/**
* Get children pages for a specific parent page
*
* <code>
* $pages = Page::children('page');
* </code>
*
* @param string $parent Parent page
* @return array
*/
public static function children($parent) {
return Pages::$pages->select('[parent="'.(string)$parent.'"]', 'all');
}
/**
* Get the available children pages for requested page.
*
* <code>
* echo Page::available();
* </code>
*
*/
public static function available() {
$pages = Pages::$pages->select('[parent="'.Pages::$requested_page.'"]', 'all');
// Display view
View::factory('box/pages/views/frontend/available_pages')
->assign('pages', $pages)
->display();
}
/**
* Get page breadcrumbs
*
* <code>
* echo Page::breadcrumbs();
* </code>
*
*/
public static function breadcrumbs() {
$current_page = Pages::$requested_page;
if ($current_page !== 'error404') {
$page = Pages::$pages->select('[slug="'.$current_page.'"]', null);
if (trim($page['parent']) !== '') {
$parent = true;
$parent_page = Pages::$pages->select('[slug="'.$page['parent'].'"]', null);
} else {
$parent = false;
}
// Display view
View::factory('box/pages/views/frontend/breadcrumbs')
->assign('current_page', $current_page)
->assign('page', $page)
->assign('parent', $parent)
->assign('parent_page', $parent_page)
->display();
}
}
/**
* Get page url
*
* <code>
* echo Page::url();
* </code>
*
*/
public static function url() {
return Option::get('siteurl').Pages::$page['slug'];
}
/**
* Get page slug
*
* <code>
* echo Page::slug();
* </code>
*
*/
public static function slug() {
return Pages::$page['slug'];
}
/**
* Get page meta robots
*
* <code>
* echo Page::robots();
* </code>
*
*/
public static function robots() {
return (Pages::$page !== null) ? Pages::$page['robots_index'].', '.Pages::$page['robots_follow'] : '';
}
}

View File

@@ -0,0 +1,133 @@
<div class="row-fluid">
<div class="span12">
<h2><?php echo __('New page', 'pages'); ?></h2>
<br />
<?php if (Notification::get('success')) Alert::success(Notification::get('success')); ?>
<?php if (isset($errors['pages_empty_name']) or isset($errors['pages_exists'])) $error_class1 = 'error'; else $error_class1 = ''; ?>
<?php if (isset($errors['pages_empty_title'])) $error_class2 = 'error'; else $error_class2 = ''; ?>
<?php
echo (
Form::open(null, array('class' => 'form-horizontal'))
);
?>
<?php echo (Form::hidden('csrf', Security::token())); ?>
<?php
echo (
Form::label('page_name', __('Name (slug)', 'pages'))
);
?>
<?php
echo (
Form::input('page_name', $post_name, array('class' => 'span6'))
);
if (isset($errors['pages_empty_name'])) echo Html::nbsp(3).'<span style="color:red">'.$errors['pages_empty_name'].'</span>';
if (isset($errors['pages_exists'])) echo Html::nbsp(3).'<span style="color:red">'.$errors['pages_exists'].'</span>';
?>
<?php
echo (
Html::br(2).
Form::label('page_title', __('Title', 'pages'))
);
?>
<?php
echo (
Form::input('page_title', $post_title, array('class' => 'span6'))
);
if (isset($errors['pages_empty_title'])) echo Html::nbsp(3).'<span style="color:red">'.$errors['pages_empty_title'].'</span>';
?>
<?php
echo (
Html::br(2).
Form::label('page_description', __('Description', 'pages')).
Form::input('page_description', $post_description, array('class' => 'span8')).
Html::br(2).
Form::label('page_keywords', __('Keywords', 'pages')).
Form::input('page_keywords', $post_keywords, array('class' => 'span8'))
);
?>
<br /><br />
<?php Action::run('admin_editor', array(Html::toText($post_content))); ?>
<br />
<div class="row-fluid">
<div class="span4">
<?php
echo (
Form::label('pages', __('Parent', 'pages')).
Form::select('pages', $pages_array, $parent_page)
);
?>
</div>
<div class="span4">
<?php
echo (
Form::label('templates', __('Template', 'pages')).
Form::select('templates', $templates_array, $post_template)
);
?>
</div>
<div class="span4">
<?php
echo (
Form::label('status', __('Status', 'pages')).
Form::select('status', $status_array, 'published')
);
?>
</div>
</div>
<hr>
<div class="row-fluid">
<div class="span8">
<?php
echo (
Form::label(__('Published on', 'pages'), __('Published on', 'pages')).
Form::input('year', $date[0], array('class' => 'input-mini')). ' ' .
Form::input('month', $date[1], array('class' => 'input-mini')). ' ' .
Form::input('day', $date[2], array('class' => 'input-mini')). ' <span style="color:gray;">@</span> '.
Form::input('minute', $date[3], array('class' => 'input-mini')). ' : '.
Form::input('second', $date[4], array('class' => 'input-mini'))
);
?>
</div>
<div class="span3">
<?php
echo (
Form::label('robots', __('Search Engines Robots', 'pages')).
'no Index'.Html::nbsp().Form::checkbox('robots_index', 'index', $post_robots_index).Html::nbsp(2).
'no Follow'.Html::nbsp().Form::checkbox('robots_follow', 'follow', $post_robots_follow)
);
?>
</div>
</div>
<hr>
<?php
echo (
Form::submit('add_page_and_exit', __('Save and exit', 'pages'), array('class' => 'btn')).Html::nbsp(2).
Form::submit('add_page', __('Save', 'pages'), array('class' => 'btn')).
Form::close()
);
?>
</div>
</div>

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